日常開(kāi)發(fā)中已骇,我們拿到接口文檔,會(huì)根據(jù)接口返回的數(shù)據(jù)來(lái)寫(xiě)模型。
在之前我都是根據(jù)返回的字典一個(gè)個(gè)key這樣對(duì)照著來(lái)創(chuàng)建模型屬性宴偿。后面遇到項(xiàng)目中有時(shí)候返回的數(shù)據(jù)里面要寫(xiě)成模型屬性的key實(shí)在是太多昭齐,寫(xiě)起來(lái)花時(shí)間容易寫(xiě)錯(cuò)又沒(méi)什么技術(shù)含量尿招。
這時(shí)候就應(yīng)該動(dòng)用開(kāi)發(fā)人員該有的程序思想了,干脆讓它自動(dòng)生成不就好了阱驾。廢話不多說(shuō)上代碼就谜。
- (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);
}
這個(gè)方法利用NSDictionary類里面的這個(gè)方法幫我們遍歷字典里面所有的key和value,期間要做的事情寫(xiě)到block中里覆,也就是幫我們自動(dòng)生成屬性代碼丧荐。
- (void)enumerateKeysAndObjectsUsingBlock:(void (^ _Nonnull)(KeyType _Nonnull key, ObjectType _Nonnull obj, BOOL * _Nonnull stop))block
至于怎么用,可以寫(xiě)成NSDictionary的一個(gè)分類喧枷。然后用字典對(duì)象直接調(diào)用就好虹统。像這樣[dict createPropertyCode]。就可以幫我們打印出屬性代碼隧甚,然后復(fù)制粘貼就好车荔。在面對(duì)屬性超多的模型時(shí),是不是方便許多了戚扳。
當(dāng)然你也可以根據(jù)需要做一些調(diào)整忧便,這里也只是提供一個(gè)開(kāi)發(fā)中的小技巧,讓機(jī)器幫我們做事往往