I am creating a list of bar buttons with its action functions (sFuncName
as below), it is dynamically changed.
When user clicks on a button, sFuncName
will be called.
for(int i = 0; i < 3 ; i++){
NSString* sFuncName = [NSString stringWithFormat:@"OnFunc_%d:", i ];
barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem target:self
action:NSSelectorFromString(sFuncName)];
}
The que开发者_JAVA百科stion is: have I got any way to dynamically declare sFuncName
to respond to buttons?
Example:
for(int i = 0; i < 3 ; i++){
NSString* sFuncName = [NSString stringWithFormat:@"OnFunc_%d:", i ];
- (void)sFuncName: (id)sender; //sFuncName: OnFunc_0, OnFunc_1, OnFunc_2
}
I don't see the advantage of creating a method declaration dynamically, as the code within these methods wouldn't be dynamic either.
So you should rather declare a single method which would be called by every button, to which you pass a tag or a reference to the sender (button) or some other value that enables your method to tell which button has been tapped prior to the method being called. You could do something like this:
-(void)buttonPressed: (int)tag {
if (tag == 0) {
// Code for first button
}
if (tag == 1) {
// Code for second button
}
// prepare code for further buttons...
}
You really shouldn't do this, this is bad coding practice and i promise you at some point in development you will regret it. On the other hand what you CAN do, is process stuff with blocks (like functions you declare inline and on the stack).
You would declare a block inline something like that:
void (^doStuff)(int, char *) = ^(int arg0, char *arg1) {
printf("hello block");
};
doStuff(1, "a");
doStuff(2, "b");
...
What you can do is make a subclass of your button that executes a given block statement on click.
More on Blocks: developer.apple.com
精彩评论