NSTimer永远不会开火

时间:2013-07-30 19:55:14

标签: objective-c macos nstimer nsinvocation

我在解决NSTimer问题时遇到了问题,我认为它必须解决多线程问题。为了确保我正确地创建了计时器,我创建了以下测试代码,并将其放入我的主视图控制器的initWithNibName中。令我惊讶的是,它也未能在那里开火。

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];

有关此代码有什么问题的任何线索?它似乎完全符合文档为使用带有NSTimer的NSInvocation指定的内容。

1 个答案:

答案 0 :(得分:3)

除了方法签名和参数之外,

NSInvocations还必须有一个目标和一个选择器:

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];