1

学习使用 coreData。目前正在看斯坦福的CS193P Lecture 14,很有帮助。我已经使用 ManagedDocument 成功设置了一个具有核心数据持久性的工作应用程序。

每次应用启动时都会运行以下代码。我的困惑是:我们怎么知道文档的 url 是正确的?它怎么知道“lastObject”总是保存文档的 URL?

if (!myManagedDocument) {        
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"theDatabase"];
    myManagedDocument = [[UIManagedDocument alloc]initWithFileURL:url];
}

下面的代码将打开文档,如果之前没有保存过,则创建/保存它。

if (![[NSFileManager defaultManager] fileExistsAtPath:[myManagedDocument.fileURL path]]) {
        [myManagedDocument saveToURL:myManagedDocument.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL sucess) {
            [self getInfoFromDatabase];
        }];
    } else if (myManagedDocument.documentState == UIDocumentStateClosed) {
        [myManagedDocument openWithCompletionHandler:^(BOOL sucess) {
            [self getInfoFromDatabase];
        }];
    } else if (myManagedDocument.documentState == UIDocumentStateNormal) {
        [self getInfoFromDatabase];
    }
4

1 回答 1

2

根据directoryanddomainMask参数,URLsForDirectory可以返回多个 URL 的数组。例如,在 OS X 上,

NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSAllDomainsMask];

返回

(
file://localhost/Users/<用户>/Library/Application%20Support/,
文件://localhost/Library/Application%20Support/,
文件://localhost/网络/库/Application%20Support/
)

但在你的情况下,在 iOS 上,

NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

返回一个恰好包含一个URL的数组,它是应用程序沙箱内的文档目录。在模拟器上,这看起来像

(
file://localhost/Users/<user>/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/AAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE/Documents/
)

因此,无论您采用该数组的第一个对象还是最后一个对象都没有关系。该代码只是假设托管文档保存在应用程序沙箱文档目录中。

于 2013-07-07T10:30:41.253 回答