NSTimer + NSInvocation causing crash on iOS 7

767 views Asked by At

I'm running into a crash when using +[NSTimer scheduledTimerWithTimeInterval:invocation:repeats] on iOS 7. The code is straightforward enough; here is the copy paste (with variable renames) in its entirety.

SEL selector = @selector(callback);
NSMethodSignature *signature = [self methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[NSTimer scheduledTimerWithTimeInterval:0.5 invocation:invocation repeats:NO];

When the timer fires, my app crashes with the following stack trace:

enter image description here

I thought that maybe one of the variables was no longer retained (even though NSTimer's documentation mentions that it retains all referenced parameters), so I strongly retained all of the variables to self. Unfortunately, the crash persists.

Thanks in advance!

2

There are 2 answers

1
Shamsudheen TK On BEST ANSWER

You are missing this line [self.invocation setSelector:selector];

This will work

SEL selector = @selector(callback);
NSMethodSignature *signature = [self methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:selector];
[NSTimer scheduledTimerWithTimeInterval:0.5 invocation:invocation repeats:NO];

- (void)callback
{
    NSLog(@"triggered");
}

Output:

triggered
5
Chris Ricca On

This answer seems to suggest you need to call setSelector: on the invocation in addition to init-ing it with the signature.