程序员

iOS-利用Runtime完成归档与解档 <NSCodin

2018-05-30  本文已影响9人  香蕉你个菠萝

如果类有多个属性的话,利用runtime就轻松多了!

.h文件

#import <Foundation/Foundation.h>

@interface DXTextModel : NSObject <NSCoding>
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *idd;
@property (nonatomic,strong) NSString *title;
@property (nonatomic,strong) NSString *kind;
@property (nonatomic,strong) NSArray *listArr;
@end
``

###.m文件
```objc
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "DXTextModel.h"

@implementation DXTextModel
//进行编码的协议方法
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    //编码
//    [aCoder encodeObject:self.name forKey:@"name"];
//    [aCoder encodeObject:self.listArr forKey:@"listArr"];
    
    //使用runtime进行解档与归档
    unsigned int count = 0;
    Ivar *ivarLists = class_copyIvarList([DXTextModel class], &count);
    for (int i = 0; i< count; i++) {
        const char * name = ivar_getName(ivarLists[i]);
        NSString * strName = [NSString stringWithUTF8String:name];
        [aCoder encodeObject:[self valueForKey:strName] forKey:strName];
    }
    free(ivarLists);//释放
}

//进行解码的协议方法
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    
    if (self = [super init]) {
        //解码
//        self.name = [aDecoder decodeObjectForKey:@"name"];
//        self.listArr = [aDecoder decodeObjectForKey:@"listArr"];
        
        //使用runtime进行解档
        unsigned int count = 0;
        Ivar *ivarLists = class_copyIvarList([DXTextModel class], &count);
        for (int i = 0; i < count; i++) {
            const char* name = ivar_getName(ivarLists[i]);
            NSString* strName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            id value = [aDecoder decodeObjectForKey:strName];
            [self setValue:value forKey:strName];
        }
        free(ivarLists);
        
    }
    
    return self;
}



-(NSString*)description{
    return [NSString stringWithFormat:@"DXTextModel-> name:%@  idd:%@  kind:%@  title:%@  listArr:%@",self.name,self.idd,self.kind,self.title,self.listArr];
    
}

@end
上一篇 下一篇

猜你喜欢

热点阅读