简体   繁体   中英

Passing a variable defined in a function to NSTimer function objective-c

I'm defining a variable in my function and trying to pass it to a nstimer. Is this possible? My concern is the function is removed from the callback stack and the variable no longer exists in memory (because we're waiting some time before we actually call anything on the parameters created in the prior method) Here's an example:

...
static NSTimer *oldTimer;

-(void)someFunction
{
    SKEmitterNode *left = [SKEmitterNode nodeWithFileNamed:leftParticle];

    if (oldTimer != nil)
    {
    [oldTimer invalidate];
    }

    oldTimer = [NSTimer scheduledTimerWithTimeInterval:sec target:self selector:@selector(doSomething:) userInfo:[NSArray arrayWithObjects: left, nil] repeats:NO];
}

-(void)doSomething:(NSTimer*)timer
{
    [[[timer userInfo] objectAtIndex:0] removeFromParent];
}

As Patrick Goley said, NSTimer retains the userInfo making it available inside of the selector method. Thanks again Patrick!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM