问题描述
如果在iOS中发生某些事件之前如何在NSThread内等待?
How to wait inside the NSThread until some event occur in iOS?
例如,我们创建了一个NSThread并启动了一个线程循环。在线程循环内部,有条件检查消息队列是否有任何消息。如果有消息,那么它将调用相应的方法来执行某些操作,否则它应该等到消息队列填充新消息。
eg, We created a NSThread and started a thread loop. Inside the thread loop, there is condition to check whether the message queue has any messages. If there is a message, then it will call the corresponding method to do some operation, else it should wait until the message queue gets populated with a new message.
是否存在是否有任何API或方法可以等到某个事件发生?
Is there any API or methods available to wait until some event occur?
For Example
NSThread *thread = [NSThread alloc]....@selector(threadLoop)
- (void)threadLoop
{
// Expecting some API or method that wait until some messages pushed into the message queue
if (...) {
}
}
应该感谢任何帮助。
推荐答案
您可以使用NSCondition。
我在ViewController中附加示例代码ready-for-test
You can use NSCondition.I attach example code "ready-for-test" in a ViewController
@interface ViewController ()
@property (strong, nonatomic) NSCondition *condition;
@property (strong, nonatomic) NSThread *aThread;
// use this property to indicate that you want to lock _aThread
@property (nonatomic) BOOL lock;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// start with the thread locked, update the boolean var
self.lock = YES;
// create the NSCondition instance
self.condition = [[NSCondition alloc]init];
// create the thread and start
self.aThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadLoop) object:nil];
[self.aThread start];
}
-(void)threadLoop
{
while([[NSThread currentThread] isCancelled] == NO)
{
[self.condition lock];
while(self.lock)
{
NSLog(@"Will Wait");
[self.condition wait];
// the "did wait" will be printed only when you have signaled the condition change in the sendNewEvent method
NSLog(@"Did Wait");
}
// read your event from your event queue
...
// lock the condition again
self.lock = YES;
[self.condition unlock];
}
}
- (IBAction)sendNewEvent:(id)sender {
[self.condition lock];
// put the event in the queue
...
self.lock = NO;
[self.condition signal];
[self.condition unlock];
}
这篇关于如何在NSThread中等待,直到iOS发生某些事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!