2
votes

For an NSOperation subclass with a call to NSRunloop in the start method as below:

NSRunLoop * runloop = [NSRunLoop currentRunLoop];
while (!stopRunloop && [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

The nsoperation is added to an NSOperationQueue [and not main queue]. I need runloop so as to get callback from a library doing some background tasks. My questions are as below: 1. Does the thread that prepares NSOperation copies all its data to the thread in which NSOperation runs [when start method execution begins] ? 2. Why the above while loop not able to terminate despite the stopRunloop is getting updated from library callback with value YES ? 3. Does a start method also need an @autoreleasepool usage ?

Thanks

2

2 Answers

1
votes

You can stop the run loop using the Core Foundation API:

CFRunLoopStop(CFRunLoopGetCurrent());

See "Exiting the Run Loop" in Run Loop Management.

0
votes

When a thread is created, it does not have a run loop associated with it - that is up to you to manage. The runloop must have at least one input source associated with it.

If you have runloop dependent code in the operation (such as networking), the operation can finish or exit quickly when the runloop has no input source attached to it. One way to managed this is to attach an input source such as an NSPort inside the operation, and remove it when the operation is "done". The cleanest way to do this is by integrating the source management with NSOperation's state using KVO (i.e. attach the port when isReady or isExecuting goes to YES, remove it when isCancelled or isFinished is set to YES).