1

我一直在让 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];

关于这段代码有什么问题的任何线索?它似乎完全按照文档指定的将 NSInvocation 与 NSTimer 一起使用。

4

1 回答 1

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];
于 2013-07-30T20:08:30.070 回答