美文网首页
关于iOS项目中BaseModel

关于iOS项目中BaseModel

作者: 我是卖报的小行家 | 来源:发表于2020-06-01 10:10 被阅读0次

关于关键字替换或者其他的使用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

相关文章

网友评论

      本文标题:关于iOS项目中BaseModel

      本文链接:https://www.haomeiwen.com/subject/nrdjzhtx.html