2011-10-25 2 views
2

저는 재단 도구를 쓰고 있습니다. 다른 진행중인 작업과 분리하기 위해 스레딩을해야합니다.FoundationTool의 Runloop

스레딩을 시도했지만 지속적으로 충돌이 발생했습니다. 그리고 마침내 나는 내 자신의 runloop을 실행해야하는 이유를 알아 냈습니다.

간단한 예를 들어 도울 수 있습니까? 다음 코드를 시도했지만 작동하지 않습니다. 내가 그것을 실행할 때마다 Exception과 충돌이 발생합니까? 재단 도구에서 스레드를 어떻게 실행합니까?

@interface MyClass : NSObject 
{ 
} 
-(void) doSomething; 
@end 

@implementation MyClass 
-(void) RunProcess: 
{ 
    printf("test"); 
} 
-(void) doSomething: 
{ 
    [NSThread detachNewThreadSelector: @selector(RunProcess:) toTarget:self withObject: nil]; 
} 
@end 

int main(void) 
{ 

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    MyClass *myObj = [[MyClass alloc] init], 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj selector:@selector(doSomething:) userInfo:nil repeats:NO]; 
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; 
    [[NSRunLoop currentRunLoop] run]; 

    [pool drain]; 
    return 0; 
} 
+0

-RunProcess :를 구현하는 위치는 어디입니까? – voidzm

+0

이것은 문제를 설명하기 위해 작성한 샘플입니다. 어쨌든 위의 코드를 업데이트했습니다. – MacGeek

+1

예외는 무엇입니까? –

답변

5
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj 
     selector:@selector(doSomething:) userInfo:nil repeats:NO]; 

공지 사항 당신의 선택은 콜론과 인수 -doSomething:이며, 아직 구현으로 당신의 방법은 콜론과 인수하지 않고, -doSomething입니다. 사실, 메서드 선언 (-doSomething)이 구현 (-doSomething:)과 일치하지 않습니다. 그것은 당신의 예제를 타이핑 할 때의 실수 일뿐, 그것이 실제로 당신의 코드에 있는지 여부는 분명하지 않습니다. 제기 된 예외는 무엇입니까?

이 실수가 코드에있는 경우 타이머는 이해할 수없는 메시지를 MyClass 개체로 보내는 것으로 끝나기 때문에 예외가 발생합니다.

당신은 가능성이 +scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:에 대한 설명서에서 권장하는대로 타이머가 다음에 화재로 설정 방법을 변경해야합니다 :

@interface MyClass : NSObject { 

} 
-(void)doSomething:(NSTimer *)timer; 
@end 

@implementation MyClass 

-(void)doSomething:(NSTimer *)timer { 
     [NSThread detachNewThreadSelector:@selector(RunProcess:) 
     toTarget:self withObject:nil]; 
} 

@end 
+0

사실, 코드 단편의 메소드 정의에는 콜론이 있습니다. 즉,이 코드는 컴파일에 실패합니다. –

+0

고맙습니다. 나를 미치게 만들었다. – MacGeek

2

예외를 보지 않고를, 내가 당신이하려고하는 것을 지적 할 수 실행 루프에 타이머를 예약하십시오 (실행 루프가없는 상태에서 scheduledTimerWithTimeInterval:... 사용). 타이머를 만들려면 timerWithTimeInterval:...