一段程序代码 --- 实现解析字典,自动转换生成属性。

来源:互联网 发布:淘宝官网网页版 编辑:程序博客网 时间:2024/05/29 08:05

创建一个NSObjcet的分类

//通过解析字典自动生成属性代码#import <Foundation/Foundation.h>@interface NSObjcet (Property)+(void)createPropertyCodeWithDict:(NSDictionary *)dict;@end
#实现文件#import "NSObject+Property.h"@implementation NSObject (Property)+ (void)createPropertyCodeWithDict:(NSDictionary *)dict{// 遍历字典[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull propertyName, id _Nonnull value, BOOL *_Nonnull stop){// 创建一个可变字符串,add字典每一个key所对应的模型数据NSMutableString strM = [NSMutableString string];// 属性代码(例如:@property(nonatomic,strong)NSString *name;   )NSString code;// 根据value的类型,判断对象的类型 (这里根据你返回数据的字段进行自行判定)if ([value isKindOfClass:NSClassFromString(@"__NSCFString")]){ //string code = [NSSring stringWithFormat:@"@property(nonatomic,strong)NSString *%@;",[propertyName];}else if ([value isKindOfClass:NSClassFromString(@"__NSCFNumber")]){ //number code = [NSSring stringWithFormat:@"@property(nonatomic,assign)NSInteger %@;",[propertyName];}else if ([value isKindOfClass:NSClassFromString(@"__NSCFArray")]){ //arraycode = [NSSring stringWithFormat:@"@property(nonatomic,strong)NSArray *%@;",[propertyName];}else if ([value isKindOfClass:NSClassFromString(@"__NSCFDictionary")]){ //dictionarycode = [NSSring stringWithFormat:@"@property(nonatomic,strong)NSDictionary *%@;",[propertyName];}[strM appendFormat:@"\n%@\n",code];NSLog("%@",strM);}];}<#注意:这个方法只能用于输出,然后你将输出的日志在写入你自己创建的model类当中,这段代码的作用仅此而已,没有实际用途,只是为了让我们不需要一个一个字段的@property去添加属性#>@end
#viewController中的调用//导入分类 类名调用方法[NSObject createPropertyCodeWithDict:dict];

日志: 将你的日志复制到对应的model 中

输出日志

这里就完结了,这样可以使我们不必再一个一个的去添加。早点休息。预祝好梦。

0 0
原创粉丝点击