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 {

                

            }

            

        }

    }

  • 相关阅读:
    git的最常用命令总结
    java 多线程 sleep 和wait
    java 多线程 线程的状态和操作系统中进程状态的对应关系
    IDEA的最常见快捷键
    设计模式 单例模式的几种实现方式
    spring boot 项目部署到服务器上出现的问题
    算法与数据结构 (八) HashMap源码
    算法与数据结构 (七) 查找 数组的优化方向: 二分查找和哈希查找,
    算法与数据结构 (六) 排序 三 非比较类的排序 基数排序
    Native Crash定位方法
  • 原文地址:https://www.cnblogs.com/bing-ge/p/4544044.html
Copyright © 2011-2022 走看看