【问题标题】:UIManagedDocument saveToURL always returns falseUIManagedDocument saveToURL 总是返回 false
【发布时间】:2014-06-17 18:26:09
【问题描述】:

我正在尝试创建一个尚不存在的 UIManagedDocument。这是我的代码:

url = [NSURL URLWithString:@"file://ProjectSSDB"];
document = [[UIManagedDocument alloc] initWithFileURL:url];

if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
    [document openWithCompletionHandler: ^(BOOL success) {
        if (success) [ProjectSSViewController documentIsReady];
        if (!success) NSLog(@"Couldn't open document at %@", url);
    }];
} else {
    [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
        NSLog(@"Returned %d", success);
        if (success) [ProjectSSViewController documentIsReady];
        if (!success) NSLog(@"Couldn't create document at %@", url);
    }];
} 

我的问题是该文件还不存在,并且 saveToURL 操作似乎总是返回 false。无论如何我可以进一步调试为什么会发生这种情况?

编辑:

好的,所以我无法写入该 URL。我现在尝试这样做:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSURL *url = [NSURL URLWithString:documentsDirectory];

NSLog(@"The URL is %@", [url absoluteString]);

当它运行时,日志似乎返回 URL 为空。还有什么我做错了吗?

【问题讨论】:

  • 我已经更新了我的答案,使用我发布的代码

标签: iphone ios objective-c


【解决方案1】:

这个路径不能写“file://ProjectSSDB”,你没有权限,需要通过这种方式获取你的应用的root:

NSString* rootPath = NSHomeDirectory();

并将数据保存在Apple file system guide line指定的子文件夹之一中

NSString* fullPath = [rootPath stringByAppendingPathComponent:@"subFoldeder/file.extension"];

【讨论】:

  • 我试过做类似的事情,我已经更新了我的问题。
【解决方案2】:

我已经成功使用以下代码 sn-p 生成 UIManagedDocumentURL 有一段时间了:

NSURL *url = [NSFileManager.defaultManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask].firstObject;
url = [url URLByAppendingPathComponent:@"ARBITRARY_NAME"];

self.document = [UIManagedDocument.alloc initWithFileURL:url];

P.s.:这是 iOS 5+ 的解决方案。

让我知道这是否适合你;)

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2021-11-05
    • 2018-11-05
    • 2019-05-06
    • 2017-04-29
    • 2013-04-30
    相关资源
    最近更新 更多