Objective-C Runtime技术调研(六)

一、资料归档篇

创建TLPeople.h

#import

@interfaceTLPeople :NSObject

@property(nonatomic,copy)NSString*name;//姓名

@property(nonatomic,strong)NSNumber*age;//年龄

@property(nonatomic,copy)NSString*occupation;//职业

@property(nonatomic,copy)NSString*nationality;//国籍

@end

TLPeople.m

#import"TLPeople.h"

#if TARGET_IPHONE_SIMULATOR

#import

#else

#import

#import

#endif

@implementationTLPeople

-(void)encodeWithCoder:(NSCoder*)aCoder

{

unsignedintcount =0;

Ivar*ivars =class_copyIvarList([TLPeopleclass], &count);

for(NSUIntegeri =0; i < count; i ++) {

Ivarivar = ivars[i];

constchar*name =ivar_getName(ivar);

NSString*key = [NSStringstringWithUTF8String:name];

idvalue = [selfvalueForKey:key];

[aCoderencodeObject:valueforKey:key];

}

free(ivars);

}

-(instancetype)initWithCoder:(NSCoder*)aDecoder

{

self= [superinit];

if(self) {

unsignedintcount =0;

Ivar*ivars =class_copyIvarList([TLPeopleclass], &count);

for(NSUIntegeri =0; i < count; i ++) {

Ivarivar = ivars[i];

constchar*name =ivar_getName(ivar);

NSString*key = [NSStringstringWithUTF8String:name];

idvalue = [aDecoderdecodeObjectForKey:key];

[selfsetValue:valueforKey:key];

}

free(ivars);

}

returnself;

}

@end

Demo传送门-> 6.1 资料归档篇Demo

你可能感兴趣的:(Objective-C Runtime技术调研(六))