I've been having problems getting an NSTimer to fire, and I assumed it had to with multi-threading issues. Just to be sure I was creating the timer correctly, I created the following test code and I placed it into my main view controller's initWithNibName. Much to my surprise, it also failed to fire there.

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(timerTest:paramTwo:paramThree:)]];
NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";
[invocation setArgument:&a atIndex:2]; //indices 0 and 1 are target and selector respectively, so params start with 2
[invocation setArgument:&b atIndex:3];
[invocation setArgument:&c atIndex:4];
[[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:5 invocation:invocation repeats:NO] forMode:NSDefaultRunLoopMode];

Any clues as to what is wrong with this code? It seems to do exactly what the documentation specifies for using an NSInvocation with an NSTimer.

有帮助吗?

解决方案

NSInvocations also have to have a target and a selector in addition to a method signature and arguments:

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(timerTest:paramTwo:paramThree:)]];
NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";
[invocation setArgument:&a atIndex:2]; //indices 0 and 1 are target and selector respectively, so params start with 2
[invocation setArgument:&b atIndex:3];
[invocation setArgument:&c atIndex:4];
[invocation setTarget:self];
[invocation setSelector:@selector(timerTest:paramTwo:paramThree:)];
[[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:1 invocation:invocation repeats:NO] forMode:NSDefaultRunLoopMode];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top