iOS数据持久化 - NSFileManager

作者: zhYx_ | 来源:发表于2020-07-21 17:31 被阅读0次

    一.简介

    • 特点
      1.NSFileManager是一个单例,相当于全局变量.
      2.NSFileManager用来管理和操作沙盒中的文件和文件夹.
      3.每个路径名都是一个NSString对象.
      4.可对文件或文件夹进行创建/删除/复制/粘贴等操作.

    • 建议使用场景
      管理沙盒中的文件或文件夹.

    二.API

    // 实例化
    @property (class, readonly, strong) NSFileManager *defaultManager;
    
    /* 安全判断 */
    // 传入路径的文件或文件夹是否存在
    - (BOOL)fileExistsAtPath:(NSString *)path;
    // 传入路径的文件或文件夹是否存在(isDirectory代表是否是文件夹)
    - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory;
    // 传入路径的文件或文件夹是否可读
    - (BOOL)isReadableFileAtPath:(NSString *)path;
    // 传入路径的文件或文件夹是否可写(系统目录不允许写入)
    - (BOOL)isWritableFileAtPath:(NSString *)path;
    // 传入路径的文件或文件夹是否可执行
    - (BOOL)isExecutableFileAtPath:(NSString *)path;
    // 传入路径的文件或文件夹是否可删除(系统目录不允许删除)
    - (BOOL)isDeletableFileAtPath:(NSString *)path;
    
    /* 访问 */
    // 传入路径的文件或文件夹的属性(如:名称/创建时间/修改时间/大小等)
    - (nullable NSDictionary<NSFileAttributeKey, id> *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error;
    // 传入路径的文件或文件夹的原始数据(NSData数据)
    - (nullable NSData *)contentsAtPath:(NSString *)path;
    // 传入路径的文件或文件夹包含的所有文件(只查找一级,子文件夹里的文件不能获取)
    - (nullable NSArray<NSString *> *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;
    // 传入路径的文件或文件夹包含的所有文件(包括所有子文件夹里的文件)
    - (nullable NSArray<NSString *> *)subpathsAtPath:(NSString *)path;
    - (nullable NSArray<NSString *> *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;
    
    /* 文件操作 */
    // path路径上创建文件夹(createIntermediates:是否自动创建路径上没有的文件夹)
    - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSFileAttributeKey, id> *)attributes error:(NSError **)error;
    // path路径上创建文件(data:文件NSData数据)
    - (BOOL)createFileAtPath:(NSString *)path contents:(nullable NSData *)data attributes:(nullable NSDictionary<NSFileAttributeKey, id> *)attr;
    // srcPath路径的文件或文件夹拷贝到dstPath路径中
    - (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
    // srcPath路径的文件或文件夹移动(剪切)到dstPath路径中
    - (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
    // srcPath路径的文件或文件夹链接到dstPath路径中
    - (BOOL)linkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
    // 删除path路径上的文件或文件夹
    - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;
    

    相关文章

      网友评论

        本文标题:iOS数据持久化 - NSFileManager

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