2013-06-13 173 views
0

我正在尝试创建一个尚不存在的UIManagedDocument。这里是我的代码:UIManagedDocument saveToURL总是返回false

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。无论如何,我可以进一步调试,为什么会发生这种情况?

编辑:

好了,所以我不能写入到该网址。我现在试着这样做:

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

NSURL *url = [NSURL URLWithString:documentsDirectory]; 

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

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

+0

我已经更新我的回答,请使用我已经张贴 – Manu

回答

1

你不能在这个路径写的“file:// ProjectSSDB”,你没有权限,你需要让你的应用程序的根以这样的方式

NSString* rootPath = NSHomeDirectory(); 

和保存在子文件夹中的一个数据,通过Apple file system guide line

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

我试着做一些类似的代码,我已经更新了我的问题。 – samturner

0

指定我已经成功地使用下面的代码生成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+解决方案。

让我知道是否适合你;)

+0

@samturner是我的解决方案吗? – damirstuhec