2010-02-09 3 views
1

기본적으로 필자는 반복하고 다른 것들 중에서 하나씩 강조 표시하고 싶은 버튼 배열을 가지고 있습니다. 그 사이에 지연이 있습니다. 쉬운 일처럼 보입니다.하지만 응답 성이 뛰어나지 만 깨끗하게 작동 할 수는 없습니다.Cocoa Touch에서 반응 형 GUI를 유지하면서 지연하는 방법은 무엇입니까?

for MyButton *button in buttons { 
    [button highlight]; 
    [button doStuff]; 
    usleep(800000); // Wait 800 milliseconds. 
} 

그러나이 응답을, 그래서 내가 대신 실행 루프를 사용하여 시도 :

나는이 함께 시작했다.

void delayWithRunLoop(NSTimeInterval interval) 
{ 
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:interval]; 
    [[NSRunLoop currentRunLoop] runUntilDate:date]; 
} 

for MyButton *button in buttons { 
    [button highlight]; 
    [button doStuff]; 
    delayWithRunLoop(0.8); // Wait 800 milliseconds. 
} 

그러나 응답하지 않습니다.

이 작업을 수행하는 합리적인 방법이 있습니까? 스레드 또는 NSTimer을 사용하는 것이 번거로워 보입니다.

답변

2

NSTimer가이 작업에 적합합니다.

타이머 동작은 x 초 동안 실행됩니다. 여기서 x는 지정한 시간입니다.

두드러진 점은 스레드가 실행되는 스레드를 차단하지 않는다는 것입니다. Peter가이 대답에 대한 의견에서 말했듯이 타이머가 별도의 스레드에서 대기한다고 말하는 것은 잘못된 것입니다. 자세한 내용은 주석의 링크를 참조하십시오.

+0

NSTimer는 별도의 스레드를 사용하지 않습니다. 현재 스레드에서 실행 루프를 사용합니다. http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Timers/Articles/timerConcepts.html 및 http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation을 참조하십시오./Classes/NSTimer_Class /. –

1

Nevermind, Jasarien이 맞았습니다. NSTimer이 적합합니다.

- (void)tapButtons:(NSArray *)buttons 
{ 
    const NSTimeInterval waitInterval = 0.5; // Wait 500 milliseconds between each button. 
    NSTimeInterval nextInterval = waitInterval; 
    for (MyButton *button in buttons) { 
     [NSTimer scheduledTimerWithTimeInterval:nextInterval 
             target:self 
             selector:@selector(tapButtonForTimer:) 
             userInfo:button 
             repeats:NO]; 
     nextInterval += waitInterval; 
    } 
} 

- (void)tapButtonForTimer:(NSTimer *)timer 
{ 
    MyButton *button = [timer userInfo]; 
    [button highlight]; 
    [button doStuff]; 
} 
관련 문제