I cannot seem to get NSKeyedArchiver
working. I have a main ViewController
, which has an NSMutableArray
as an instance variable. The array is populated by multiple instances of a custom class. The custom class conforms to the NSCoding
protocol and implements both the encoding and decoding methods. From the main view controller, I call
- (NSString *)itemArchivePath
{
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//only one document in list - get path t o it
NSString *documentDirectory = [documentDirectories firstObject];
return [documentDirectory stringByAppendingString:@"locations.archive"];
}
- (BOOL)saveChanges
{
//returns success or failure
NSString *path = [self itemArchivePath];
return [NSKeyedArchiver archiveRootObject:myArray //this is the array to archive
toFile:path];
}
In the app delegate, I call the saveChanges method for applicationDidEnterBackground. The method returns true on the simulator, but false for the actual device. I am not sure what to do. Any help is appreciated. Thanks!
EDIT: Based on Zaph's comment, I have changed the saveChanges method to:
- (void)saveChanges
{
//returns success or failure
NSString *path = [self itemArchivePath];
NSData *dataOfArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];
NSFileManager *checker = [NSFileManager defaultManager];
[dataOfArray writeToFile:path
atomically:YES];
if ([checker fileExistsAtPath:path]) {
NSLog(@"Archive Successful");
}
else {
NSLog(@"Archive Did Not Work");
}
}
NSLog the path! It is probably wrong as @Wolfgang states.
[documentDirectory stringByAppendingString:@"locations.archive"]
will not add a "/" between the path and filename. use:
[documentDirectory stringByAppendingPathComponent:@"locations.archive"]
When code does not work make it as simple as possible, break up compound statements into individual statements. Then follow along with the debugger and/or NSLog()
statements checking every step.