前言
1.大家平时在数据请求时候一般用的MVC模式,然后创建模型,要写繁琐的属性。
2.当打印模型的时候,模型也只能打印出一个地址,不能看到模型里面属性具体值,又要去重写它的描述。
- 以上内容麻烦,然后突然一天看到个大神的简书,模仿他自己重新写了个NSObject的分类,一行代码生成所有属性和描述。你只是粘贴复制你Log内容了。
- 重写描述里面有些类型要改一下,但是json数据为空的要自己判断,如果哪位大神有其他方法还请告知。
效果图
- 生成的属性和重写描述
步骤
-
大家网络请求到的json数据一般如下:
然后添加一个NSObject的分类,里面符号一大堆脑口痛,你只需粘贴复制,代码内容如下:
+(void)propertyCodeWithDictionary:(NSDictionary *)dict
{
NSMutableString *strM = [NSMutableString string];
NSMutableString *descriptionHeader = [NSMutableString stringWithFormat:@"[NSString stringWithFormat:%@\"",@"@"];
NSMutableString *descriptionEnd = [NSMutableString string];
NSInteger count = [dict count];
__block NSInteger index = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key,
id _Nonnull obj,
BOOL * _Nonnull stop) {
// NSLog(@"类型%@\n",[obj class]);
NSString *str;
NSString *Header;
index ++;
if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")] || [obj isKindOfClass:NSClassFromString(@"NSTaggedPointerString")] || [obj isKindOfClass:NSClassFromString(@"__NSCFConstantString")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;",key];
Header = [NSString stringWithFormat:@"%@:%@,\\n",key,@"%@"];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;",key];
Header = [NSString stringWithFormat:@"%@:%@,\\n",key,@"%@"];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSArray *%@;",key];
Header = [NSString stringWithFormat:@"%@:%@,\\n",key,@"%@"];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSDictionary *%@;",key];
Header = [NSString stringWithFormat:@"%@:%@,\\n",key,@"%@"];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
Header = [NSString stringWithFormat:@"%@:%@,\\n",key,@"%d"];
}
if ([obj isKindOfClass:(NSClassFromString(@"NSNull"))]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@ (null);",key];
Header = [NSString stringWithFormat:@"%@:%@,\\n",key,@"%@"];
}
[descriptionEnd appendFormat:@"_%@,",key];
[descriptionHeader appendFormat:@"%@",Header];
[strM appendFormat:@"\n%@",str];
}];
if (count == index && count > 0) {
[descriptionHeader replaceCharactersInRange:NSMakeRange(descriptionHeader.length - 3, 3) withString:@"\","];
[descriptionEnd replaceCharactersInRange:NSMakeRange(descriptionEnd.length - 1, 1) withString:@"];"];
}
NSLog(@"\n\n*******模型所有属性,自己要改下(默认空的数据为字符串)*******%@",strM);
NSLog(@"\n\n***************重写模型的描述粘贴复制这句***************\nreture %@%@",descriptionHeader,descriptionEnd);
}
3.最后在请求成功得到数据的Block里面一句话
[NSObject propertyCodeWithDictionary:<#请求得到的模型字典#>];
4.通过打印设置你模型的属性,还有重新描述。
5.打印模型就再也不担心只是个地址了。