how to get instanceName by String
In Objective-C how to get instance name by certain rules?
For example:
Type1: self.btn(0,1,2,3,4,5,6,7,8,9...) in for loop get number from i
for(int i = 0; i<10; i++){
//wrong code ( similar ActionScript3.0 code)
self."btn"+i = [UIButton buttonWithType:UIButonTypeRoundRect];
//i think code but, not available
self.[NSString stringWithFormat:@"btn%d", i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
}
Type2: UIButton *btn(0,1,2,3,4,5,6,7,8,9...) in for loop get number from i
for(int i =0; i<10; i++){
//wrong code ( similar ActionScript3.0 code)
UIButton *"btn"+i = [UIButton buttonWithType:UIButtonTypeRoundRect];
//i think code but, not available
UIButton *[NSString stringWithFormat:@"btn%d", i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
}
So, In ActionScript3.0 Soruce is below.
for( var i=0; i<10; i++){
this["btn"+i] = new SimpeButton();
//btn0, btn1, btn2...btn1开发者_开发问答0 get by for loop i object Simpebutton ten.
}
In objective c there is no instance name for buttons. There is a tag property, where you can store integer value so you can recognize proper button. You can create buttons in a loop, set a proper tag property and store in an array:
NSMutableArray *buttonsArray = [[NSMutableArray alloc] init];
for( var i=0; i<10; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundRect];
button.tag = i;
[buttonsArray addObject:button];
}
and then you can loop this array in one way:
for (UIButton *aButton in buttonsArray) {
// do something with aButton instance
}
or another:
for (int i=0; i<[buttonsArray count]; i++) {
// do something with [buttonsArray objectAtIndex:i];
}
That precise idiom doesn't exist in Objective-C. The equivalent is to use an NSArray (or, for cases where the identifiers aren't sequentially numbered, an NSDictionary).
精彩评论