IOS setValue类似于Java里面的反射机制。
使用这个方法,根据属性名称来设置属性。这个方法,在拥有大量按一定规则命名的属性时尤其有用。
比如,某个类,有如下代表每列的数组,命名格式是:@”column%dArray” :
1 | @property (strong, nonatomic) NSArray *column1Array; |
2 | @property (strong, nonatomic) NSArray *column2Array; |
3 | @property (strong, nonatomic) NSArray *column3Array; |
4 | @property (strong, nonatomic) NSArray *column4Array; |
5 | @property (strong, nonatomic) NSArray *column5Array; |
如果一个个给属性赋值,那要写大量的重复性代码。
利用setValue方法,只要在一个循环里,就可以设置好这些属性:
1 | for ( int i=1; i<=5; i++) { |
2 | UIImageView *appleView = [[UIImageView alloc] initWithImage:apple]; |
3 | UIImageView *barView = [[UIImageView alloc] initWithImage:bar]; |
4 | UIImageView *cherryView = [[UIImageView alloc] initWithImage:cherry]; |
5 | UIImageView *lemonView = [[UIImageView alloc] initWithImage:lemon]; |
6 | UIImageView *sevenView = [[UIImageView alloc] initWithImage:seven]; |
7 | NSArray *imageViewArray = [[NSArray alloc] initWithObjects:appleView,barView,cherryView,lemonView,sevenView, nil]; |
8 | NSString *fieldName = [[NSString alloc] initWithFormat:@ "column%dArray" ,i]; |
9 | NSLog(@ "set value for key:%@" ,fieldName); |
10 | [self setValue:imageViewArray forKey:fieldName]; |
同样,在读取属性的时候,也可以根据当前的条件生成属性名称,用属性名称读取属性:
1 | - (UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view |
3 | NSString *arrayName = [[NSString alloc] initWithFormat:@ "column%dArray" ,component+1]; |
4 | NSArray *array = [self valueForKey:arrayName]; |
6 | return [array objectAtIndex:row]; |