Debugging Archiver

347 Views Asked by At

I cannot figure out what is wrong with my archiving and unarchiving. I am trying to save data from a class. The encoder and decoder are:

//archiving
- (void)encodeWithCoder:(NSCoder *)aCoder
{
//encode only certain instance variables
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.location forKey:@"location"]; 


}

- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [self init];
if (self) {
    //decode data
    [self setName:[aDecoder decodeObjectForKey:@"name"]];
    [self setLocation:[aDecoder decodeObjectForKey:@"location"]];

}

return self;

}

The instance variables are properties, and they are values of a custom class. Multiple instances of this class populate an NSMutableArray stored in my main view controller.

My view controller contains the methods:

- (NSString *)itemArchivePath
{
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

//only one document in list - get path t o it
NSString *documentDirectory = [documentDirectories objectAtIndex:0];

return [documentDirectory stringByAppendingString:@"file.archive"];
}

- (BOOL)saveChanges
{
//returns success or failure
NSString *path = [self itemArchivePath];

return [NSKeyedArchiver archiveRootObject:customClassArray //This is the array storing multiple instances of the custom class
                                   toFile:path];
}

The comment about the array is not in the actual code. And finally, the app delegate has the following code:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

BOOL success = [mainViewController saveChanges];
if (success) {
    NSLog(@"Saved Successfully!");
}
else {
    NSLog(@"Unsuccessful");
}

}

Unfortunately, whenever running the code, "unsuccessful" is always logged, and I am not sure why. The mainViewController is an instance variable of the app delegate. I have tried debugging for a very long time, and I cannot find the problem. Any help is appreciated. Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

There's a good chance that the path to which you're trying to save isn't valid. You should try logging it and see whether the value is sane when the save fails. You might also want to look at using stringByAppendingPathComponent: instead of stringByAppendingString:.