Objective C: Sending arguments to a method called by a UIButton

后端 未结 6 714
甜味超标
甜味超标 2021-01-06 10:26

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 cr

6条回答
  •  生来不讨喜
    2021-01-06 11:23

    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:

    
    @interface ClickDelegate : NSObject {
        NSTimer timer;
    }
    
    @property (nonatomic, assign) NSTimer *timer;
    
    - (void)clickAction:(id)sender;
    
    @end
    
    
    @implementation ClickDelegate
    
    @synthesize timer; 
    
    - (void)clickAction:(id)sender {
        // do what you need (like destroy the NSTimer)
    }
    
    @end
    
    

    Then change the target:

    
    // In your view controller
                          
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:(0.009) target:self selector:@selector(moveStickFig:) userInfo:stickFig repeats:YES];                                                                               
       
    // Instantiate a new delegate for your delegate action
    // and set inside of it all the objects/params you need
    ClickDelegate *aDelegate = [[ClickDelegate alloc] init];
    aDelegate.timer = timer;
    
    [stickFig addTarget:aDelegate action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.myDelegate = aDelegate; // as suggested in the comments, you need to retain it
    [aDelegate release]; // and then release it
    
    

    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

提交回复
热议问题