【问题标题】:Custom NSObject iniWithCoder not called未调用自定义 NSObject iniWithCoder
【发布时间】:2014-06-26 07:46:33
【问题描述】:

我有一个自定义对象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;
}

【问题讨论】:

    标签: ios nskeyedarchiver nscoding nskeyedunarchiver


    【解决方案1】:

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

    试试这个,

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

    【讨论】:

    • 不幸的是,这不起作用。 InitWithCoder:仍然不会被调用。
    • 检查是否设置断点或登录initWithCoder: 以确保它不会被调用。
    • 我在 initWithCoder: 方法中放置了断点,并且我已经确认它没有被触发
    • 你确定data 不为零吗?
    • 是的,打印data输出135个字节,在save方法打印时也是这样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多