Can I do this?? Trying to load an object from within itself.
Posted
by Smikey
on Stack Overflow
See other posts from Stack Overflow
or by Smikey
Published on 2010-05-13T11:38:23Z
Indexed on
2010/05/13
11:44 UTC
Read the original article
Hit count: 239
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
© Stack Overflow or respective owner