OStack程序员社区-中国程序员成长平台

标题: ios - NSCoding:自定义类未归档,但类成员为空/无 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:39
标题: ios - 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)initWithTitleNSString*)tTitle levelNSString*)tLevel stateNSString*)tState visibleBOOL)tVisible linkNSString*)tLink linkTypeNSString*)tLinkType anIdNSString*)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) encodeWithCoderNSCoder *)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)initWithCoderNSCoder *)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 方法中的某个地方一定有错误,但我找不到它,非常感谢任何帮助。



Best Answer-推荐答案


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

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

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

关于ios - NSCoding:自定义类未归档,但类成员为空/无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357285/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4