根据字典,生成property属性代码
- 遍历字典,根据value类型生成对应的属性
@implementation NSObject (Property)
+ (void)createPropertyCodeWithDictionary:(NSDictionary *)dict
{
// 必须先创建,否则下面输出为nil [nil appendFormat:xxx];
NSMutableString *stringM = [NSMutableString string];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
// created_at----__NSCFString
// NSLog(@"%@----%@", key, [obj class]);
NSString *code;
if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;", key];
} else if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;", key];
} else if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;", key];
} else if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;", key];
} else if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;", key];
}
// NSLog(@"%@", code);
[stringM appendFormat:@"\n%@\n", code];
}];
// 一次性输出好复制
NSLog(@"%@", stringM);
}
@end
如何使用?
- (void)viewDidLoad {
[super viewDidLoad];
// 1.获得json文件地址
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];
// 2.json转换为字典
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSArray *dictArray = dict[@"statuses"];
// 字典转property属性
[NSObject createPropertyCodeWithDictionary:dictArray[0][@"user"]];
}
代码资源:我的Github