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]; |
一樣,在讀取屬性的時候,也能夠根據當前的條件生成屬性名稱,用屬性名稱讀取屬性:code
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]; |