美文网首页
iOS 设置目录或文件的访问权限

iOS 设置目录或文件的访问权限

作者: sytuzhouyong | 来源:发表于2022-10-09 09:25 被阅读0次

背景

iOS App偶现Documents目录下的某个子目录文件在极偶现的情况下出现丢失的情况,怀疑可能是其他模块将其删除了,所以想通过设置子目录文件的权限为只读权限,阻止误删的发生。

NSFileManager相关API

/* setAttributes:ofItemAtPath:error: returns YES when the attributes specified in the
'attributes' dictionary are set successfully on the item specified by 'path'. If this
method returns NO, a presentable NSError will be provided by-reference in the 'error'
parameter. If no error is required, you may pass 'nil' for the error.
This method replaces changeFileAttributes:atPath:.
*/
- (BOOL)setAttributes:(NSDictionary<NSFileAttributeKey, id> *)attributes 
         ofItemAtPath:(NSString *)path 
                error:(NSError **)error 
                API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

NSFilePosixPermissions取值说明

Number 权限说明 Ref
0 No permission ---
1 Execute permission --x
2 Write permission -w-
3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx
4 Read permission r--
5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x
6 Read and write permission: 4 (read) + 2 (write) = 6 rw-
7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx

只读属性

NSDictionary *attributes = @{ NSFilePosixPermissions : @(0544) };
NSFileManager *manager = [NSFileManager defaultManager];
BOOL success = [manager setAttributes:attributes ofItemAtPath:path error:error];

读写属性

NSDictionary *attributes = @{ NSFilePosixPermissions : @(0755) };
NSFileManager *manager = [NSFileManager defaultManager];
BOOL success = [manager setAttributes:attributes ofItemAtPath:path error:error];

PS

  1. 网上说的将NSFilePosixPermissions设置成@(0444)就可以了,但是我在测试时,如果直接设置成会@(0444),结果返回YES,但同时也会将目录里的文件和子目录清空,这肯定是不行的。
  2. 当设置目录访问权限为@(0544)后,删除目录内的非目录文件会提示权限不够;但是如果删除子目录内的文件则不会提醒权限,还是会删除成功。所以为了保证删除设置目录内的任意文件都提示权限不够,应该递归的将所有子目录的访问权限也同时设置成只读。
  3. NSFilePosixPermissions更多的细节:https://www.tutorialspoint.com/unix/unix-file-permission.htm

相关文章

  • iOS 设置目录或文件的访问权限

    背景 iOS App偶现Documents目录下的某个子目录文件在极偶现的情况下出现丢失的情况,怀疑可能是其他模块...

  • Linux中文件/目录的特殊权限

    每一个文件和目录都有自己的访问权限,访问权限确定后,用户能否访问文件或者目录。最为熟知的一个文件或目录拥有三种权限...

  • 2019-12-20 目录与文件 ACL权限设置命令setfac

    查看目录或文件当前ACL权限 getfacl /app #app为目录名称 设置目录或文件ACL权限 setfac...

  • linux 文件和目录

    linux 目录结构 访问权限 用户能够控制一个给定的文件或目录的访问程度,一个文件或目录可能有读、写及执行权限:...

  • Linux文件权限

    Linux系统中的文件和目录通过使用访问许可权限,来确定谁能通过何种方式进行访问与操作。文件或目录的访问权限分为只...

  • chmod

    chmod命令用于改变linux系统文件或目录的访问权限。用它控制文件或目录的访问权限。该命令有两种用法。一种是包...

  • chmod

    chmod命令用于改变linux系统文件或目录的访问权限。用它控制文件或目录的访问权限。该命令有两种用法。一种是包...

  • 基本命令

    4.2.3 改变访问权限命令 文件或目录的访问权限分为:读\写\可执行.以文件为例,只读权限表示只允许读它的内容,...

  • 四、文件权限(一)

    1.基本权限 UGO 文件权限设置: 可以赋于某个用户或组 能够以何种方式 访问某个文件 案例: 1.1.设置...

  • linux用户和权限管理命令

    目标 添加新用户:useradd 设置用户密码:passwd 改变文件或目录权限:chomd 改变文件或目录的所有...

网友评论

      本文标题:iOS 设置目录或文件的访问权限

      本文链接:https://www.haomeiwen.com/subject/wvdgartx.html