【发布时间】:2014-09-12 05:39:48
【问题描述】:
是否可以获取存储在 Core Data 中的文件的路径,还是只能提取文件本身?我需要在 Core Data 中存储为 NSData 属性的文件的路径,而不是数据库本身。一些 iOS 功能通常需要一个 NSURL 而不是文件本身,我还没有弄清楚如何将它与 Core Data 结合起来。
【问题讨论】:
是否可以获取存储在 Core Data 中的文件的路径,还是只能提取文件本身?我需要在 Core Data 中存储为 NSData 属性的文件的路径,而不是数据库本身。一些 iOS 功能通常需要一个 NSURL 而不是文件本身,我还没有弄清楚如何将它与 Core Data 结合起来。
【问题讨论】:
如果您使用 SQLite,则数据库中没有“文件”。数据库是单个文件。
如果您将二进制数据存储在数据库中,则无法直接访问其下的文件(甚至假设您使用外部存储作为选项)。
如果您想在 Core Data 下直接访问 SQLite 数据库中的某些内容,那么您需要自己将其写入另一个文件。
【讨论】:
这是获取相关 NSURL 的方法:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @"YOUR_DATABASE_NAME";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
要在更宏大的背景下查看它,这通常是您设置 UIManagedDocument 以使用 Core Data 的方式:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @"YOUR_DATABASE_NAME";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
self.document = [[UIManagedDocument alloc] initWithFileURL:url];
BOOL fileExists = [fileManager fileExistsAtPath:[url path]];
if (fileExists) {
[self.document openWithCompletionHandler:^(BOOL success) {
if (success) {
self.context = self.document.managedObjectContext;
// Post notification so others can gather the document and context
[[NSNotificationCenter defaultCenter] postNotificationName:@"DatabaseReady"
object:self];
}
if (!success) NSLog(@"couldn't open file at %@", url);
}];
} else {
[self.document saveToURL:url
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) {
self.context = self.document.managedObjectContext;
// Post notification so others can gather the document and context
[[NSNotificationCenter defaultCenter] postNotificationName:@"DatabaseReady"
object:self];
}
if (!success) NSLog(@"couldn't open file at %@", url);
}];
}
【讨论】:
nameOfManagedObject.objectID.URIRepresentation 获取它所包含的对象的路径。更新第一篇文章以使其更清晰。