Waiting for a specified duration in Cocoa

2019-02-02 21:50发布

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

    // give the user some visual feedback and wait a bit so he can see it
    [self displayThoseChangesToTheUser];
    [self performSelector:@selector(buttonPressedPart2:) withObject:nil afterDelay:0.35];
}

- (void) buttonPressedPart2: (id)unused {
    [self automaticallyReturnToPreviousView];
}

Just to be clear, there is no functional problem with this code -- my only beef is a stylistic one. In my case the flow is simple enough that it works, but try to encapsulate it or throw in some conditionals and things could turn ugly. It's been kind of nagging at me that I couldn't find a way to wait and then return to that same point in code like this (fictitious) example:

- (void) buttonPressed {
    [self doStuff];
    [UIMagicUnicorn waitForDuration:0.35];
    [self doStuffAfterWaiting];
}

7条回答
forever°为你锁心
2楼-- · 2019-02-02 22:02

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-02 22:03

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.

查看更多
beautiful°
4楼-- · 2019-02-02 22:13

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

[[NSOperationQueue currentQueue] addOperationWithBlock:^{
    [self doStuffAfterWaiting];
}];
查看更多
在下西门庆
5楼-- · 2019-02-02 22:14

There is

usleep(1000000);

and

[NSThread sleepForTimeInterval:1.0f];

both of which will sleep for 1 second.

查看更多
孤傲高冷的网名
6楼-- · 2019-02-02 22:15

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

查看更多
Explosion°爆炸
7楼-- · 2019-02-02 22:15

Tadah!

Slightly more informative, the link points to NSThread sleepForTimeInterval:

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

查看更多
登录 后发表回答