2009-10-20 77 views
4

我想使用一個打開的面板讓用戶選擇一個目的地,但我想在那個時候提醒他們該目錄不可寫。我通常更喜歡創建它並處理錯誤,但這對我並不有用,因爲我不想創建該文件夾。 (如果有的話,我一定會處理這個錯誤。)如何判斷一個目錄是否可以在Objective-C中寫入?

我認爲可能有更好的方法,而不是創建它並刪除它,這會很臭。

我試過這樣做,認爲「文件」可能意味着像其他一些方法的文件或目錄。

NSFileManager *fm = [NSFileManager defaultManager]; 
[fm isWritableFileAtPath:destinationString] 

(我還沒有確定,如果我想提供機會來驗證覆蓋的權限,但隨時告訴我怎麼了。)

+0

我沒想到的面板甚至可以讓你選擇一個人跡罕至的目的地,但現在回想起來,我不知道,如果不我曾經真的測試過。 – 2009-10-20 22:37:11

+0

它絕對可以讓你選擇一些不可寫的東西。 – zekel 2009-10-21 14:26:54

回答

3

目錄的路徑以 「/」 結束。假設你的代碼是:

NSString* destinationString = [[panel URL] path]; 
[fm isWritableFileAtPath:destinationString]; 

你會與不一端與destinationString結束了「/」,因此isWritableFileAtPath:將測試寫入到一個名爲「someDir」,而不是文件的可能性文件夾「someDir」。

速戰速決將做到這一點:

NSString* destinationString = [[panel URL] path]; 

if (![destinationString hasSuffix:@"/"]) 
    destinationString = [destinationString stringByAppendingString:@"/"]; 

[fm isWritableFileAtPath:destinationString]; 
+0

@inkjet感謝您瞭解它爲什麼在某些時候工作。 – zekel 2014-08-14 17:58:37

3

你想

-attributesOfItemAtPath:error:. 

- jcr

+0

這是否意味着我必須查看filePosixPermissions,fileGroupOwnerAccountName,fileOwnerAccountName,NSUserName,並找出它自己? – zekel 2009-10-21 14:22:08

+0

對於NSURL對象,您可以檢查NSURLIsWritableKey資源值。 – Jenn 2016-01-07 01:30:55

1

是的,目錄算作文件。

+0

那麼,這是否意味着如果[fm isWriteableFileAtPath:@「/ someDir /」]返回YES,我可以在該目錄中創建文件? – Tom 2012-01-21 18:39:47

5

編輯:看起來像噴墨想象出爲什麼我得到不一致的結果。標記他是正確的答案。


奇怪。我之前嘗試過使用isWriteableAtPath,但它似乎沒有像我期望的那樣工作,但現在使用單獨的測試。

NSFileManager *fm = [NSFileManager defaultManager]; 
NSLog(@"%d /private/ writeable?", [fm isWritableFileAtPath:@"/private/"]); 
NSLog(@"%d /Applications/ writeable?", [fm isWritableFileAtPath:@"/Applications/"]); 
NSLog(@"%d /Users/MYUSERNAME/ writeable?", [fm isWritableFileAtPath:@"/Users/MYUSERNAME/"]); 

打印

0 /private/ writeable? 
1 /Applications/ writeable? 
1 /Users/MYUSERNAME/ writeable? 
+1

但它最終在實際的真實情況下工作嗎? – Enchilada 2011-06-14 19:59:35

+0

是的,它爲我工作。 – zekel 2012-04-11 17:25:27

相關問題