gpt4 book ai didi

iphone - 如何在 NSThread 中等待直到 iOS 中发生某些事件?

转载 作者:技术小花猫 更新时间:2023-10-29 10:59:59 26 4
gpt4 key购买 nike

如何在 NSThread 中等待直到 iOS 中发生某些事件?

例如,我们创建了一个 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 (...) {

}
}

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用 NSCondition。我在 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];
}

关于iphone - 如何在 NSThread 中等待直到 iOS 中发生某些事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com