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?
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With