首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在iOS中设置文件夹/文件的权限

问如何在iOS中设置文件夹/文件的权限
EN

Stack Overflow用户
提问于 2015-01-30 15:47:57
回答 1查看 5.7K关注 0票数 3

如何将权限设置为iOS中的文件夹和文件,该文件夹位于documents文件夹中?

在“文档”文件夹中创建文件时,是否可以设置只读权限?

或者其他的解决方案?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-30 16:18:08

根据创建文件的方式,可以指定文件属性。若要使文件只读,请传递以下属性:

代码语言:javascript
复制
NSDictionary *attributes = @{ NSFilePosixPermissions : @(0444) };

注意值中的前导0。这一点很重要。它表示这是一个八进制数。

另一个选项是在文件创建后设置其属性:

代码语言:javascript
复制
NSString *path = ... // the path to the file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
if (![fm setAttributes:attributes ofItemAtPath:path error:&error]) {
    NSLog(@"Unable to make %@ read-only: %@", path, error);
}

更新:

要确保保留现有权限,请执行以下操作:

代码语言:javascript
复制
NSString *path = ... // the path to the file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
// Get the current permissions
NSDictionary *currentPerms = [fm attributesOfFileSystemForPath:path error:&error];
if (currentPerms) {
    // Update the permissions with the new permission
    NSMutableDictionary *attributes = [currentPerms mutableCopy];
    attributes[NSFilePosixPermissions] = @(0444);
    if (![fm setAttributes:attributes ofItemAtPath:path error:&error]) {
        NSLog(@"Unable to make %@ read-only: %@", path, error);
    }
} else {
    NSLog(@"Unable to read permissions for %@: %@", path, error);
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28239577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档