xcode NSFileManager & NSFilePosixPermissions

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9655185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:35:32  来源:igfitidea点击:

NSFileManager & NSFilePosixPermissions

xcodepermissionsnsdictionarynsfilemanagerchmod

提问by qwertz

I want to use the octal permissions (used for chmod) for NSFilePosixPermissions. Here is what I did now:

我想对 NSFilePosixPermissions 使用八进制权限(用于 chmod)。这是我现在所做的:

NSFileManager *manager = [NSFileManager defaultManager];
NSDictionary *attributes;

[attributes setValue:[NSString stringWithFormat:@"%d", 0777] 
             forKey:@"NSFilePosixPermissions"]; // chmod permissions 777
[manager setAttributes:attributes ofItemAtPath:@"/Users/lucky/Desktop/script" error:nil];

I get no error, but when I check the result with "ls -o" the permission are't -rwxrwxrwx.

我没有收到错误,但是当我用“ls -o”检查结果时,权限不是 -rwxrwxrwx。

What's wrong? Thanks for help.

怎么了?感谢帮助。

回答by gcbrueckmann

First, NSFilePosixPermissionsis the name of a constant. Its value may also be the same, but that's not guaranteed. The value of the NSFilePosixPermissionsconstant could change between framework releases, e. g. from @"NSFilePosixPermissions"to @"posixPermisions". This would break your code. The right way is to use the constant as NSFilePosixPermissions, not @"NSFilePosixPermissions".

首先,NSFilePosixPermissions是常量的名称。它的值也可能相同,但这并不能保证。NSFilePosixPermissions常量的值可能会在框架版本之间发生变化,例如从@"NSFilePosixPermissions"@"posixPermisions"。这会破坏你的代码。正确的方法是使用常量 as NSFilePosixPermissions,而不是@"NSFilePosixPermissions"

Also, the NSFilePosixPermissions referencesays about NSFilePosixPermisions:

此外,NSFilePosixPermissions 参考NSFilePosixPermisions

The corresponding value is an NSNumberobject. Use the shortValuemethod to retrieve the integer value for the permissions.

对应的值是一个NSNumber对象。使用该shortValue方法检索权限的整数值。

The proper way to set POSIX permissions is:

设置 POSIX 权限的正确方法是:

// chmod permissions 777

// Swift
attributes[NSFilePosixPermissions] = 0o777

// Objective-C
[attributes setValue:[NSNumber numberWithShort:0777] 
             forKey:NSFilePosixPermissions];

回答by Charlton Provatas

Solution in Swift 3

Swift 3 中的解决方案

let fm = FileManager.default

var attributes = [FileAttributeKey : Any]()
attributes[.posixPermissions] = 0o777
do {
    try fm.setAttributes(attributes, ofItemAtPath: path.path)
}catch let error {
    print("Permissions error: ", error)
}