2013-07-30 1 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]; 

이 코드의 잘못된 점에 대한 단서가 있습니까? NSTner와 함께 NSInvocation을 사용하기 위해 설명서에서 지정한 내용을 정확하게 수행하는 것으로 보입니다.

답변

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

I은 ​​메소드 서명 대상 및 선택 정보를 포함하는 인상 하였다; 그렇지 않다면 그 목적은 무엇입니까? – Regan

+1

Nope. 메서드 시그니처는 셀렉터의 형식을 설명하는 문자열이며 인수의 스택 정렬에 관한 쓸모없는 정보입니다. NSInvocation은 원래 대상에 대한 호출이 실패 할 경우 메시지 전달 메커니즘을 작동시키기 위해이를 필요로합니다. – CodaFi