我在我的应用程序中使用iTunes文件共享,并且需要将Core Data的sqlite数据库放在别处,以便用户不会使用它。我已阅读a previous SO post关于隐藏Core Data使用的sqlite文件的最佳方法。
关于是否将数据库放在Library / Preferences或名为.data
的目录中似乎存在矛盾的意见,但我认为我同意最好的方法是使用.data
目录。 / p>
目前,核心数据模板代码提供了-applicationDocumentsDirectory
方法:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
我想实现一个名为applicationHiddenDocumentsDirectory
的函数,它可以让我访问“.data”子目录,但我不太了解Objective-C或Cocoa / Foundation框架来访问目录。
有人可以帮我实现这个方法吗?
谢谢!
==罗文==
答案 0 :(得分:14)
- (NSString *)applicationHiddenDocumentsDirectory {
// NSString *path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@".data"];
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [libraryPath stringByAppendingPathComponent:@"Private Documents"];
BOOL isDirectory = NO;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory]) {
if (isDirectory)
return path;
else {
// Handle error. ".data" is a file which should not be there...
[NSException raise:@".data exists, and is a file" format:@"Path: %@", path];
// NSError *error = nil;
// if (![[NSFileManager defaultManager] removeItemAtPath:path error:&error]) {
// [NSException raise:@"could not remove file" format:@"Path: %@", path];
// }
}
}
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
// Handle error.
[NSException raise:@"Failed creating directory" format:@"[%@], %@", path, error];
}
return path;
}
答案 1 :(得分:5)
当新的CoreData模板返回NSURL对象而不是NSString路径时,这是我上面代码的更新版本:
- (NSURL *)applicationHiddenDocumentsDirectory {
// NSString *path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@".data"];
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [libraryPath stringByAppendingPathComponent:@"Private Documents"];
NSURL *pathURL = [NSURL fileURLWithPath:path];
BOOL isDirectory = NO;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory]) {
if (isDirectory) {
return pathURL;
} else {
// Handle error. ".data" is a file which should not be there...
[NSException raise:@"'Private Documents' exists, and is a file" format:@"Path: %@", path];
// NSError *error = nil;
// if (![[NSFileManager defaultManager] removeItemAtPath:path error:&error]) {
// [NSException raise:@"could not remove file" format:@"Path: %@", path];
// }
}
}
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
// Handle error.
[NSException raise:@"Failed creating directory" format:@"[%@], %@", path, error];
}
return pathURL;
}