Bha*_*ath 10 iphone objective-c nsthread nsrunloop ios
在iOS中发生某些事件之前,如何在NSThread内等待?
例如,我们创建了一个NSThread并启动了一个线程循环.在线程循环内部,有条件检查消息队列是否有任何消息.如果有消息,那么它将调用相应的方法来执行某些操作,否则它应该等到消息队列填充新消息.
是否有任何API或方法可用于等待某些事件发生?
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 (...) {
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助应该被赞赏.
Lom*_*baX 14
您可以使用NSCondition.我在ViewController中附加了示例代码"ready-for-test"
@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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14495 次 |
| 最近记录: |