我有一个自定义对象 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;
}
最佳答案
更改if (self == [super init])
至 if (self = [super init])
在 initWithCoder:
试试这个,
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
.....
}
return self;
}
关于ios - 未调用自定义 NSObject iniWithCoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24425050/