我想归档我的自定义对象。ClassA 拥有一个字典,其值是 ClassB 的实例。
一切看起来都不错 ClassA 的 initWithCoder,并且声明了 _dictionary strong
,但是在 init 返回并且我调用callMeAfterInit
之后,_dictionary 是空的(不是 null,一个有效的空字典)。
这应该很简单,但我没有太多使用存档,所以也许我缺少一些基本的东西。什么可能导致 init 返回后字典被清空?
这是基本代码:
@interface ClassA : NSObject <NSCoding>
@property (strong, nonatomic) NSMutableDictionary *dictionary;
@end
@implementation ClassA
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.dictionary forKey:@"dictionary"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
_dictionary = [decoder decodeObjectForKey:@"dictionary"];
// breakpoint here and I can inspect a good dictionary, full of ClassB values
}
return self;
}
- (void)callMeAfterInit {
NSLog(@"%@", self.dictionary);
// Log output here shows an empty dictionary (valid, but with 0 pairs)
}
@end
@interface ClassB : NSObject <NSCoding>
@property (strong, nonatomic) NSNumber *number;
@property (strong, nonatomic) NSArray *array;
@end
@implementation ClassB
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.number forKey:@"number"];
[encoder encodeObject:self.array forKey:@"array"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
_number = [decoder decodeObjectForKey:@"number"];
_array = [decoder decodeObjectForKey:@"array"];
}
return self;
}
@end