2013-06-13 170 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