如果我正确理解你,请问如何将DRY(不要重复自己)应用于此代码。
«更多二 - 使用for»艾兹赫尔·戴克斯特拉
或
«更多二 - 使用枚举» vikingosegundo
- (void)viewDidLoad { // or loadView, see Rob's answer
[super viewDidLoad];
NSArray *properties= @[@{@"color": [UIColor orangeColor], @"text": @"Ceterum censeo"},
@{@"color": [UIColor cyanColor], @"text": @"Carthaginem esse"},
@{@"color": [UIColor purpleColor], @"text": @"delendam"}];
[properties enumerateObjectsUsingBlock:^(NSDictionary *properties, NSUInteger idx, BOOL *stop) {
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, (idx + 1) * 20, 200, 20)];
l.backgroundColor = properties[@"color"];
l.text = properties[@"text"];
l.font= [UIFont italicSystemFontOfSize:12];
[self.view addSubview:l];
}];
}
好的,为什么我更喜欢这个基于块的枚举?
因为它有一个突变保护并为我提供了正确的免费索引,我需要这个框架。
A C for
-loop for (int idx = 0; idx < [properties count]; ++idx)
给了我正确的索引,但我必须包括一个额外的语句来获取对象NSDictionary *property = properties[idx];
,当它不具有突变后卫:它可以反复可能导致不好的东西在改变。
快速枚举for(NSDictionary *property in properties)
具有这样的变异保护,并且枚举比块枚举更快一些。但它有一个很大的缺点,即如果我需要索引,我必须调用NSUIndex idx = [properties indexForObject:property];
,而不是线性的,导致二次运行时性能:再见,速度优势。更糟的是:如果一个数组包含相同的对象,它将只能重复地找到第一个 - 这是创建错误数据的好机会。
根据代码数量的不同,将其移入辅助方法可能会很有用 - 但这更多的是关于味道。
正如你到底问题是关于可读性,我想分享的口味另一回事:我喜欢对象创建封装到一个不同的范围:通过使用一个隐含的块
无论是
UILabel *label = ^{
UILabel *l =[[UILabel alloc] initWithFrame:CGRectMake(0, (idx + 1) * 20, 200, 20)];
l.backgroundColor = properties[@"color"];
l.text = properties[@"text"];
l.font= [UIFont italicSystemFontOfSize:12];
return l;
}();
[self.view addSubview:label];
或语句表达
UILabel *label = ({
UILabel *l =[[UILabel alloc] initWithFrame:CGRectMake(0, (idx + 1) * 20, 200, 20)];
l.backgroundColor = properties[@"color"];
l.text = properties[@"text"];
l.font= [UIFont italicSystemFontOfSize:12];
l;
});
[self.view addSubview:label];
注意,由于WWDC2015苹果(终于!!!)discou鼓励使用'tag'来跟踪观点。请参阅[Cocoa Touch最佳实践](https://developer.apple.com/videos/wwdc/2015/?id=231) – vikingosegundo