青春不是用来迷茫任性的
拿到网络数据,创建模型定义属性,这些不是很死板,写得很频繁很枯燥的代码吗?
为此我写了一个NSObject分类自动生成代码,实现:
+ (void)autoCreatePropertyCodeWithDict:(NSDictionary *)dict {
NSMutableString *strM = [NSMutableString string];
// 1.遍历字典,把字典中的所有key取出来,生成对应的属性代码
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *type;
if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")]) {
type = @"NSString";
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]){
type = @"NSArray";
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]){
type = @"NSNumber";
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]){
type = @"NSDictionary";
}
NSString *str;
if ([type containsString:@"NSString"]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) %@ *%@;",type,key];
}else if ([type containsString:@"NS"]) {
str = [NSString stringWithFormat:@"@property (nonatomic, strong) %@ *%@;",type,key];
}else{
str = [NSString stringWithFormat:@"@property (nonatomic, assign) %@ %@;",type,key];
}
[strM appendFormat:@"\n%@\n",str];
}];
NSLog(@"\n\n/**************自动生成属性代码**************/\n %@ \n/**************自动生成属性代码**************/\n\n",strM);
}
用法:当我拿到数据 po打印一下
F339C92C-0B51-4A01-AF71-8F548E88108B.png
然后复制到模型中即可
网友评论