美文网首页
iOS开发中的归解档

iOS开发中的归解档

作者: Michael_NO1 | 来源:发表于2017-08-24 16:30 被阅读14次

    首先要遵守NSCoding协议;
    重写两个方法:

    //归档属性
    - (void)encodeWithCoder:(NSCoder *)coder
    {
        //归档!!
        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];
            //归档
            [coder encodeObject:value forKey:KEY];
        }
        //但凡在C语言里面 看到New Creat Copy 都需要释放
        free(ivars);
        
    }
    //解档
    - (instancetype)initWithCoder:(NSCoder *)coder
    {
        self = [super init];
        if (self) {
            unsigned int count = 0;
            Ivar * ivars = class_copyIvarList([self class], &count);
            for (int i = 0; i < count; i++) {
                //名称
                const char * name = ivar_getName(ivars[i]);
                NSString * KEY = [NSString stringWithUTF8String:name];
                //解档
                id value = [coder decodeObjectForKey:KEY];
                //设置到成员变量上
                [self setValue:value forKey:KEY];
            }
        free(ivars);
            
        }
        return self;
    }
    

    相关文章

      网友评论

          本文标题:iOS开发中的归解档

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