所以我有一个对象,我在其中实现了 NS Coding。我整天都在为此绞尽脑汁。据我了解,因为我已经实现了 NSCoding,所以当在数组本身上调用归档/取消归档方法时,应该对数组的索引进行编码和解码。因此,要么我对它的工作原理的理解不正确,要么我的实现中有一些错误。
文件被写入,数组被反序列化并显示其中有一个对象。但是数组中的类没有数据。
实现如下所示:
#pragma mark NSCoding
#define kTitle @"Title"
#define kDescription @"Description"
#define kIsCompleted @"IsCompleted"
#define kDate @"Date"
#define kImage @"Image"
-(id)initWithCoder:(NSCoder *)decoder
{
[super init];
title = [decoder decodeObjectForKey:kTitle];
description = [decoder decodeObjectForKey:kDescription];
isCompleted = [decoder decodeBoolForKey:kIsCompleted];
date = [decoder decodeObjectForKey:kDate];
image = [decoder decodeObjectForKey:kImage];
return self;
}
-(void) encodeWithCoder:(NSCoder *) encoder
{
[encoder encodeObject:title forKey:kTitle];
[encoder encodeObject:description forKey:kDescription];
[encoder encodeBool:isCompleted forKey:kIsCompleted];
[encoder encodeObject:date forKey:kDate];
[encoder encodeObject:image forKey:kImage];
}
@end
编码看起来像这样,有一些故障排除更改:
-(void) writeFile
{
NSData *encodedObject;
encodedObject = [NSKeyedArchiver archivedDataWithRootObject: bucketItems];
//NSFileHandle *file;
// file = [NSFileHandle fileHandleForWritingAtPath:filePath];
//if(true)//file == nil)
//{
//NSLog(@"Failed to open a file handle for writing. Attempting to create a file.");
//[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
//file = [NSFileHandle fileHandleForWritingAtPath:filePath];
//if(file == nil)
//{
// NSLog(@"Unable to create new file.");
// }
//}
[encodedObject writeToFile:self.filePath atomically:YES];
//[file writeData: encodedObject];
//[file closeFile];
}
然后解码发生在这里,程序启动,检查是否有保存的数据,并加载它
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *fileData;
fileData = [file readDataToEndOfFile];
bucketItems = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
NSLog(@"Data file found: loading");
[file closeFile];