ios - 未调用自定义 NSObject iniWithCoder

标签 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;
}

最佳答案

更改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/

相关文章:

ios - UIScrollView 中缺少 UIToolBar

swift - 将对象作为类存储到文件中

ios - 序列化包含对核心数据中 NSManagedObjects 的引用的多维数组

objective-c - 如何使用 NSSecureCoding 来保证集合类的内容?

ios - 如何根据数据量将数据存储在 iPhone/iPad 上?

ios - 不使用 ARC 时替换 __weak

iOS 7/8 : How do I set the Navigation Bar to be pure white (#FFFFFF) and still maintain translucency?

ios - NSKeyedUnarchiver 导致崩溃

ios - 如何在 uiimagepickercontroller 中创建可裁剪的横幅图像?

swift3 - 如何将字典写入文件?