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

2022-10-09  本文已影响0人  sytuzhouyong

背景

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
上一篇 下一篇

猜你喜欢

热点阅读