Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer doesn't pass arguments to the selector

I create an NSTimer:

    [NSTimer scheduledTimerWithTimeInterval:2.0
                                     target:self
                                   selector:@selector(createObject:)
                                   userInfo:nil
                                    repeats:YES];

and createObject: is defined as follows:

- (void)createObject:(ccTime) dt{

    int r = arc4random() % 4;


    for (int i=0; i < r; i++) {

    character[charIndex] = [CCSprite spriteWithFile:@"o.png"];

    }
}

What I want to achieve is to send some variables into the method. I rewrote the function as:

- (void)createObject:(ccTime) dt cID:(int)cID {

    int r = arc4random() % 4;


    for (int i=0; i < r; i++) {

    character[cID] = [CCSprite spriteWithFile:@"o.png"];

    }
}

but I can't pass the variable cID to the function from the timer. Is it possible to do this?

like image 802
Ahoura Ghotbi Avatar asked Nov 28 '22 22:11

Ahoura Ghotbi


1 Answers

according to the documentation methods that are called from a NSTimer need a signature like this:

- (void)timerFireMethod:(NSTimer*)theTimer

It is not possible to provide custom parameters, or more than one parameter.


So rewrite your timer method so it uses the userInfo of the NSTimer

- (void)createObject:(NSTimer *)timer {
    NSDictionary *userInfo = [timer userInfo];
    int cID = [[userInfo objectForKey:@"cID"] intValue];
    /* ... */
}

create a userInfo and then start the timer like this:

NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithInt:cID], @"cID",
                          /* ... */
                          nil];
[NSTimer scheduledTimerWithTimeInterval:2.0
                                 target:self
                               selector:@selector(createObject:)
                               userInfo:userInfo
                                repeats:YES];
like image 148
Matthias Bauch Avatar answered Dec 18 '22 16:12

Matthias Bauch