1

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!

Dan Loewenherz
  • 10,879
  • 7
  • 50
  • 81

2 Answers2

2

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
Shamsudheen TK
  • 30,739
  • 9
  • 69
  • 102
1

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

Community
  • 1
  • 1
  • Welcome to SO! It is usually common courtesy (if it isn't a rule somewhere) to let the OP know if his question is a duplicate. The answer that you post should be your own. That way if the answer that you link works, he can up-vote that answer and the credit can go to the correct person. – CaptJak Jan 09 '14 at 00:07
  • What does OP stand for? And how should I let her know? Comment on the question? – Chris Ricca Jan 09 '14 at 17:43
  • OP is Original Post (or poster). And you are correct, a comment on the question. I am not trying to discourage you from answering, or even telling you to delete this answer. Just a pointer with regards to answering questions :) – CaptJak Jan 09 '14 at 18:12
  • Appreciate it - I've used SO as long as it has been around, but this is my first time posting anything :) – Chris Ricca Jan 09 '14 at 19:55
  • well played, on both sides. – drew.. Apr 26 '15 at 23:56