日常開發中,我們拿到接口文檔,會根據接口返回的數據來寫模型。
在之前我都是根據返回的字典一個個key這樣對照著來創建模型屬性。后面遇到項目中有時候返回的數據里面要寫成模型屬性的key實在是太多,寫起來花時間容易寫錯又沒什么技術含量。
這時候就應該動用開發人員該有的程序思想了,干脆讓它自動生成不就好了。廢話不多說上代碼。
- (void)createPropertyCode
{
NSMutableString *codes = [NSMutableString string];
// 遍歷字典
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {
NSString *code;
if ([value isKindOfClass:[NSString class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key];
} else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
} else if ([value isKindOfClass:[NSNumber class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];
} else if ([value isKindOfClass:[NSArray class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];
} else if ([value isKindOfClass:[NSDictionary class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];
}
// @property (nonatomic, strong) NSString *source;
[codes appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",codes);
}
這個方法利用NSDictionary類里面的這個方法幫我們遍歷字典里面所有的key和value,期間要做的事情寫到block中,也就是幫我們自動生成屬性代碼。
- (void)enumerateKeysAndObjectsUsingBlock:(void (^ _Nonnull)(KeyType _Nonnull key, ObjectType _Nonnull obj, BOOL * _Nonnull stop))block
至于怎么用,可以寫成NSDictionary的一個分類。然后用字典對象直接調用就好。像這樣[dict createPropertyCode]。就可以幫我們打印出屬性代碼,然后復制粘貼就好。在面對屬性超多的模型時,是不是方便許多了。
當然你也可以根據需要做一些調整,這里也只是提供一個開發中的小技巧,讓機器幫我們做事往往