zoukankan      html  css  js  c++  java
  • 自动归档解档工具

    1.首先获取一个类的所有属性

    + (NSArray *)getAllPropertyWithClass:(Class)class
    {
        NSMutableArray *propertyArr = [[NSMutableArray alloc] init];
        unsigned int count;
        while (class != [NSObject class]) {
            objc_property_t *properties = class_copyPropertyList(class, &count);
            for(int i = 0; i < count; i++)
            {
                objc_property_t property = properties[i];
                NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
                if ([propertyName isEqualToString:@"distace"]) {
                    continue;
                }
                [propertyArr addObject:propertyName];
            }
            if (properties) {
                free(properties);
            }
            //得到父类的消息
            class = class_getSuperclass(class);
        }
        return propertyArr;
    }

    2.用kvc对每个属性进行归档解档

    - (instancetype)initWithCoder:(NSCoder *)coder

    {

        self = [super init];

        if (self) {

            NSArray *properties = [GetAllPropertyTool getAllPropertyWithClass:[self class]];

            for (NSString *property in properties) {

                @try {

                    [self setValue:[coder decodeObjectForKey:property] forKey:property];

                }

                @catch (NSException *exception) {

                    

                }

                @finally {

                    

                }

                

            }

        }

        return self;

    }

     

    - (void)encodeWithCoder:(NSCoder *)coder

    {

        NSArray *properties = [GetAllPropertyTool getAllPropertyWithClass:[self class]];

        for (NSString *property in properties) {

            @try {

                [coder encodeObject:[self valueForKey:property] forKey:property];

            }

            @catch (NSException *exception) {

                

            }

            @finally {

                

            }

            

        }

    }

  • 相关阅读:
    操作系统基础知识
    os库基本介绍
    原型模式
    ASP .NetCore 部署500错误 查看异常详情
    css设置文本自动换行
    SqlServer数据库链接字符串
    Json列表数据查找更新
    VB中将类标记为可序列化
    VB 性能优化点
    参加公司工作总结会要准备的内容 IT 技术部
  • 原文地址:https://www.cnblogs.com/bing-ge/p/4544044.html
Copyright © 2011-2022 走看看