2013-07-30 162 views
1

我一直有问题让NSTimer触发,我认为它必须解决多线程问题。为了确保正确创建计时器,我创建了以下测试代码,并将其放入我的主视图控制器的initWithNibName中。令我惊讶的是,它也未能在那里开枪。NSTimer永远不会触发

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的使用。

回答

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

我的印象是,该方法包含签名的目标和选择信息下;如果不是,它的目的是什么? – Regan

+1

没有。方法签名只是一个字符串,它描述了选择器的格式以及一些关于参数堆栈对齐的无用信息。 NSInvocation需要它来使消息转发机制在原始目标上的调用失败的情况下工作。 – CodaFi

相关问题