NSObject + NSCoding Category

来源:互联网 发布:网络歌手作曲 编辑:程序博客网 时间:2024/06/06 22:48

在.h文件中 <NSCoding>

在.m文件中

#import <objc/objc-runtime.h>

-(instancetype)initWithCoder:(NSCoder *)aDecoder {

    self = [selfinit];

    if (self) {

        

        

        unsigned int count =0;

        objc_property_t *propertyList = class_copyPropertyList([self class], &count);

        for (int i =0; i < count; i++) {

            objc_property_t property = propertyList[i];

            const char *propertyName = property_getName(property);

            // 将取出来的C语言字符串转化为OC字符串(char -> NSString)

            NSString *propertyNameStr = [NSStringstringWithCString:propertyName encoding:NSUTF8StringEncoding];

            // 解档取出属性的值

            id value = [aDecoder decodeObjectForKey:propertyNameStr];

            // 使用setValueForKey赋值,相当于set方法

            [self setValue:value forKey:propertyNameStr];

        }


        free(propertyList);

        

    }

    return self;

}


-(void)encodeWithCoder:(NSCoder *)aCoder {

    

    unsigned int count =0;

    objc_property_t *propertyList = class_copyPropertyList([self class], &count);

    for (int i =0; i < count; i++) {

        objc_property_t property = propertyList[i];

        const char *propertyName =property_getName(property);

        // 将取出来的C语言字符串转化为OC字符串(char -> NSString)

        NSString *propertyNameStr = [NSStringstringWithCString:propertyName encoding:NSUTF8StringEncoding];

        // 取出当前属性的值,相当于self.name

        id value = [selfvalueForKey:propertyNameStr];

        [aCoder encodeObject:value forKey:propertyNameStr];

    }

    free(propertyList);

}


0 0
原创粉丝点击