When is a Cocoa callback given controll?
I've been searching around the web for an answe开发者_如何转开发r to this one, but was unable to find an answer, on the other side I think it's something quite common thus there is a possibility I'm missing some keywords here. Anyhow, the problem is as follows:
When is control given to a callback function in ObjC (iPhone)?
Does it happen after control is given to a high up in the hierarchy class responsible for the runloop? Can it occur in the middle of another function call being executed?
As an example, let's take the NSURLConnection, we don't know or can't predict when it's going to call didReceiveResponse or the other callback methods, can it be the case that didReceiveResponse get's called when I'm in the middle of another function? (highly doubt that but was unable to find information on callbacks wating for the end of the run loop)
Cheers, Kaspa
can it be the case that didReceiveResponse get's called when I'm in the middle of another function?
No, within a single thread, code is not executed in parallel. The runloop schedules the execution of all messages and dispatches them in sequences. Not even NSTimers are guaranteed to fire to the precision they are theoretically capable of because they have to wait for the runloop like everything else.
The callbacks will not be called from in a middle of your function, indeed. You have to give back control to the main runloop for it to process events, and call your callback.
If you want to know who exactly calls your callback, put a breakpoint in it, and check the stack trace.
The only time the didReceiveReponse will be called while something else is executing, is if you have launched the connection on it's own thread (typically in an NSOperation).
This is why when you do have connections in a background thread, you usually use something like performSelectorInMainThread to change the value for other parts of the application - though you can adjust properties directly if they are not marked nonatomic and are not mutable collections.
By default, basically all cocoa touch classes work entirely in a single thread, including many asynchronous operations like background network calls. The main exceptions are NSOperation and friends, and things related to NSThread.
The OS can do this by inserting its callbacks in the run loop schedule. There are also a few cases when one of your calls will also result in a callback on the same stack - for example, if you call resignFirstResponder on an object that notifies its delegate when this happens, such as UITextField.
A couple relevant blog posts:
- quick intro to NSRunLoop
- Friendly overview of Objective-C callbacks
精彩评论