objective-c 在 Cocoa 中等待指定的持续时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2232366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Waiting for a specified duration in Cocoa
提问by Purple Ninja Girl
Is there a more straightforward way to wait for a specific amount of time in Cocoa than what I have come up with below?
有没有比我在下面提出的更直接的方法来等待 Cocoa 中的特定时间?
- (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 functionalproblem with this code -- my only beef is a stylisticone. 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];
}
回答by Brad Larson
There is
有
usleep(1000000);
and
和
[NSThread sleepForTimeInterval:1.0f];
both of which will sleep for 1 second.
两者都会休眠 1 秒。
回答by Jason Moore
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 的做法。它可能比你使用的方法更丑陋,但它允许重复事件,所以我更喜欢它。
[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.
你想避免像 usleep() 这样只会挂起你的应用程序并让它感觉没有响应的东西。
回答by Ole Begemann
I'm not sure if it exists (yet), but with blocks in 10.6 (or PLBlocksin 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.
我不确定它是否存在(还),但是使用 10.6 中的块(或10.5 和 iPhone 上的PLBlocks)应该很容易编写一个像performBlock:afterDelay:这样的小包装器,它可以完全满足您的需求,而无需睡眠整个线程。确实会是一段有用的小代码。
Mike Ash has written about an approach like this on his blog:
Mike Ash在他的博客上写过类似这样的方法:
NSString *something = ...;
RunAfterDelay(0, ^{
NSLog(@"%@", something);
[self doWorkWithSomething: something];
});
回答by F'x
What's wrong with a simple usleep? I mean, except for the sake of "Cocoa purity", it's still much shorter than other solutions :)
一个简单的有什么问题usleep?我的意思是,除了“可可纯度”之外,它仍然比其他解决方案短得多:)
回答by pestilence669
You probably want to use an NSTimerand 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.
您可能想要使用NSTimer并让它发送“doStuffAfterWaiting”消息作为您的回调。任何类型的“睡眠”都会阻塞线程,直到它醒来。如果它在你的 UI 线程中,它会导致你的应用看起来“死了”。即使事实并非如此,这也是糟糕的形式。回调方法将释放 CPU 以执行其他任务,直到达到您指定的时间间隔。
This dochas usage examples and discusses the differences on how & where to create your timer.
本文档提供了使用示例,并讨论了创建计时器的方式和位置的差异。
Of course, performSelector:afterDelay: does the same thing.
当然, performSelector:afterDelay: 做同样的事情。
回答by Malaxeur
To wait, there is NSThread sleepForTimeInterval:.
等待,有NSThread sleepForTimeInterval:。
This solution was actually taken from: What's the equivalent of Java's Thread.sleep() in Objective-C/Cocoa?
这个解决方案实际上取自:Objective-C/Cocoa 中 Java 的 Thread.sleep() 的等价物是什么?
回答by Julian F. Weinert
If you don't mind an asynchronous solution, here you go:
如果您不介意异步解决方案,请执行以下操作:
[[NSOperationQueue currentQueue] addOperationWithBlock:^{
[self doStuffAfterWaiting];
}];

