创建Person类
.h文件
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Person : NSObject<NSCoding>
@property (nonatomic,copy) NSString *name; @end
@end
.m文件
#import "Person.h"
@implementation Person
//编码
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int count = 0;
Ivar * ivars = class_copyIvarList([self class], &count);
for (int i = 0 ; i< count;i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
free(ivars);
}
//解码
- (id)initWithCoder:(NSCoder *)aDecoder {
if(self = [super init]) {
unsigned int count;
// 获得指向当前类的所有属性的指针
Ivar * ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
// 获取指向当前类的一个属性的指针
Ivar ivar = ivars[i];
// 获取C字符串的属性名
const char *name = ivar_getName(ivar);
// C字符串转OC字符串
NSString *propertyName = [NSString stringWithUTF8String:name];
// 解码属性值
NSString *propertyValue = [aDecoder decodeObjectForKey:propertyName];
[self setValue:propertyValue forKey:propertyName];
}
// 记得释放
free(ivars);
}
return self;
}
json解析类同理。
网友评论