Search code examples
iphoneloadingencodernscodingdecoder

Can I do this?? Trying to load an object from within itself


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


Solution

  • 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.