问题
I'd like to make a custom class that extends NSOperation in order to make successful communication with another device by bluetooth. The question I have is how can I implement the main method of the class so that it will wait for an event triggered by the bluetooth?
回答1:
Never use an infinite loop. It is not energy-efficient. As @lead_the_zeppelin said, use semaphore/mutex/etc. For example you may use dispatch_group
functions like this:
dispatch_group_t waitGroup = dispatch_group_create();
dispatch_group_enter(waitGroup);
dispatch_async(otherQueue, ^{
//long-running code
dispatch_group_leave(waitGroup);
}
dispatch_group_wait(waitGroup, DISPATCH_TIME_FOREVER);
回答2:
What I did was just use continuous loop in a while until some event will trigger a BOOL to stop the loop. I don't know if this is safe, but it works.
while(!self.didFinish){
;
}
来源:https://stackoverflow.com/questions/30372160/nsoperation-wait-for-event