我已经看过How do I create a global UIManagedDocument instance per document-on-disk shared by my whole application using blocks?,但我真的不明白。
我想要实现的是整个应用程序应该只有一个UIManagedDocument - 一个核心数据库。不同的对象应该调用一个方法并获得唯一的UIManagedDocument。
我使用带有类方法的辅助类:
+ (UIManagedDocument *)getsharedDatabase:(NSString *)databaseName
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:databaseName];
// url is now "<Documents Directory>/<databaseName>"
if (![[NSFileManager defaultManager] fileExistsAtPath:[url absoluteString]])
{
// does not exist on disk, so create one
UIManagedDocument *managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
return managedDocument;
}
else
{
UIManagedDocument *managedDocument = **?????**
return managedDocument;
}
}
正如您在问号中所看到的,我不知道如何获取现有文件。我检查了UIManagedDocument类引用但找不到它。
你能帮助我吗? 非常感谢提前。修改的 我想知道......单身方法怎么样,如:
+ (UIManagedDocument *) sharedDatabase
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"databaseName"];
// url is now "<Documents Directory>/databaseName"
static UIManagedDocument *managedDocument = nil;
static dispatch_once_t mngddoc;
dispatch_once(&mngddoc, ^{
managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
});
return managedDocument;
}
答案 0 :(得分:0)
如果磁盘上存在UIManagedDocuments,则需要在目录中搜索匹配的文件。通常,文件将具有一些标识属性,如公共文件扩展名。
这样的事情:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSURL *appDirectoryURL = [appDelegate applicationDocumentsDirectory];
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:appDirectoryURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
for (NSURL *fileURL in directoryContents) {
NSString *documentExtension = [fileURL pathExtension];
if ([documentExtension isEqualToString:@"myfileextension"]) {
}
}