2011-04-30 5 views
0

객체 배열을 반복하는 루프를 작성하여 for 루프를 작성했습니다. 이제 사용자가 IBAction을 호출하는 버튼을 클릭 할 때까지 루프 반복을 중단 할 수 있는지 스스로 묻습니다.for 루프 반복을 일시 중지하여 사용자 입력을 기다림

for (int i = 0; i < [array count]; i++) { 
    // do something with the object 

    // wait for action method called 
    // user clicked action so go on 
} 

답변

3

귀하의 경우에 맞게 코드를 적용 할 수 있습니다. 기본적으로 루프를 여러 메시지로 "언 롤링"합니다. [self doItForIndex:[NSNumber numberWithInt:0]];

- (BOOL)canDoitForIndex:(NSNumber *)i { 
    // return YES if you want to go ahead 
    // (e.g. test a BOOL you set in response to the user tapping a button 
} 

- (void)waitForIndex:(NSNumber *)i { 
    if ([self canDoItForIndex:i]) { 
     // do anything to clean up for i 
     // then repeat for i+1: 
     [self doItForIndex:[NSNumber numberWithInt:[i intValue]+1]]; 
    } else { 
     [self performSelector:_cmd withObject:i afterDelay:0.01f; 
    } 
} 

- (void)doItForIndex:(NSNumber *)i { 
    if ([i intValue] < lastIndex) { 
     // do what you have to do 
     [self waitForIndex:i]; 
    } 
    // else you're done 
} 

애플의 NSRunLoop 개념 순서를 시작하면 꽤 빨리 처리를 완료 할 예정이다. 당신이 뭔가를 기다려서 메인 스레드를 묶는다면, 당신의 앱에있는 어떤 것도 일어날 수 없다. 위의 코드는 "대기"를 여러 메시지 전송으로 나누고 앱의 반응을 유지합니다.

+0

많은 도움을 주셔서 감사합니다. –

1

ODRM 알고리즘은 매우 잘 작동합니다. 이와

[self performSelector:_cmd withObject:i afterDelay:0.01f]; 

: 나는 UI 요소의 업데이트가 없었

[NSThread sleepForTimeInterval:0.25]; 
    [NSThread detachNewThreadSelector:_cmd toTarget:self withObject:i]; 

, 우리가 백그라운드 스레드에서 대기 강제로 더 나은했다 난 그냥이 줄을 변경했습니다.

+0

좋은 개선, 메인 스레드를 차단하지 마십시오. – alinoz