3

I've spent the past few hours trying to figure this out, but I've ran out of ideas.

All I'm trying to do is archive an object, but the method archiveRootObject keeps on returning NO

Here's my code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"MyAppCache"];
NSString *fullPath = [cacheDirectory stringByAppendingPathComponent:@"archive.data"];

if(![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
    [[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
}

NSArray *array = [NSArray arrayWithObjects:@"hello", @"world", nil];
NSLog(@"Full Path: %@", fullPath);
BOOL res = [NSKeyedArchiver archiveRootObject:array toFile:fullPath];

if(res){
    NSLog(@"YES");
}else{
    NSLog(@"NO");
}

Every time time I run this, it prints NO.

Any help would be appreciated!

Khon Lieu
  • 4,295
  • 7
  • 37
  • 39

2 Answers2

6

You create a directory with the path fullPath and then you try to write the file at the same path. Overwriting a directory with a file like this is not possible. Use your cacheDirectory string to create your directory.

Sven
  • 22,475
  • 4
  • 52
  • 71
1

NSString *cacheDirectory is not a mutable string and after you init it, you attempt to modify it so you are writing to the top-level directory.

For a quick fix, try:

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,   NSUserDomainMask, YES);
NSString *documentPath = ([documentPaths count] > 0) ? [documentPaths objectAtIndex:0] : nil;
NSString *documentsResourcesPath = [documentPath  stringByAppendingPathComponent:@"MyAppCache"];

NSString *fullPath = [documentsResourcesPath stringByAppendingPathComponent:@"archive.data"];
JimP
  • 87
  • 5
  • 1
    Thanks for your suggestion Jim, I tried your suggestion but it didn't work. Turns out Sven found the bug. My code is trying to overwrite a directory with a file. – Khon Lieu Jan 14 '13 at 21:36
  • Well, my code works but I neglected to change the create directory code to use the correct iVAR. if(![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){ [[NSFileManager defaultManager] createDirectoryAtPath:documentsResourcesPath withIntermediateDirectories:YES attributes:nil error:nil]; Good luck and best regards, Jim – JimP Jan 14 '13 at 21:53
  • This worked for me when saving data though how would you load data from this? Thanks in advance. – uplearned.com Aug 10 '14 at 23:00