【问题标题】:How do I share one UIManagedDocument between different objects?如何在不同对象之间共享一个 UIManagedDocument?
【发布时间】:2012-03-14 20:41:33
【问题描述】:

我已经看过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;
}

【问题讨论】:

  • 您的单例方法看起来是可行的方法。您可以将 url 创建代码移动到 dispatch_once 中以对其进行优化。
  • 太好了,谢谢,在应得的地方给予赞扬:科林·惠勒是我的灵感 - stackoverflow.com/a/2200751/1096476

标签: iphone ipad core-data ios5 uimanageddocument


【解决方案1】:

如果磁盘上有现有的 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"]) {
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多