我无法弄清楚为什么我使用NSKeyedArchivers / NSKeyedUnarchivers时应用程序崩溃
|
我正在开发我的第一个iphone \'Diary \'应用程序,该应用程序使用包含NSString标题,NSString文本和NSDate creationDate的自定义\'Entry \'对象。当我尝试存档NSMutableArray of Entry对象,并在下次视图加载时检索它们时,应用程序崩溃。我已经看过一堆使用NSKeyedArchivers的示例代码和示例,但是仍然无法弄清楚为什么会发生这种情况。我猜测保存条目的数组初始化存在问题,但不确定...
这是代码,也许您可以找到我一直监督的内容... \“
//--------- Entry.m---------------
- (id) initWithCoder:(NSCoder *)aDecoder{
if ((self = [super init])) {
self.title = [[aDecoder decodeObjectForKey:@\"title\"] retain];
self.text = [[aDecoder decodeObjectForKey:@\"text\"] retain];
self.created = [[aDecoder decodeObjectForKey:@\"created\"] retain];
}
return self;
}
- (void) encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.title forKey:@\"title\"];
[aCoder encodeObject:self.text forKey:@\"text\"];
[aCoder encodeObject:self.created forKey:@\"created\"];
}
//-------------- Diary View Controller.m
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
- (void) writeDataToArchive {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]
initForWritingWithMutableData:data];
[archiver encodeObject:self.entriesArray forKey:@\"entriesArray\"];
[archiver finishEncoding];
BOOL result = [data writeToFile:[self dataFilePath] atomically:YES];
[archiver release];
[data release];
}
- (void)addItem:sender {
int count = [entriesArray count] +1;
NSString *newEntryTitle = [NSString stringWithFormat:@\"Entry %d\", count];
Entry *anEntry = [[Entry alloc] initWithTitle:newEntryTitle text:@\"-\"
created:[NSDate date]];
[entriesArray addObject:anEntry];
[self.tableView reloadData];
[anEntry release];
[self writeDataToArchive];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *data = [[NSMutableData alloc]
initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]
initForReadingWithData:data];
NSMutableArray *array = [unarchiver decodeObjectForKey:@\"entriesArray\"];
entriesArray = [array mutableCopy];
[array release];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
// ... some other stuff
NSUInteger row = indexPath.row;
Entry *entry = [entriesArray objectAtIndex:row];
cell.textLabel.text = entry.title;
return cell;
}
非常感谢。
没有找到相关结果
已邀请:
2 个回复
完趣镐
中的
,因为您不拥有它。 请检查Cocoa内存管理规则,因为您的代码中还有其他两个内存管理问题。尤其是,
在您的“ 4”方法中,假设属性保留或复制,所有泄漏。
嘘伪
@JeremyP指出了另一个问题。由于您没有分配或保留* array,因此不应释放它。