OS X编程

Objective-C Runtime技术调研(六)

2017-04-27  本文已影响8人  tridonlee

一、资料归档篇

创建TLPeople.h

#import <Foundation/Foundation.h>

@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 <objc/objc-runtime.h>

#else

#import <objc/runtime.h>

#import <objc/message.h>

#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

上一篇 下一篇

猜你喜欢

热点阅读