How to wait in NSThread until some event occur in iOS?

前端 未结 3 1025
野性不改
野性不改 2021-02-14 10:10

How to wait inside the NSThread until some event occur in iOS?

eg, We created a NSThread and started a thread loop. Inside the thread loop, there is condition to check w

3条回答
  •  余生分开走
    2021-02-14 10:46

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

提交回复
热议问题