Asynchronous NSUrlConnection not on main runloop
I am creating a set of classes which interface with a web service. At the core of this, the data is retrieved from the service using an asynchronous NSUrlConnection. In my mind, it is important that it is asynchronous, as a client of these web service interfaces has to have the ability to cancel a request that is in progress (ie cancel an NSUrlConnection).
The web service calls return JSON data, potentially lots of it, and this is parsed and the classes I am creating will create proper data structures out of them. Depending on which web service method is called, the request can end up being expensive - too expensive to run on the main thread, so I would like to either add the option of running the service requests asynchronously, or not giving the option, and forcing asynchronous calls.
Async calls are all well and good, but I am having problems starting an NSUrlConnection asynchronously on a runloop that isn't the main one. The problem I'm describing seems to be fairly well documented: I am led to believe the delegate of the NSUrlConnection is not called because the runloop that launches the connection has terminated, and therefore the calls back to the delegate cannot be scheduled on its runloop.
What is the best way to go about solving this issue?
I have tried using:
while (!self.isRequestComplete && !self.isRequestCancelled)
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
It seems to work ok from the basic trial I have done, except if the runloop that this is being executed on is actually the main runloop, for which I have had a few crashes...
Would an option be to offer asynchronous calls to clients, and then use the above method if the option is utilised? Is there a better way of achieving what I am trying to do?
What I am aiming to achieve is for a package of classes that allow interfacing with my specific web service, where the clients of my code do not need to worry about whether their own delegates (which my classes hold references to) will be called on different threads. I want them to be called on the exact same runloop that they called my code on - basically, exactly how NSUrlConnection operates!
Thanks in advance! Nick
I think you may have "gone up the wrong creek" so to speak. Generally speaking you don't need to worry about run loops unless you are doing something rather odd. It sounds like you need to do some reading on multi-threading, particularly Grand Central Dispatch.
链接地址: http://www.djcxy.com/p/30594.html