开发者

How can you tell if a directory is writeable in Objective-C?

I want to use an open panel to let the user select a destination, but I want to alert them at that point that point that the directory is not-writable. I generally prefer to create it and handle the error, but that's not useful to me here, since I don't want to create the folder just yet. (I'll be sure to handle 开发者_高级运维the error when I do create it, if there is one.)

I thought there might be a better way than to just create it and delete it, which would stink.

I tried doing this, thinking that "file" might mean file or directory like some other methods.

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

(I'm not sure yet if I want to offer the chance to authenticate to override permissions, but feel free to tell me how.)


Edit: Looks like inkjet figured out why I was getting inconsistent results. Marking his as the correct answer.


Weird. I tried isWriteableAtPath before and it didn't seem to work as I expected, but now with an isolated test does.

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/"]);

Prints

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


A directory's path ends with "/". Assuming your code is:

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

You'll end up with a destinationString that does not end with "/", therefore isWritableFileAtPath: will be testing the possibility of writing to a file named "someDir" instead of the folder "someDir".

A quick fix would be to do this:

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

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

[fm isWritableFileAtPath:destinationString];


You want

-attributesOfItemAtPath:error:.

-jcr


Yes, directories count as files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜