摘要:当我从<NSCoding>
父级派生自定义类时,我看到在应用程序状态保留期间调用了encodeWithCoder
方法。如果我将父级更改为SKNode
,则不再调用encodeWithCoder
方法。
详细说明:
我的视图控制器在UIKit
应用程序状态保留期间被编码。它编码MyNode
类型的单个对象。
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
[super encodeRestorableStateWithCoder:coder];
MyNode *myNode = [[MyNode alloc] init];
NSLog(@"view controller encoding");
[coder encodeObject:myNode forKey:@"myNode"];
}
MyNode
是为此问题而构建的精简版。我将包含完整性代码,但编码和解码方法仅调用NSLog
和super
。
@interface MyParent : NSObject <NSCoding>
@end
@interface MyNode : MyParent
@end
@implementation MyParent
- (id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"MyParent decoding");
self = [super init];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
NSLog(@"MyParent encoding");
}
@end
@implementation MyNode
- (id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"MyNode decoding");
self = [super initWithCoder:aDecoder];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
NSLog(@"MyNode encoding");
[super encodeWithCoder:aCoder];
}
@end
当MyNode
的父级是MyParent
时,如上所述,我在应用程序保留期间看到了我的记录输出:
2014-05-12 15:22:33.342 Flippy[35091:60b] saving application state
2014-05-12 15:22:33.342 Flippy[35091:60b] view controller encoding
2014-05-12 15:22:33.343 Flippy[35091:60b] MyNode encoding
2014-05-12 15:22:33.343 Flippy[35091:60b] MyParent encoding
但是当我将MyNode
的父级更改为SKNode
时,我的encodeWithCoder
实现不会被调用:
2014-05-12 15:22:57.847 Flippy[35115:60b] saving application state
2014-05-12 15:22:57.848 Flippy[35115:60b] view controller encoding
为什么不呢?
我尝试过的事情:
NSKeyedArchiver
存档我的自定义类。这可以按预期工作。UIStateRestoring
协议,并使用具有恢复标识符的应用程序注册它。这对我来说没什么意义。classForCoder
混淆,与this question一样。但它听起来并不适用,并且classForCoder
无法在我的自定义类中调用。(启发此测试案例的我的现实问题的详细信息似乎并不重要。)