uml
uml

Reputation: 1189

Invoking method via selector

I am writing a function in objective C. That is what I got:

int rndValue = (((int)arc4random()/0x100000000)*width);
timer1 = [NSTimer scheduledTimerWithTimeInterval:.01 
                                          target:self 
                           [self performSelector:@selector(doItAgain1:)  
                                      withObject:rndValue] 
                                        userInfo:nil
                                         repeats:YES];

The selector invokes this method and passes parameter:

-(void)doItAgain1:(int)xValuex{
}

At this stage the top code produces syntax error. Syntax error: 'Expected ] before performSelector' What is the prob? Best regards

Upvotes: 0

Views: 62

Answers (2)

iluvcapra
iluvcapra

Reputation: 9464

That line should probably read

timer1 = [NSTimer scheduledTimerWithTimeInterval:.01 
         target:self selector:@selector(doItAgain1:) 
         userInfo:nil repeats:YES];

You can't send a method argument with this call, in order to do that you have to do something like:

NSInvocation *inv = [NSInvocation invocationWithMethodSignature:
    [self methodSignatureForSelector:@selector(doItAgain1:)]];

[inv setSelector:@selector(doItAgain1:)];
[inv setTarget:self];
[inv setArgument:&rndValue atIndex:2];

timer1 = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval).01 
         invocation:inv 
         repeats:YES];

Upvotes: 2

sergio
sergio

Reputation: 69027

This would be more correct:

[NSTimer scheduledTimerWithTimeInterval:.01 target:self 
                 selector:@selector(doItAgain1:)
                 userInfo:[NSNumber numberWithInt:rndValue] repeats:YES];

Also notice that the syntax for the selector you call in this way must be:

- (void)doItAgain1:(NSTimer*)timer {

   int rndValue = [timer.userInfo intValue];
   ...
}

It is not possible to specify an int argument to such a timer selector, thus the trick to convert it into a NSNumber object.

Upvotes: 1

Related Questions