NSKeyedArchiverRootObject archive returns NO

I spent the last few hours trying to figure it out, but I ran out of ideas.

All I'm trying to do is archive the object, but the archiveRootObject method continues to return NO

Here is 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 I run this, it prints NO .

Any help would be appreciated!

+2
source share
2 answers

You create a directory with the fullPath , and then try to write the file in the same way. It is not possible to overwrite a directory with such a file. Use the cacheDirectory line to create your directory.

+6
source

NSString * cacheDirectory is not a mutable string, and after you initialize it, you try to change it to write 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"]; 
+1
source

Source: https://habr.com/ru/post/973801/


All Articles