Dan Loewenherz
Dan Loewenherz

Reputation: 11253

NSTimer + NSInvocation causing crash on iOS 7

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!

Upvotes: 1

Views: 747

Answers (2)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

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

Upvotes: 2

Chris Ricca
Chris Ricca

Reputation: 61

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

Upvotes: 1

Related Questions