2

我想保留一个 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 方法中的某个地方一定有错误,但我找不到它,非常感谢任何帮助。

4

1 回答 1

1

实现initWithCoder:方法时,需要正确调用super:

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

正在取消归档的实例具有更多属性,而不仅仅是特定类中的添加。您也不想检查与 的相等性self,您想分配给self

于 2013-08-21T12:46:49.040 回答