Cocoa touch 在检索持久存储文档的上下文中理解NSURL
学习使用coreData。目前正在看斯坦福大学的CS193P第14讲,这非常有帮助。我已使用ManagedDocument成功设置了一个具有核心数据持久性的工作应用程序 每次应用程序启动时都会运行下面的代码。我的困惑是:我们如何知道文档的url是正确的?它如何知道“lastObject”将始终是已保存文档的URLCocoa touch 在检索持久存储文档的上下文中理解NSURL,cocoa-touch,nsfilemanager,Cocoa Touch,Nsfilemanager,学习使用coreData。目前正在看斯坦福大学的CS193P第14讲,这非常有帮助。我已使用ManagedDocument成功设置了一个具有核心数据持久性的工作应用程序 每次应用程序启动时都会运行下面的代码。我的困惑是:我们如何知道文档的url是正确的?它如何知道“lastObject”将始终是已保存文档的URL if (!myManagedDocument) { NSURL *url = [[[NSFileManager defaultManager] URLsForD
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];
}
根据
目录
和域掩码
参数,URLsForDirectory
可以返回
多个URL的数组。例如,在OSX上
NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSAllDomainsMask];
返回
(
file://localhost/Users/<user>/Library/Application%20Support/,
file://localhost/Library/Application%20Support/,
file://localhost/Network/Library/Application%20Support/
)
返回正好包含一个URL的数组,该URL是
应用程序沙箱。在模拟器上,这看起来像
(
file://localhost/Users/<user>/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE/Documents/
)
(
file://localhost/Users/<user>/库/应用程序%20Support/iPhone%20Simulator/5.0/Applications/AAAAA-BBBB-CCCC-DDDD-EEEE/Documents/
)
因此,获取该数组的第一个或最后一个对象并不重要。
代码仅假设托管文档保存在文档目录中
应用程序沙箱的一部分
(
file://localhost/Users/<user>/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE/Documents/
)