YYModel
YYModel copied to clipboard
对于容器类需在modelContainerPropertyGenericClass 里面设定容器类型
@ibireme 对于容器类需在modelContainerPropertyGenericClass 里面设定容器类型,有时候会忘记设置或者不小心被干掉了,容器里面的保留的数据将是字典类型。这样外面业务层访问有可能会崩溃。能不能有办法 如果类型不匹配就直接返回nil 给这个容器呢?或者如果这个问题不普遍,我想自己定制yymodel?请教下有方案吗
hi,可以写一个BaseModel,然后在modelCustomTransformFromDictionary:这个方法里面遍历所有容器类属性,然后进行值的校验就可以判断是否是实现了modelContainerPropertyGenericClass方法:具体代码可以参考一下如下:
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic
{
// 遍历所有属性
unsigned int __propertyCount;
objc_property_t *__propertyList = class_copyPropertyList([self class], &__propertyCount);
for (int i = 0; i < __propertyCount; i++) {
objc_property_t __property = __propertyList[i];
NSString *__propertyAtt = [NSString stringWithUTF8String:property_getAttributes(__property)];
// 判断是容器类
if ([__propertyAtt rangeOfString:@"Array"].location != NSNotFound) {
NSString *__propertyName = [NSString stringWithUTF8String:property_getName(__property)];
id __propertyValue = [self valueForKey:__propertyName];
if ([__propertyValue isKindOfClass:[NSArray class]]) {
// 已经被初始化
// 在这里可以进一步校验是否有内容,内容是否是NSDictionary,如果是则说明没有用对应的model类接收
} else {
// 没有被初始化
// 该赋值
}
}
}
free(__propertyList);
return YES;
}` 但个人感觉这个倒是没有必要,既然使用了yymodel最基本的用法还是应该遵循的,如果忘记写容器类的对应的方法,直接导致崩溃可以提前暴露出问题,这样不更好吗?哈哈欢迎继续交流(code格式怎么弄啊)
如果这样写就做了很多多余的工作,感觉这个需求应该是YYModel的业务层面,应该由使用者按需实现比较好、
可以试试直接在头文件声明:https://github.com/ibireme/YYModel/issues/79