development

Objective-C / Cocoa에서 Java의 Thread.sleep ()에 해당하는 것은 무엇입니까?

big-blog 2020. 8. 5. 07:27
반응형

Objective-C / Cocoa에서 Java의 Thread.sleep ()에 해당하는 것은 무엇입니까?


Java에서는 Thread.sleep ()을 사용하여 현재 스레드의 실행을 일정 시간 중단 할 수 있습니다. Objective C에 이와 같은 것이 있습니까?


예, + [NSThread sleepForTimeInterval :]이 있습니다

미래의 질문에 대해 Objective-C는 언어 자체이며 객체 라이브러리 (적어도 하나 이상)는 코코아입니다.


자고 일초 자바 :

Thread.sleep(1000);

자고 일초 목표의 C :

[NSThread sleepForTimeInterval:1.0f];

왜 자니? 휴면 상태 일 때 UI 및 다른 스레드에서로드되지 않는 백그라운드 URL로드를 차단하고 있습니다 (NSURL 비동기 메소드 사용은 여전히 ​​현재 스레드에서 작동 함).

실제로 원하는 것은 performSelector : withObject : AfterDelay입니다. 그것은 NSObject에서 나중에 미리 정해진 간격으로 메소드를 호출하는 데 사용할 수있는 메소드입니다. 나중에 수행 될 호출을 예약하지만 스레드가 처리하는 다른 모든 것들 (UI 및 데이터로드와 같은)은 여전히 계속합니다.


물론 표준 Unix sleep () 및 usleep () 호출도 사용할 수 있습니다. (하지만 Cocoa를 쓰면 [NSThread sleepForTimeInterval :]을 유지합니다.)


NSThread sleepForTimeInterval (commented code)을 사용하여 절전 모드로 전환하면 데이터 가져 오기는 차단되지만 + [NSThread sleepForTimeInterval :] (checkLoad 메서드)은 데이터 가져 오기를 차단하지 않습니다.

아래 예제 코드는 다음과 같습니다.

- (void)viewDidAppear:(BOOL)animated
{
//....
//show loader view
[HUD showUIBlockingIndicatorWithText:@"Fetching JSON data"];
//    while (_loans == nil || _loans.count == 0)
//    {
//        [NSThread sleepForTimeInterval:1.0f];
//        [self reloadLoansFormApi];
//        NSLog(@"sleep ");
//    }
[self performSelector:@selector(checkLoad) withObject:self afterDelay:1.0f];
}

-(void) checkLoad
{
    [self reloadLoansFormApi];
    if (_loans == nil || _loans.count == 0)
    {
        [self performSelector:@selector(checkLoad) withObject:self afterDelay:1.0f];
    } else
    {
        NSLog(@"size %d", _loans.count);
        [self.tableView reloadData];
        //hide the loader view
        [HUD hideUIBlockingIndicator];
    }
}

usleep ()은 이것을 사용하여 현재 스레드를 때때로 일시 중지시키는 데 사용할 수 있습니다.

참고 : https://stackoverflow.com/questions/829449/whats-the-equivalent-of-javas-thread-sleep-in-objective-c-cocoa

반응형