iPhone - how to pass an object to a button action
I have to pass an object to an button's action... something like
开发者_开发问答[myButton addTarget:self action:@selector(sendIt:MY_OBJECT) forControlEvents:UIControlEventTouchDown];
I cannot set a variable and use that on the method because I am on a static class.
How do I do that?
You cannot, the signature of an button's action is always*) -(IBAction)methodToCall:(id)sender
where sender
is your button, or whatever is calling the action.
I cannot set a variable and use that on the method because I am on a static class.
I am not sure what you mean with this.
*) There are a couple of other signatures new on the iPhone compared to the Mac, but none of those allow passing objects either.
The UIButton cannot pass object to event selector. You can use the property tag example:
myButton.tag = SOMEBUTTON_ID;
Also you can cast pointer to you object to NSInteger and assign it to tag property, but this technique does not solve problem of the lifetime of the object and in the future, such code may stop working.
I discovered a way to do that.
You create a class of UIButton and inside the class you declare a public variable that corresponds to the type of object you want to pass.
When you create the button you use that class and store the object inside its property.
then when the button is clicked you retrieve the ID, retrieve the button and the object stored inside it.
Now you have the object...
精彩评论