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

我怕爱的太早我们不能终老 提交于 2019-11-29 21:09:28
smorgan

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.)

Sleeping for one second in Java:

Thread.sleep(1000);

Sleeping for one second in Objective C:

[NSThread sleepForTimeInterval:1.0f];

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.

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.)

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

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

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