ios nsCoding设置但不调用encodeWithCoder

时间:2015-02-15 08:02:51

标签: ios

我正在尝试使用NSCoding来保存和恢复应用程序状态。我之前没用过它。

在我的应用程序中,从不调用协议方法encodeWithCoder和initWithCoder。我准备了一个具有相同问题的简单测试用例,所以希望有人可以告诉我我做错了什么。

这是我的CodingTest.h文件:

#import <Foundation/Foundation.h>

@interface CodingTest : NSObject <NSCoding>
- (void) saveData;
- (void) loadData;
- (id) init: (int) testValue;

@end

这是CodingTest.m

#import "CodingTest.h"
@interface CodingTest()
@property int testInt;
@end

@implementation CodingTest
- (id) init: (int) testValue
{
  _testInt = testValue;
  return self;
}

-(void) loadData
{
  CodingTest *newTestClass = [NSKeyedUnarchiver unarchiveObjectWithFile:@"testfile"];
}

-(void) saveData
{
  [NSKeyedArchiver archiveRootObject:self toFile:@"testfile"];
}

- (void) encodeWithCoder:(NSCoder *)encoder {
  [encoder encodeInt:_testInt forKey:@"intValue"];
}

- (id)initWithCoder:(NSCoder *)decoder {   
  int oldInt = [decoder decodeIntForKey:@"intValue"];
  return [self init:oldInt];
}

@end

我称之为:

CodingTest *testCase = [[CodingTest alloc] init:27];
  [testCase saveData ];
  [testCase loadData];

init,saveData和loadData都被调用。但是从不调用encodeWithEncoder和initWithCoder。我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是“testfile”本身不是有效的文件名。如果将其更改为“tmp / testfile”,则可以正常工作。

有趣的是,如果你在编码时得到文件名错误,它就不会调用解码函数,即使解码调用没有指定文件名。