Skip to content

Latest commit

 

History

History
82 lines (54 loc) · 2.49 KB

Note_00179_20160512.md

File metadata and controls

82 lines (54 loc) · 2.49 KB

变更记录

序号 录入时间 录入人 备注
1 2016-05-12 Alfred Jiang -

方案名称

数据存储 - 文件(目录)操作笔记

关键字

数据存储 \ 文件操作 \ 文件夹 \ 文件目录操作 \ 笔记

需求场景

  1. 进行文件操作
  2. 管理数据文件

参考链接

  1. Sina - NSJSONSerialization-JSON数据与NSDictionary和NSArray之间的转化

详细内容

1. 创建文件目录
- (NSString *)dirFullPath:(NSString *)dirName
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [path objectAtIndex:0];
    NSString *dirPath = [documentsDirectory stringByAppendingPathComponent:dirName];
    
    BOOL isDirectory = NO;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDirectory]) {

        if (isDirectory) {

            return dirPath;
        }
    }
    
    [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:NULL];
    
    return dirPath;
}
2. 读取文件目录下全部文件
NSArray *directoryContents = [[NSFileManager defaultManager] subpathsAtPath:dirFullPath];
3. 向文件目录添加文件,超过指定最大个数 ( MAX_FILES_COUNT ) 移除多余文件
NSArray *directoryContents = [[NSFileManager defaultManager] subpathsAtPath:dirFullPath];
    
NSArray *sortedList = [directoryContents sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
    return [obj2 compare:obj1];
}];
    
if ([sortedList count] > MAX_FILES_COUNT) {

    NSArray *subList = [sortedList subarrayWithRange:NSMakeRange(MAX_FILES_COUNT, ([sortedList count] - MAX_FILES_COUNT))];
        
    [subList enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
        NSLog(@"Remove file : %@",obj);
        [[NSFileManager defaultManager] removeItemAtPath:[[self dirPathForURL:URLString] stringByAppendingPathComponent:obj] error:nil];
    }];
}

效果图

(无)

备注