NSCoding:自定义类未归档,但具有空/零类成员

时间:2013-08-21 12:21:11

标签: ios objective-c nscoding

我想要保留一个NSDictionary,填充自定义对象到光盘:

     NSDictionary *menuList = [[NSMutableDictionary alloc]initWithDictionary:xmlParser.items];
     //here the "Menu List"`s Object are filled correctly

     //persisting them to disc:
     NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
     NSString *directory = [paths objectAtIndex:0];
     NSString *fileName = [NSString stringWithUTF8String:MENU_LIST_NAME];
     NSString *filePath = [directory stringByAppendingPathComponent:fileName];

     //saving using NSKeyedArchiver
     NSData* archiveData = [NSKeyedArchiver archivedDataWithRootObject:menuList];
     [archiveData writeToFile:filePath options:NSDataWritingAtomic error:nil];

     //here the NSDictionary has the correct amount of Objects, but the Objects` class members are partially empty or nil
     NSData *data = [NSData dataWithContentsOfFile:filePath];
     NSDictionary *theMenu = (NSDictionary*)[NSKeyedUnarchiver unarchiveObjectWithData:data];

这里是自定义对象的.m(存储在NSDictionary中的对象类型)

- (id)initWithTitle:(NSString*)tTitle level:(NSString*)tLevel state:(NSString*)tState visible:(BOOL)tVisible link:(NSString*)tLink linkType:(NSString*)tLinkType anId:(NSString*)tId {
if ((self = [super init])) {
    self.anId = tId;
    self.title = tTitle;
    self.level = tLevel;
    self.state = tState;
    self.visible = tVisible;
    self.link = tLink;
    self.linkType = tLinkType;
 }
 return self;
 }


 - (void) encodeWithCoder:(NSCoder *)encoder {
 [encoder encodeObject:self.anId forKey:@"anId"];
 [encoder encodeObject:self.level forKey:@"level"];
 [encoder encodeObject:self.state forKey:@"state"];
 [encoder encodeBool:self.visible forKey:@"visible"];
 [encoder encodeObject:self.title forKey:@"title"];
 [encoder encodeObject:self.link forKey:@"link"];
 [encoder encodeObject:self.linkType forKey:@"linkType"];
 }

 - (id)initWithCoder:(NSCoder *)decoder {

 if(self == [super init]){
    self.anId = [decoder decodeObjectForKey:@"anId"];
    self.level = [decoder decodeObjectForKey:@"level"];
    self.state = [decoder decodeObjectForKey:@"state"];
    self.visible = [decoder decodeBoolForKey:@"visible"];
    self.title = [decoder decodeObjectForKey:@"title"];
    self.link = [decoder decodeObjectForKey:@"link"];
    self.linkType = [decoder decodeObjectForKey:@"linkType"];

}

return self;
 }
 @end

我不知道为什么对象被正确归档,但是对象的成员在某处丢失了。我假设NSCoding方法中某处肯定存在错误,但我无法找到它,任何帮助都非常感激。

1 个答案:

答案 0 :(得分:1)

当您实施initWithCoder:方法时,您需要正确调用super:

if (self = [super initWithCoder:decoder]) {

正在取消归档的实例具有的属性多于您在特定类中添加的属性。您也不希望检查与self的平等,您希望分配给self