前言
基于OC开发中,避免不了和JSON数据打交道,界面数据填充,我们可以通过原生的NSDictionary取值,这样做不是很优雅,于是我们通过一个字典去初始化一个模型类,通过属性名取值,但这样似乎不是很自动化。于是后来就有了JSON自动转模型框架,如MJExtension、YYModel等高性能转化框架。而MJExtension 使用很简单,引入MJExtension后调用一行代码即可,由于MJExtension是给NSObject增加了category,因此使用该框架不需要修改数据model的继承关系,无代码入侵。MJExtension可以轻松实现JSON和模型互转,自定义别名,自定义转换,归档解档,总之相当的强大。
实现原理
通过阅读源码,MJExtension的原理就是使用runtime获取该类和其所有父类的所有的属性名,并根据属性名在数据字典中获取对应的值,然后通过setValue:forKey设置属性的值。
以下MJExtension中的核心代码及runtime API
// ***** 获取父类, 返回Class
class_getSuperclass(Class _Nullable cls)
// ***** 获取属性列表, 返回数据类型 objc_property_t * 数组.
class_copyPropertyList(Class _Nullable cls, unsigned int * _Nullable outCount)
// 示例:
unsigned int outCount = 0;
objc_property_t *properties = class_copyPropertyList(c, &outCount);
// ***** 获取属性名,返回char *类型,可转为NSString.
property_getName(objc_property_t _Nonnull property)
// 示例:
objc_property_t property;
NSString *name = @(property_getName(property));
// ***** 获取property的attribute,返回char *类型,可转为NSString. 用于获取property的类型
property_getAttributes(objc_property_t _Nonnull property)
// 示例:
objc_property_t property;
NSString *attrs = @(property_getAttributes(property));
// ***** 使用KVO给数据model的property赋值,value为字典中取出的数据, key为数据模型object的属性名.
[object setValue:value forKey:key];
复制代码
框架思维导图
核心代码简介
NSObject+MJKeyValue
主要作用: 遍历该类所有的属性(包括定义在父类中的属性),封装成MJProperty类型返回. 并根据MJProperty中定义的属性名从数据字典中取值(这里要求字典中的key值的名称与属性名相同), 赋值给model的属性.
/**
核心代码:
*/
- (instancetype)mj_setKeyValues:(id)keyValues context:(NSManagedObjectContext *)context
{
// 获得JSON对象
......
//通过封装的方法回调一个通过运行时编写的,用于返回属性列表的方法。
[clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
@try {
// 0.检测是否被忽略
......
// 1.取出属性值
id value;
NSArray *propertyKeyses = [property propertyKeysForClass:clazz];
......
// 如果没有值,就直接返回
if (!value || value == [NSNull null]) return;
// 2.复杂处理
MJPropertyType *type = property.type;
......
// 3.赋值
[property setValue:value forObject:self];
} @catch (NSException *exception) {
......
}
}];
......
return self;
}
复制代码
NSObject+MJProperty
主要作用: 获取属性并封装成MJProperty的具体实现.
#pragma mark - --公共方法--
+ (void)mj_enumerateProperties:(MJPropertiesEnumeration)enumeration {
// 获得成员变量
......
// 遍历成员变量
......
}
#pragma mark - 公共方法
+ (NSMutableArray *)mj_properties
{
NSMutableArray *cachedProperties = [self mj_propertyDictForKey:&MJCachedPropertiesKey][NSStringFromClass(self)];
if (cachedProperties == nil) {
if (cachedProperties == nil) {
cachedProperties = [NSMutableArray array];
[self mj_enumerateClasses:^(__unsafe_unretained Class c, BOOL *stop) {
// 1.获得所有的成员变量
......
// 2.遍历每一个成员变量
for (unsigned int i = 0; i<outCount; i++) {
......
}
// 3.释放内存
free(properties);
}];
[self mj_propertyDictForKey:&MJCachedPropertiesKey][NSStringFromClass(self)] = cachedProperties;
}
}
return cachedProperties;
}
复制代码
NSObject+MJClass
主要作用:遍历所有的父类,用于获取父类的属性.
+ (void)mj_enumerateClasses:(MJClassesEnumeration)enumeration
{
// 1.没有block就直接返回
if (enumeration == nil) return;
// 2.停止遍历的标记
BOOL stop = NO;
// 3.当前正在遍历的类
Class c = self;
// 4.开始遍历每一个类
while (c && !stop) {
// 4.1.执行操作
enumeration(c, &stop);
// 4.2.获得父类
c = class_getSuperclass(c);
if ([MJFoundation isClassFromFoundation:c]) break;
}
}
复制代码
其他功能代码简介
- 设置类属性的黑白名单,可以定向解析或忽略某些属性.
#pragma mark - 属性白名单配置
/**
* 这个数组中的属性名才会进行字典和模型的转换
*
* @param allowedPropertyNames 这个数组中的属性名才会进行字典和模型的转换
*/
+ (void)mj_setupAllowedPropertyNames:(MJAllowedPropertyNames)allowedPropertyNames;
#pragma mark - 属性黑名单配置
/**
* 这个数组中的属性名将会被忽略:不进行字典和模型的转换
*
* @param ignoredPropertyNames 这个数组中的属性名将会被忽略:不进行字典和模型的转换
*/
+ (void)mj_setupIgnoredPropertyNames:(MJIgnoredPropertyNames)ignoredPropertyNames;
复制代码
NSObject+MJKeyValue源码解析:
- 对类属性的缓存,解析一次该类的属性之后,下次不会重复解析
+ (NSMutableArray *)mj_properties {
//获取已缓存的property数组
NSMutableArray *cachedProperties = [self dictForKey:&MJCachedPropertiesKey][NSStringFromClass(self)];
if (cachedProperties == nil) {
//未缓存过,初始化数组.
//解析propertys并添加进cachedProperties数组中.
......
//缓存属性数组
[self dictForKey:&MJCachedPropertiesKey][NSStringFromClass(self)] = cachedProperties;
}
return cachedProperties;
}
复制代码
3.动态修改某些值特性的属性值
在自己定义的数据model中可以通过实现 mj_newValueFromOldValue:property: 方法来替换某些属性的值.
例如:在CutsomModel中写以下代码,可以实现给名为CutsomProperty的属性赋值为CutsomValue;
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property {
if ([property.name isEqualToString:@"CutsomProperty"]) {
return @"CutsomValue";
} else {
return oldValue;
}
}
复制代码
NSObject+MJKeyValue中源码解析
- (instancetype)mj_setKeyValues:(id)keyValues context:(NSManagedObjectContext *)context {
......
//返回所有的属性, 已封装成MJProperty类型.
//MJProperty中有该属性的属性名,属性类型等信息.
[clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
@try {
......
//如果model实现了mj_newValueFromOldValue: property方法,则会返回新的值.
id newValue = [clazz mj_getNewValueFromObject:self oldValue:value property:property];
if (newValue != value) { // 有过滤后的新值
[property setValue:newValue forObject:self];
return;
}
.....
} @catch (NSException *exception) {
......
}
}];
return self;
}
复制代码
属性类型说明
//An int
NSString *const MJPropertyTypeInt = @"i";
//A short
NSString *const MJPropertyTypeShort = @"s";
//A float
NSString *const MJPropertyTypeFloat = @"f";
// A double
NSString *const MJPropertyTypeDouble = @"d";
//A long`l` is treated as a 32-bit quantity on 64-bit programs.
NSString *const MJPropertyTypeLong = @"l";
//A long long
NSString *const MJPropertyTypeLongLong = @"q";
//A char
NSString *const MJPropertyTypeChar = @"c";
//A C++ bool or a C99 _Bool
NSString *const MJPropertyTypeBOOL1 = @"c";
NSString *const MJPropertyTypeBOOL2 = @"b";
//A character string (char *)
NSString *const MJPropertyTypePointer = @"*";
NSString *const MJPropertyTypeIvar = @"^{objc_ivar=}";
NSString *const MJPropertyTypeMethod = @"^{objc_method=}";
// An unknown type (among other things, this code is used for function pointers)
NSString *const MJPropertyTypeBlock = @"@?";
// A class object (Class)
NSString *const MJPropertyTypeClass = @"#";
//A method selector (SEL)
NSString *const MJPropertyTypeSEL = @":";
// An object (whether statically typed or typed id)
NSString *const MJPropertyTypeId = @"@";
复制代码
基于Runtime自动归档解档
如果模型属性很多的话,手动实现每个属性的归档解档,还是相当麻烦的,通过Runtime遍历成员变量,调用KVC,实现自动化归档解档
@implementation NSObject (MJCoding)
- (void)mj_encode:(NSCoder *)encoder
{
Class clazz = [self class];
NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames];
NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames];
[clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
// 检测是否被忽略
if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
if ([ignoredCodingPropertyNames containsObject:property.name]) return;
id value = [property valueForObject:self];
if (value == nil) return;
[encoder encodeObject:value forKey:property.name];
}];
}
- (void)mj_decode:(NSCoder *)decoder
{
Class clazz = [self class];
NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames];
NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames];
[clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
// 检测是否被忽略
if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
if ([ignoredCodingPropertyNames containsObject:property.name]) return;
id value = [decoder decodeObjectForKey:property.name];
if (value == nil) { // 兼容以前的MJExtension版本
value = [decoder decodeObjectForKey:[@"_" stringByAppendingString:property.name]];
}
if (value == nil) return;
[property setValue:value forObject:self];
}];
}
@end
复制代码
具体使用,在.m添加MJExtensionCodingImplementation宏定义即可
@implementation xxx
MJExtensionCodingImplementation
@end
复制代码
常用方法
自定义属性别名
/**
* 将属性名换为其他key去字典中取值
*
* @return 字典中的key是属性名,value是从字典中取值用的key
*/
+ (NSDictionary *)mj_replacedKeyFromPropertyName;
/**
* 将属性名换为其他key去字典中取值
*
* @return 从字典中取值用的key
*/
+ (id)mj_replacedKeyFromPropertyName121:(NSString *)propertyName
复制代码
模型包含数组模型
/**
* 数组中需要转换的模型类
*
* @return 字典中的key是数组属性名,value是数组中存放模型的Class(Class类型或者NSString类型)
*/
+ (NSDictionary *)mj_objectClassInArray;
复制代码
字典转模型
/**
* 通过字典来创建一个模型
* @param keyValues 字典(可以是NSDictionary、NSData、NSString)
* @return 新建的对象
*/
+ (instancetype)mj_objectWithKeyValues:(id)keyValues;
复制代码
模型转字典
/**
* 将模型转成字典
* @return 字典
*/
- (NSMutableDictionary *)mj_keyValues;
复制代码
当字典转模型完毕时调用
- (void)mj_didConvertToObjectWithKeyValues:(NSDictionary *)keyValues;
复制代码
自定义转换,返回新的值
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property;
复制代码
结语
优秀的框架设计能力,每个类都有其单一的功能,通过组合统一,实现了一套友好易于使用的API接口,上手非常方便。Runtime技术很强大,应用也是非常的广泛。