29

ココアで特定の時間を待つためのより簡単な方法は、私が以下で思いついたものよりもありますか?

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

明確にするために、このコードには機能上の問題はありません。私の唯一の牛肉は文体的なものです。私の場合、フローは機能するほど単純ですが、カプセル化するか、いくつかの条件をスローすると、状況が醜くなる可能性があります。この(架空の)例のようなコードで、待ってから同じポイントに戻る方法が見つからなかったのは、ちょっとしつこいことでした。

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

7 に答える 7

73

There is

usleep(1000000);

and

[NSThread sleepForTimeInterval:1.0f];

both of which will sleep for 1 second.

于 2010-02-09T20:43:53.663 に答える
13

これがNSTimerのやり方です。使用している方法よりも醜いかもしれませんが、イベントを繰り返すことができるので、私はそれを好みます。

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

usleep()のように、アプリがハングして応答しなくなってしまうようなことは避けたいと考えています。

于 2010-02-09T20:51:51.303 に答える
3

I'm not sure if it exists (yet), but with blocks in 10.6 (or PLBlocks in 10.5 and on the iPhone) it should be pretty easy to write a little wrapper like performBlock:afterDelay: that does exactly what you want without the need to sleep the entire thread. Would be a useful little piece of code indeed.

Mike Ash has written about an approach like this on his blog:

NSString *something = ...;
RunAfterDelay(0, ^{
    NSLog(@"%@", something);
    [self doWorkWithSomething: something];
});
于 2010-02-09T20:44:30.530 に答える
2

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.

于 2010-02-09T20:42:53.727 に答える
2

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

于 2010-02-09T20:45:46.217 に答える
1

非同期ソリューションを気にしない場合は、次のようにします。

[[NSOperationQueue currentQueue] addOperationWithBlock:^{
    [self doStuffAfterWaiting];
}];
于 2016-09-17T22:40:23.307 に答える
0

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?

于 2010-02-09T20:42:59.250 に答える