2

摘要:当我从父类派生自定义类时<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是为这个问题构建的精简类。为了完整起见,我将包含代码,但 encode 和 decode 方法仅调用NSLogand 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当is的父级时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

但是当我将父级更改为MyNodetoSKNode时,我的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,就像在这个问题中一样。但这听起来并不适用,并且classForCoder无论如何都不会在我的自定义类上被调用。

(启发这个测试用例的现实问题的细节似乎并不相关。)

4

0 回答 0