Reputation: 691
I am trying to use NSCoding to save and recover application state. I haven't used it before.
In my app, the protocol methods encodeWithCoder and initWithCoder are never being called. I have prepared a simple test case with the same problem so hopefully somebody can tell me what I am doing wrong.
Here is my CodingTest.h file:
#import <Foundation/Foundation.h>
@interface CodingTest : NSObject <NSCoding>
- (void) saveData;
- (void) loadData;
- (id) init: (int) testValue;
@end
Here is 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
I call it as follows:
CodingTest *testCase = [[CodingTest alloc] init:27];
[testCase saveData ];
[testCase loadData];
init, saveData and loadData are all being called. But encodeWithEncoder and initWithCoder are never called. What am I doing wrong?
Upvotes: 0
Views: 408
Reputation: 691
The problem is that "testfile" on its own is not a valid filename. If this is changed to "tmp/testfile" it works fine.
Interestingly, if you get the file name wrong on encode, it won't call the decode function, even though the decode call doesn't specify the file name.
Upvotes: 1