用runtime歸檔、解檔、copy
//
// TestModel.h
// Test
//
// Created by 路燈下的黑貓 on 2018/9/27.
// Copyright © 2018年 張浩. All rights reserved.
//
#import
#import
NS_ASSUME_NONNULL_BEGIN
@interfaceTestModel : NSObject
@property (nonatomic,assign) float height;
@property (nonatomic,strong) NSArray * dataArr;
@property (nonatomic,retain) NSArray * dataArr1;
@property (nonatomic,copy) NSString * name;
@property (nonatomic,retain) NSString * name2;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
NS_ASSUME_NONNULL_END
//
// TestModel.m
// Test
//
// Created by 路燈下的黑貓 on 2018/9/27.
// Copyright © 2018年 張浩. All rights reserved.
//
#import "TestModel.h"
@implementation TestModel
- (instancetype)initWithDict:(NSDictionary *)dict {
if(self= [superinit]) {
//1.獲取類的屬性及屬性對應的型別
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * attributes = [NSMutableArray array];
//獲得底層的屬性列表
unsignedintoutCount =0;
objc_property_t *propertyList = class_copyPropertyList([selfclass], &outCount);
for(inti =0; i
objc_property_t property = propertyList[i];
constchar*key = property_getName(property);
constchar*attribute = property_getAttributes(property);
[keys addObject:[NSString stringWithCString:key encoding:NSUTF8StringEncoding]];
[attributes addObject:[NSString stringWithCString:attribute encoding:NSUTF8StringEncoding]];
}
free(propertyList);
//通過keys 來賦值
for(NSString * keyinkeys) {
if(dict[key]) {
[selfsetValue:dict[key] forKey:key];
}
}
}
return self;
}
//解檔
/*
* 通過歸檔來初始化,也就是把這個歸檔來解出來
**/
- (id)initWithCoder:(NSCoder *)aDecoder {
if(self= [superinit]) {
unsignedintoutCount =0;
Ivar * ivars = class_copyIvarList([selfclass], &outCount);
for(inti =0; i
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[selfsetValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
free(ivars);
}
return self;
}
/*
* 歸檔
**/
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsignedintoutCount;
Ivar * ivars = class_copyIvarList([selfclass], &outCount);
for(inti =0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[selfvalueForKey:key] forKey:key];
}
}
/*
實現copy 協議
**/
- (id)copyWithZone:(NSZone *)zone {
idcopy = [[[selfclass]allocWithZone:zone]init];
unsignedintoutCount;
Ivar * ivars = class_copyIvarList([selfclass], &outCount);
for(inti =0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
idvalue = [selfvalueForKey:key];
[copy setValue:value forKey:key];
}
free(ivars);
returncopy;
}
@end