I have a method that is being called when a UIButton is clicked. When I create the button I want it to store an NSTimer as an argument.
This is the timer and the creation of the UIButton. How would I add in the timer to be sent down to the method? I've tried withObject:timer
but it gives me a warning and crashes at runtime.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:(0.009) target:self selector:@selector(moveStickFig:) userInfo:stickFig repeats:YES];
[stickFig addTarget:self action:@selector(tapFig:andTime:) forControlEvents:UIControlEventTouchUpInside];
This is the method I'm sending it down to:
-(void) tapFig:(id)sender andTime:(NSTimer *)timer
I've also tried [stickFig performSelector:@selector(tapFig:andTime) withObject:nil withObject:timer]
after I defined the UIButton, but that also results in a warning and crashes.
You could take the approach where you extend UIButton.
Then your method
And to set userInfo
Would that work for you?
You can create subclass of UIButton, add property in this subclass, store your object in this property and get it in action method through sender.
Modify your method to take a single
NSArray
as an argument. Then, create your array of parameters and pass it toperformSelector
.To be more clear:
You would create the
IBAction
required for the control's event and a second method that takes anNSArray
as an argument. When theIBAction
method is called, it would call the second method after creating theNSArray
of parameters. Think of it as a "method chain."You need to make the timer a property of your view controller and then referenced it from your
tapFig:
method. Here is what your code might look like:MainViewController.h
MainViewController.m
Notice the
@property
declaration in the header file. I'd consider taking another look at the timer initialization too, but that could just be me. I hope this helps!You can't - UIControl action selectors are invoked with no parameters, the control that is the source of the action, or the control that is the source of the action and the UIEvent which occurred on that control. In IB you have to connect the UIButton to such a method: you can't add any other custom parameters.
If you want it to have access to other objects, they need to be instance variables.
Review Apple's Introduction to Objective C if you want to understand how to define instance variables.
I suggest to create a small support class that works like a delegate that simply takes care of the click action for you, then change the target of your
addTarget
method.First create your support class:
Then change the target:
In this way you're delegating the click callback to another object. This case is really simple (you just need to get the NSTimer instance) but in a complex scenario it also helps you to design the application logic by delegating different stuff to different small classes.
Hope this helps! Ciao