Store coredata file outside of documents directory?

后端 未结 1 803
礼貌的吻别
礼貌的吻别 2021-01-14 23:13

I allow itunes sharing in my application but I noticed that the coredata create sqlite in the document directory

can I change the save of this file to library , if

相关标签:
1条回答
  • 2021-01-14 23:51

    this is possible. I made a little helper method which creates a path that is not accessible through itunes. The database will be stored in the library directory, which is included in itunes back ups.

    - (NSString *)applicationPrivateDocumentsDirectory {
        static NSString *path;
        if (!path) {
            NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
            path = [libraryPath stringByAppendingPathComponent:@"Private Documents"];
            BOOL isDirectory;
            if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory]) {
                NSError *error = nil;
                if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
                    NSLog(@"Can't create directory %@ [%@]", path, error);
                    abort(); // replace with proper error handling
                }
            }
            else if (!isDirectory) {
                NSLog(@"Path %@ exists but is no directory", path);
                abort(); // replace with error handling
            }
        }
        return path;
    } 
    

    and then you would replace

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"SomeApp.sqlite"];
    

    in the - (NSPersistentStoreCoordinator *)persistentStoreCoordinator method with:

    NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationPrivateDocumentsDirectory] stringByAppendingPathComponent:@"SomeApp.sqlite"]];
    
    0 讨论(0)
提交回复
热议问题