What's the equivalent of Java's Thread.sleep() in Objective-C/Cocoa?

不羁岁月 提交于 2019-11-28 17:15:50

问题


In Java you can suspend the current thread's execution for an amount of time using Thread.sleep(). Is there something like this in Objective C?


回答1:


Yes, there's +[NSThread sleepForTimeInterval:]

(Just so you know for future questions, Objective-C is the language itself; the library of objects (one of them at least) is Cocoa.)




回答2:


Sleeping for one second in Java:

Thread.sleep(1000);

Sleeping for one second in Objective C:

[NSThread sleepForTimeInterval:1.0f];



回答3:


Why are you sleeping? When you sleep, you are blocking the UI and also any background URL loading not in other threads (using the NSURL asynchronous methods still operates on the current thread).

Chances are what you really want is performSelector:withObject:AfterDelay. That's a method on NSObject you can use to call a method at some pre-determined interval later - it schedules a call that will be performed at a later time, but all of the other stuff the thread handles (like UI and data loads) will still continue.




回答4:


Of course, you could also use the standard Unix sleep() and usleep() calls, too. (If writing Cocoa, I'd stay with the [NSThread sleepForTimeInterval:], however.)




回答5:


If you use NSThread sleepForTimeInterval(commented code) to sleep, fetching data will be blocked, but +[NSThread sleepForTimeInterval:] (checkLoad method) will not block fetching data.

My example code as below:

- (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];
    }
}



回答6:


usleep() can also be used as ive used this to pause the current thread at times



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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!