IOS setValue:根据属性名称设置属性

IOS setValue相似于Java里面的反射机制。

使用这个方法,根据属性名称来设置属性。这个方法,在拥有大量按必定规则命名的属性时尤为有用。数组

好比,某个类,有以下表明每列的数组,命名格式是:@”column%dArray” :app

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;

若是一个个给属性赋值,那要写大量的重复性代码。atom

利用setValue方法,只要在一个循环里,就能够设置好这些属性:spa

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];
11 }

一样,在读取属性的时候,也能够根据当前的条件生成属性名称,用属性名称读取属性:code

1 - (UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
2 {
3     NSString *arrayName = [[NSString alloc] initWithFormat:@"column%dArray",component+1];
4     NSArray *array = [self valueForKey:arrayName];
5
6     return [array objectAtIndex:row];
7 }
相关文章
相关标签/搜索