您的当前位置:首页正文

iOS快速归档解档(傻瓜版)

来源:华拓网

废话不多说,直接上代码

首先当然是导入头文件

#import <objc/runtime.h>

将下面的代码复制到你要保存的模型文件的.m中

//归档
- (void)encodeWithCoder:(NSCoder *)aCoder{
    unsigned int count;
    Ivar *ivar = class_copyIvarList([self class], &count);
    for (int i=0; i<count; i++) {
        Ivar iva = ivar[i];
        const char *name = ivar_getName(iva);
        NSString *strName = [NSString stringWithUTF8String:name];
        //利用KVC取值
        id value = [self valueForKey:strName];
        [aCoder encodeObject:value forKey:strName];
    }
    free(ivar);
}

//解档
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivar = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar iva = ivar[i];
            const char *name = ivar_getName(iva);
            NSString *strName = [NSString stringWithUTF8String:name];
            //进行解档取值
            id value = [aDecoder decodeObjectForKey:strName];
            //利用KVC对属性赋值
            [self setValue:value forKey:strName];
        }
        free(ivar);
    }
    return self;
}

获取文件地址

// 获取沙盒Document路径
filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//获取沙盒temp路径
filePath = NSTemporaryDirectory();
//获取沙盒Cache路径
filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

//文件路径
NSString *uniquePath=[filePath stringByAppendingPathComponent:你的文件名称];

你要保存的位置正常的归档就可以了

[NSKeyedArchiver archiveRootObject:你要保存的模型  toFile:保存文件的路径];

正常的解档(是有返回值的)

解档出来的模型 = [NSKeyedUnarchiver unarchiveObjectWithFile:你保存文件的路径];

删除沙盒中的文件

-(void)deleteFileWithFileName:(NSString *)fileName filePath:(NSString *)filePath {
    //创建文件管理对象
    NSFileManager* fileManager=[NSFileManager defaultManager];
    //获取文件目录
    if (!filePath) {
        //如果文件目录设置有空,默认删除Cache目录下的文件
        filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    }
    //拼接文件名
    NSString *uniquePath=[filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
    //文件是否存在
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    //进行逻辑判断
    if (!blHave) {
        NSLog(@"文件不存在");
        return ;
    }else {
        //文件是否被删除
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        //进行逻辑判断
        if (blDele) {
            NSLog(@"删除成功");
        }else {
            
            NSLog(@"删除失败");
        }
    }
}