Is it possible to set the text field for a UITextField for multiple objects from within a loop using setValue:forKey:? I am a little confused if I should be somehow specifying "text" in the property name, or if I am missing something else?
// INTERFACE
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_01;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_02;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_03;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_04;
@property(nonatomic, retain) IBOutlet UITextField *textFieldBit_05;
.
// IMPLEMENT
@synthesize textFieldBit_01;
@synthesize textFieldBit_02;
@synthesize textFieldBit_03;
@synthesize textFieldBit_04;
@synthesize textFieldBit_05;
for(unsigned int counter=1; counter<=5; counter++) {
NSString *propertyName = [[NSString alloc] initWithFormat:@"textFieldBit_%02d.text",counter];
NSString *propertyValue = [[NSString alloc] initWithFormat:@"%d", counter];
[self setValue:propertyValue forKey:propertyName];
[propertyName release]开发者_C百科;
[propertyValue release];
}
EDIT_001
Maybe I should try and clarify my question a little: I am essentially trying to set the text on one of 5 UITextFields each time round a loop. I could use an "if" or "switch" but that looks a little like overkill. I thought maybe setValue:forKey: would let me do it by building a unique key during each iteration and using a single call.
if(counter == 1) [textFieldBit_01 setText:@"%02d", 1];
if(counter == 2) [textFieldBit_02 setText:@"%02d", 2];
if(counter == 3) [textFieldBit_03 setText:@"%02d", 3];
if(counter == 4) [textFieldBit_04 setText:@"%02d", 4];
if(counter == 5) [textFieldBit_05 setText:@"%02d", 5];
EDIT_002
NSString *propertyName = [[NSString alloc] initWithFormat:@"labelBit_%02d.text",counter];
NSString *propertyValue = [[NSString alloc] initWithFormat:@"%d", geoTag];
[self setValue:propertyValue forKeyPath:propertyName];
Thank you for the answer, I now understand where I was going wrong, what I was using was setValue:forKey: when in a situation where I needed to access "labelBit_01.text" I should have been using setValue:forKeyPath:
gary
Try
[self setValue:propertyValue forKeyPath:[propertyName stringByAppendingString:@".text"]];
What this ends up giving you is this:
self.textFieldBit_01.text = @"01";
精彩评论