项目中用到了自定义的model:Person(栗子)。此model须要能够实现归档的功能,可是属性很是多,且相似的model不少。若是按照常规去写归档的代码,那么不管是写起来仍是维护起来都很是困难。git
因为model继承自NSObject,因此给NSObject添加了扩展用来实现自定义model的归档功能。实现思路来源于伟大的网络和MJExtention,因此应该不算是原创吧,反正这个实现也快烂大街了。github
大体为:网络
1:获取当前类及父类的class及属性名称和类型函数
2:实现归档常规方法atom
3:宏定义常规方法,方便实现spa
最主要的方法为第一步。code
NSObject (Coding).morm
- (void)coding_encode:(NSCoder *)aCoder { //获取当前类属性名称及值 [self enumPropertyList:^(id key, id value) { //归档常规方法 [aCoder encodeObject:value forKey:key]; }]; } - (nullable instancetype)coding_decode:(NSCoder *)aDecoder { [self enumPropertyList:^(id key, id value) { [self setValue:[aDecoder decodeObjectForKey:key] forKey:key]; }]; return self; } - (void)enumPropertyList:(void(^)(id key, id value))emunBlock { //获取当前类及父类 [self enumClass:^(__unsafe_unretained Class cl, BOOL *stop) { //根据获取的类的名称获得全部属性相关信息 [self propertyForClass:cl finish:^(PropertyModel *pModel) { NSString *attributeTypeString = pModel.propertyType;//此处为了方便只获取了属性名称 使用PropertyModel便于扩展 NSString *name = pModel.name; //判断当前属性是否支持coding协议 if ([attributeTypeString hasPrefix:@"@\""]) {//对象类型都是以@"开头 attributeTypeString = [attributeTypeString substringWithRange:NSMakeRange(2, attributeTypeString.length - 3)]; Class attributeClass = NSClassFromString(attributeTypeString); BOOL isConformCoding = class_conformsToProtocol(attributeClass, NSProtocolFromString(@"NSCoding")); NSString *message = [NSString stringWithFormat:@"model:%@ 不支持NSCoding协议",attributeTypeString]; NSAssert(isConformCoding, message); } if (emunBlock) { emunBlock(name,[self valueForKey:name]); } }]; }]; }
获取类名及属性名称对象
NSObject (Class).mblog
- (void)enumClass:(void(^)(Class cl, BOOL *stop))enumBlock { if (!enumBlock) { return; } BOOL sstop = NO; Class c = self.class; while (c && !sstop) { enumBlock(c,&sstop); c = class_getSuperclass(c); if (isClassForFoundatation(c)) { break ; } } }
此处借鉴(copy)了MJExtention实现方式,包括判断当前类是否属于Foundataion类型的方法,只不过我使用了函数的方式表示,纯粹是想尝试一下不一样的风格。
NSSet *foundationClasses(){ return [NSSet setWithObjects: [NSURL class], [NSDate class], [NSValue class], [NSData class], [NSError class], [NSArray class], [NSDictionary class], [NSString class], [NSAttributedString class], nil]; } BOOL isClassForFoundatation(Class class){ __block BOOL result = NO; [foundationClasses() enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) { if ([class isSubclassOfClass:obj] || (class == [NSObject class])) { result = YES; *stop = YES; } }]; return result; }
如下是根据class获取属性
- (void)propertyForClass:(Class)cl finish:(void(^)(PropertyModel *pModel))finish { if (!finish) { return; } unsigned int count; objc_property_t *properties = class_copyPropertyList(cl, &count); for (int i = 0; i < count; i++) { objc_property_t p = properties[i]; NSString *name = @(property_getName(p)); NSString *attribute = @(property_getAttributes(p)); NSRange dotLocation = [attribute rangeOfString:@","]; NSString *attributeTypeString ; if (dotLocation.location == NSNotFound) { attributeTypeString = [attribute substringFromIndex:1]; }else{ attributeTypeString = [attribute substringWithRange:NSMakeRange(1, dotLocation.location - 1)]; } PropertyModel *model = [PropertyModel new]; model.name = name; model.propertyType = attributeTypeString; finish(model); } free(properties); }
其中PropertyModel是为了方便扩展,当前是须要属性名称及类型。
@interface PropertyModel : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *propertyType; @end
到此,核心代码已经完毕
在.h文件中声明宏定义就能够
@interface NSObject (Coding) - (void)coding_encode:(NSCoder *_Nonnull)aCoder ; - (nullable instancetype)coding_decode:(NSCoder *_Nonnull)aDecoder ; @end #define CodingImplmentation \ - (void)encodeWithCoder:(NSCoder *)aCoder { \ [self coding_encode:aCoder]; \ } \ - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { \ if (self == [super init]){ \ [self coding_decode:aDecoder];\ }\ return self;\ }\ #define DWObjectCodingImplmentation CodingImplmentation
在自定义的model:Person.m的文件中只添加宏定义就能够自动实现归档功能
@implementation Person #pragma mark - 归档 DWObjectCodingImplmentation
PS:不要忘记在.h文件中写上<NSCoding>
demo验证了继承自Person的model能够归档、model中属性嵌套model也能够正常运行。
献上github源码,下载下来直接使用就能够。想了一下是否要支持cocoapod或者carthage,可是代码这么简单,仍是算了。
若是有任何不符合规范或者遗漏的地方,请各路大神指教。
github: https://github.com/DawnWdf/NSObjectExtention
PPS:另外代码中有实现copying协议的方法,与coding相似,不赘述。可变对象的copy协议,因为可是没什么可用的地方因此注释了。有兴趣的能够本身尝试。
还有字典转换model的方法,纯粹自娱自乐,请你们忽略。
Modify 5/7/2017
自定义model:person不实现Copying协议也能够放到字典key中的办法
NSValue *value = [NSValue valueWithNonretainedObject:object]; NSDictionary *dic = @{value:@"value for person"}; NSLog(@"%@",dic); NSLog(@"%@",[(Person *)value.nonretainedObjectValue name1]);