views:

48

answers:

1

Hi all! I have an object which conforms to the NSCoding protocol.

The object contains a method to save itself to memory, like so:

- (void)saveToFile {
 NSMutableData *data = [[NSMutableData alloc] init];
 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
 [archiver encodeObject:self forKey:kDataKey];
 [archiver finishEncoding];
 [data writeToFile:[self dataFilePath] atomically:YES];
 [archiver release];
 [data release];
}

This works just fine. But I would also like to initialise an empty version of this object and then call its own 'Load' method to load whatever data exists on file into its variables. So I've created the following:

- (void)loadFromFile {
 NSString *filePath = [self dataFilePath];
 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
  NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  self = [unarchiver decodeObjectForKey:kDataKey];
  [unarchiver finishDecoding];
 } 
}

Now this second method doesn't manage to load any variables. Is this line not possible perhaps?

self = [unarchiver decodeObjectForKey:kDataKey];

Ultimately I would like to use the code like this:

One viewController takes user entered input, creates an object and saves it to memory using

[anObject saveToFile];

And a second viewController creates an empty object, then initialises its values to those stored on file by calling:

[emptyObject loadFromFile];

Any suggestions on how to make this work would be hugely appreciated. Thanks :)

Michael

+1  A: 

Why don't you use initWithCoder: instead? It should return you an object initialized with a given coder. Since your object conforms to NSCoding, this shouldn't be an issue.

pgb
Thanks for the fast reply! Doesn't the method decodeObjectForKey: automatically use my initWithCoder: method when it tries to decode the saved data? So I don't need to call it explicitly? Hence the line:self = [unarchiver decodeObjectForKey:kDataKey];Or am I getting this muddled up?
Smikey
It does, but I think the way you are expected to use the protocol is via its `initWithCoder:` message.
pgb
Ok - but the initWithCoder: method needs to be passed an NSCoder object - what do I use for this?
Smikey