1.我定义一个TestModel
//
// TestModel.h
// runTime
//
// Created by apple on 16/5/27.
// Copyright © 2016年 李重阳. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface TestModel : NSObject<NSCoding,NSCopying>
@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
//
// TestModel.m
// runTime
//
// Created by apple on 16/5/27.
// Copyright © 2016年 李重阳. All rights reserved.
//
#import "TestModel.h"
@implementation TestModel
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [super init]) {
//1.获取类的属性及属性对应的类型
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * attributes = [NSMutableArray array];
//获得底层的属性列表
unsigned int outCount = 0;
objc_property_t *propertyList = class_copyPropertyList([self class], &outCount);
for (int i = 0 ; i<outCount; i++) {
objc_property_t property = propertyList[i];
const char *key = property_getName(property);
const char *attribute = property_getAttributes(property);
[keys addObject:[NSString stringWithCString:key encoding:NSUTF8StringEncoding]];
[attributes addObject:[NSString stringWithCString:attribute encoding:NSUTF8StringEncoding]];
}
free(propertyList);
//通过keys 来赋值
for (NSString * key in keys) {
if (dict[key]) {
[self setValue:dict[key] forKey:key];
}
}
free(ivars);
}
return self;
}
//解档
/*
* 通过归档来初始化,也就是把这个归档来解出来
**/
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int outCount = 0;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i<outCount; i++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
free(ivars);
}
return self;
}
/*
* 归档
**/
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
/*
实现copy 协议
**/
- (id)copyWithZone:(NSZone *)zone {
id copy = [[[self class]allocWithZone:zone]init];
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
id value = [self valueForKey:key];
[copy setValue:value forKey:key];
}
free(ivars);
return copy;
}
@end