自定义NSObject iniWithCoder未调用

时间:2014-06-26 07:46:33

标签: ios nskeyedarchiver nscoding nskeyedunarchiver

我有一个自定义对象LevelContent,其中包含一些属性。 LevelContent符合NSCoding,我已实施encodeWithCoder:initWithCoder:方法。我保存并将数据提取到Parse.com。保存工作正常如下:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.currentLevelContent];

当我获取数据时,我正确地获得了NSData,但是当我尝试使用下载的数据初始化LevelContent时,initWithCoder:永远不会被调用。我尝试使用此加载LevelContent

LevelContent *content = [NSKeyedUnarchiver unarchiveObjectWithData:data];

这是编码/解码的代码

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.tiles forKey:@"tiles"];
    [aCoder encodeObject:self.attributes forKey:@"attributes"];
    [aCoder encodeObject:self.level forKey:@"level"];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self == [super init]) {
        self.tiles = [NSMutableArray array];
        [self.tiles addObjectsFromArray:[aDecoder decodeObjectForKey:@"tiles"]];
        self.attributes = [NSMutableDictionary dictionary];
        [self.attributes addEntriesFromDictionary:[aDecoder decodeObjectForKey:@"attributes"]];
        self.level = [Level levelWithTopIndex:0 detailIndex:0];
        self.level = [aDecoder decodeObjectForKey:@"level"];
    }
    return self;
}

1 个答案:

答案 0 :(得分:1)

if (self == [super init])

中将if (self = [super init])更改为initWithCoder:

试试这个,

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        .....
    }
    return self;
}