Search code examples
iosobjective-cxcodenstimerexc-bad-access

Bad access with NSTimer while passing multiple parameters


XCode Image while project is running

I have come down to this simple NSTimer learning. It is working fine with no parameter at all. But with two parameters it is throwing bad-access. Am i passing parameters in right way or there is something else I missed out.

Although same problem has been referred here and here but none is solving the purpose.

Code correctness along with concept(why is it bad access) will be appreciated. Thanks.

@implementation ScreeLog1
-(void)tickTock{
    NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                                                  target: self
                                                selector:@selector(onTick::)
                                                userInfo: [NSDictionary                                                  dictionaryWithObjectsAndKeys:
                                                           @"a",@"b", nil]                                              repeats:NO];

}

-(void)onTick:(NSString *)message1 :(NSString *)message2 {
    NSLog(@"%@****%@\n",message1,message2);
}
@end

And yes i am using ARC, Xcode5.1


Solution

  • The selector you pass to the scheduledTimerWithTimeInterval method can only have one argument: the NSTimer. You handle your custom parameters via the userInfo dictionary.

    Try this:

    -(void)tickTock{
        NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                                                      target: self
                                                    selector:@selector(onTick:)
                                                    userInfo: [NSDictionary                                                  dictionaryWithObjectsAndKeys:
                                                               @"a",@"b",@"c",@"d", nil]
                                              repeats:NO];
    
    }
    
    -(void)onTick:(NSTimer *)timer {
        NSDictionary *userInfo = [timer userInfo];
        NSLog(@"%@*****%@\n", userInfo[@"b"], userInfo[@"d"]);
    }