2011-07-30 50 views
2

我創建了一個NSSavePanel使用此代碼:替換沙盒應用程序中使用NSSavePanel文件

NSSavePanel *savePanel = [NSSavePanel savePanel]; 
savePanel.delegate = self; 

savePanel.directoryURL = ...; 
savePanel.nameFieldStringValue = ...; 

[savePanel beginSheetModalForWindow:self.window 
        completionHandler:^(NSInteger returnCode) { 

if (returnCode == NSFileHandlingPanelOKButton) { 

// the completion handler 

} 
}]; 

如果保存面板,用戶選擇一個已經存在的文件,會出現提示框「,‘XXX’已經存在,你想替換它嗎?「。

如果用戶按「替換」按鈕,在完成處理舊的文件與NSFileManagerremoveItemAtPath:error:方法去掉,然後創建新的文件(在現實:它是在一個臨時位置創建,然後使用moveItemAtPath:toPath:error:方法感動,但我認爲這只是一個實現細節):

if (returnCode == NSFileHandlingPanelOKButton) { 
    // overwrite the url, because if we are here is because the user has already 
    // expressed its willingness to overwrite the previous file 
    NSError *error = nil; 
    BOOL res = [[NSFileManager defaultManager] removeItemAtURL:savePanel.URL error:&error]; 

    if (res) { 
    res = [[NSFileManager defaultManager] moveItemAtPath:tmpFilePath toPath:savePanel.URL error:&error]; 
    } 

    // ... 
} 

在過去,一切都一直工作正常。然而,今天,我開始使用具有「讀/寫訪問」權限的Lion's Sandbox。

隨着沙箱,removeItemAtPath:error:成功,但以下moveItemAtPath:toPath:error:返回一個錯誤。

這似乎是合理的,因爲Powerbox賦予我訪問(讀取和寫入)文件的權利。當我刪除這個文件時,授予我的權利已經耗盡。

我的猜測是對的嗎?

我該如何解決這個問題?

+0

覆蓋的圖像:withItemAtURL:'而不是'removeItemAtURL:錯誤:'+'moveItemAtPath:toPath:錯誤:'我得到錯誤「您無權將文件」XXX「保存在文件夾」YYY「」中。有什麼我失蹤?我錯在哪裏? – Dev

回答

1

問題是,一旦刪除文件,您對該文件的權限也會消失。您需要執行的操作是覆蓋文件,例如使用[[NSFileManager defaultManager] createFileAtPath:contents:attributes:]。該NSFileManager documentation狀態此方法如下:

If a file already exists at path, this method overwrites the contents of that file if the current process has the appropriate privileges to do so.

NSData/NSMutableData使用方法也可能會有所幫助。

0

使用[NSFileHandle fileHandleForWritingToURL:error:]後跟writeData:調用覆蓋現有文件。這種方法適用於我的沙盒應用程序。對於新文件,只需使用NSFileManager的createFileAtPath方法創建它:contents:attributes :(如果內容不適合內存,則內容設置爲nil),然後使用NSFileHandle寫入數據。

如果你想使用核心顯卡即使使用方法`replaceItemAtURL看到NSSavePanel, CGImageDestinationFinalize and OS X sandbox