ios 利用Runtime实现自动化归解档

1.oc版本


//归档
- (void)encodeWithCoder:(NSCoder *)aCoder{
    
   //使用runtime获取所有成员变量
    unsigned int count = 0;
    
    Ivar * ivars = class_copyIvarList([self class], &count);
    
    //便利
    
    for (int i = 0; i < count; i++) {
        
        //获取变量的名字
        Ivar ivar = ivars[i];
        const char * name = ivar_getName(ivar);
        NSString * key = [NSString stringWithUTF8String:name];
        
        //kvc
        id value = [self valueForKey:key];
        
        //编码
        [aCoder encodeObject:value forKey:key];
    }
    //释放
    free(ivars);
}


//解档
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    if (self) {
        //使用runtime获取所有成员变量
        unsigned int count = 0;
        Ivar * ivars =  class_copyIvarList([self class], &count);
        
        for (int i = 0 ; i < count; i++) {
            
            Ivar ivar = ivars[i];
            const char * name = ivar_getName(ivar);
            NSString * key = [NSString stringWithUTF8String:name];
            
            //解码
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
            
        }
        //释放
        free(ivars);
    }
    
    
    return self;
    
}

//调用
    
    Person * person = [Person new];
    person.name = @"guominghui";
    person.nick = @"Jack";
    
    NSString * path = [NSString stringWithFormat:@"%@/gmh.plist",NSHomeDirectory()];
    
    //归档
    [NSKeyedArchiver archiveRootObject:person toFile:path];
    
    //解档
    Person * p1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];


2.swift 版本

1)根据oc的方法来写;

//复杂点的swift写法
@objcMembers
class Person:NSObject,NSCoding{


    var name = ""
    var nickName:String?

    init(name:String = "guominghui", nickName:String? = "cat") {

        self.name = name;
        self.nickName = nickName;

    }

    func encode(with aCoder: NSCoder) {

        var count : UInt32 = 0
        guard let ivarlist = class_copyIvarList(object_getClass(self), &count) else {


            print("ivarlist == nil")

            return
        }

        for i in 0..
  1. swift4的新写法;

//另外一种写的方式
class Person:NSObject,Codable{


    var name = ""
    var nickName:String?

    init(name:String = "guominghui", nickName:String? = "cat") {

        self.name = name;
        self.nickName = nickName;

    }
}

         //归档调用
        let person = Person()
        let path = NSHomeDirectory() + "/gmh_archive.json";
        
        let data = try? JSONEncoder().encode(person)
        
        try? data?.write(to: URL(fileURLWithPath: path))

你可能感兴趣的:(ios 利用Runtime实现自动化归解档)