用runtime歸檔、解檔、copy

我先定義一個TestModel

//

//ViewController.m

//CocoTest_1

//

//Created by S u p e r m a n on 2017/3/14.

//Copyright ? 2017年張浩. All rights reserved.

//

#import"ViewController.h"

//

//TestModel.h

//runTime

//

//Created by apple on 16/5/27.

//Copyright ? 2017年張浩. All rights reserved.

//

#import

#import

@interfaceTestModel :NSObject

@property(nonatomic,assign)floatheight;

@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 ? 2017年張浩. All rights reserved.

//

#import"TestModel.h"

@implementationTestModel

- (instancetype)initWithDict:(NSDictionary*)dict {

if(self= [superinit]) {

//1.獲取類的屬性及屬性對應(yīng)的類型

NSMutableArray* keys = [NSMutableArrayarray];

NSMutableArray* attributes = [NSMutableArrayarray];

//獲得底層的屬性列表

unsignedintoutCount =0;

objc_property_t*propertyList =class_copyPropertyList([selfclass], &outCount);

for(inti =0; i

objc_property_tproperty = propertyList[i];

constchar*key =property_getName(property);

constchar*attribute =property_getAttributes(property);

[keysaddObject:[NSStringstringWithCString:keyencoding:NSUTF8StringEncoding]];

[attributesaddObject:[NSStringstringWithCString:attributeencoding:NSUTF8StringEncoding]];

}

free(propertyList);

//通過keys來賦值

for(NSString* keyinkeys) {

if(dict[key]) {

[selfsetValue:dict[key]forKey:key];

}

}

free(ivars);

}

returnself;

}

//解檔

/*

*通過歸檔來初始化,也就是把這個歸檔來解出來

**/

- (id)initWithCoder:(NSCoder*)aDecoder {

if(self= [superinit]) {

unsignedintoutCount =0;

Ivar* ivars =class_copyIvarList([selfclass], &outCount);

for(inti =0; i

Ivarivar = ivars[i];

NSString* key = [NSStringstringWithUTF8String:ivar_getName(ivar)];

[selfsetValue:[aDecoderdecodeObjectForKey:key]forKey:key];

}

free(ivars);

}

returnself;

}

/*

*歸檔

**/

- (void)encodeWithCoder:(NSCoder*)aCoder {

unsignedintoutCount;

Ivar* ivars =class_copyIvarList([selfclass], &outCount);

for(inti =0; i < outCount; i ++) {

Ivarivar = ivars[i];

NSString* key = [NSStringstringWithUTF8String:ivar_getName(ivar)];

[aCoderencodeObject:[selfvalueForKey:key]forKey:key];

}

}

/*

實現(xiàn)copy協(xié)議

**/

- (id)copyWithZone:(NSZone*)zone {

idcopy = [[[selfclass]allocWithZone:zone]init];

unsignedintoutCount;

Ivar* ivars =class_copyIvarList([selfclass], &outCount);

for(inti =0; i < outCount; i ++) {

Ivarivar = ivars[i];

NSString* key = [NSStringstringWithUTF8String:ivar_getName(ivar)];

idvalue = [selfvalueForKey:key];

[copysetValue:valueforKey:key];

}

free(ivars);

returncopy;

}

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容