我想存档我的自定义对象。 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
最佳答案
您没有显示调用 callMeAfterInit
的代码,因此这是猜测。
很可能,您没有与 ClassA
的同一个实例进行对话。您是否碰巧在某处调用了[[ClassA alloc] init];
?
关于iphone - NSCoding 和 ARC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17219633/