Waiting for a specified duration in Cocoa

前端 未结 7 1890
生来不讨喜
生来不讨喜 2020-12-29 03:41

Is there a more straightforward way to wait for a specific amount of time in Cocoa than what I have come up with below?

- (void) buttonPressed {
    [self ma         


        
相关标签:
7条回答
  • 2020-12-29 03:47

    What's wrong with a simple usleep? I mean, except for the sake of "Cocoa purity", it's still much shorter than other solutions :)

    0 讨论(0)
  • 2020-12-29 03:50

    If you don't mind an asynchronous solution, here you go:

    [[NSOperationQueue currentQueue] addOperationWithBlock:^{
        [self doStuffAfterWaiting];
    }];
    
    0 讨论(0)
  • 2020-12-29 03:53

    There is

    usleep(1000000);
    

    and

    [NSThread sleepForTimeInterval:1.0f];
    

    both of which will sleep for 1 second.

    0 讨论(0)
  • 2020-12-29 03:53

    You probably want to use an NSTimer and have it send a "doStuffAfterWaiting" message as your callback. Any kind of "sleep" will block the thread until it wakes up. If it's in your U.I. thread, it'll cause your app to appear "dead." Even if that's not the case, it's bad form. The callback approach will free up the CPU to do other tasks until your specified time interval is reached.

    This doc has usage examples and discusses the differences on how & where to create your timer.

    Of course, performSelector:afterDelay: does the same thing.

    0 讨论(0)
  • 2020-12-29 04:00

    Here's the NSTimer way of doing it. It's might be even uglier than the method you're using, but it allows repeating events, so I prefer it.

    [NSTimer scheduledTimerWithTimeInterval:0.5f 
                                     target:self
                                   selector: @selector(doSomething:) 
                                   userInfo:nil
                                    repeats:NO];
    

    You want to avoid something like usleep() which will just hang your app and make it feel unresponsive.

    0 讨论(0)
  • 2020-12-29 04:03

    To wait, there is NSThread sleepForTimeInterval:.

    This solution was actually taken from: What's the equivalent of Java's Thread.sleep() in Objective-C/Cocoa?

    0 讨论(0)
提交回复
热议问题