问题描述:

I need to pass an integer to my method startEvent:. The method is a timer's action method. I've read about how to pass data with userInfo, however I don't understand how to do that so I can still call the method as I'd normally do.

How do I pass integers from an NSTimer and from a regular call to the same method?

[NSTimer scheduledTimerWithTimeInterval:0.032f target:self selector:@selector(startEvent:) userInfo:nil repeats:NO];

[self startEvent: 0];

-(void)startEvent:(int) event {

// ...

}

网友答案:

Use a pass-through for the timer's action method:

- (void)startEventFromTimer:(NSTimer *)tim
{
    [self startEvent:[[tim userInfo] intValue]];
}

Where your timer was created with an NSNumber for its user info object.

[NSTimer scheduledTimerWithTimeInterval:0.032f 
                                 target:self 
                               selector:@selector(startEventFromTimer:) 
                               userInfo:@(theIntYouWantToPass)
                                repeats:NO];
网友答案:

You are starting from a fundamental misunderstanding. Your method cannot be the timers action method unless it conforms to the documented signature.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html

  • (void)timerFireMethod:(NSTimer *)timer

The only opportunity you have to pass additional information in is via the userinfo object, as Josh Caswells answer demonstrates.

相关阅读:
Top