以最少的代码让自定的model实现NSCoding、NSCopying协议

项目中用到了自定义的model:Person(栗子)。此model需要可以实现归档的功能,但是属性非常多,且类似的model很多。如果按照常规去写归档的代码,那么无论是写起来还是维护起来都非常困难。

由于model继承自NSObject,所以给NSObject添加了扩展用来实现自定义model的归档功能。实现思路来源于伟大的网络和MJExtention,所以应该不算是原创吧,反正这个实现也快烂大街了。

大致为:

1:获取当前类及父类的class及属性名称和类型

2:实现归档常规方法

3:宏定义常规方法,方便实现

最主要的方法为第一步。

NSObject (Coding).m

- (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).m

- (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]);
原文地址:https://www.cnblogs.com/PhenixWang/p/7093650.html