关于关键字替换或者其他的使用MJExtension
声明文件.h
#import <Foundation/Foundation.h>
@interface BaseModel : NSObject<NSCoding>
@end
实现文件 .m
#import "BaseModel.h"
#import <objc/runtime.h>
@implementation BaseModel
//归档反归档
-(void)encodeWithCoder:(NSCoder *)aCoder{
//使用runtime批量编码
unsigned propertyCount;
objc_property_t *propertyArray = class_copyPropertyList([self class], &propertyCount);
for (int i = 0 ; i < propertyCount; ++i) {
//取出元素
objc_property_t aProperty = propertyArray[i];
//获取属性名
const char *aPropertyName = property_getName(aProperty);
NSString *aPropertyNameString= @(aPropertyName);
// id Value = [self valueForKey:aPropertyNameString];
[aCoder encodeObject:[self valueForKey:aPropertyNameString] forKey:aPropertyNameString];
}
free(propertyArray);
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
//如果父类也遵守NSCoding协议,可能需要首先调用父类方法
// self = [super initWithCoder:aDecoder];
//否则直接写
self = [super init];
if (self) {
unsigned propertyCount;
objc_property_t *propertyArray = class_copyPropertyList([self class ], &propertyCount);
for (int i = 0 ; i<propertyCount; ++i) {
objc_property_t aProperty = propertyArray[i];
const char *aPropertyName = property_getName(aProperty);
NSString *aPropertyNameString= @(aPropertyName);
[self setValue:[aDecoder decodeObjectForKey:aPropertyNameString] forKey:aPropertyNameString];
}
free(propertyArray);
}
return self;
}
@end
网友评论