iOS, NSURLConnection: Delegate Callbacks on Different Thread?

后端 未结 4 1422
借酒劲吻你
借酒劲吻你 2020-12-28 10:20

How can I get NSURLConnection to call it\'s delegate methods from a different thread instead of the main thread. I\'m trying to mess around with the scheduleInRunLoop:forMod

4条回答
  •  孤城傲影
    2020-12-28 10:51

    NSURLConnection is already doing the download off of the main thread asynchronously. If I understand your question, you would like the delegate messages to be sent on a thread other than the main thread? You can't do that as you can't modify the internal implementation of NSURLConnection. I can think of two ways to simulate this.

    1. Create a sublcass of NSURLConnection (e.g. MyURLConnection) that assigns itself as own delegate. Note that this creates an intentional retain cycle so be careful. MyURLConnection should define a new delegate that supports NSURLConnectionDelegate. Let's call this finalDelegate. When MyURLConnection handles it's own delegate messages, forward or dispatch them to finalDelegate on whatever thread you like.

    2. Similar to option #1 but without the subclass. Handle the NSURLConnection delegate methods on the main thread and forward/dispatch them to whatever thread you like.

    The main difference is if you want a reusable subclass that behaves this way or it's a one off implementation.

    EDIT: added suggestion on how to run code in the background

    If you are going to process the response in the background I would either use operations or grand central dispatch. No need to mess around with run loops and creating threads. Check out Apple's Concurrency Programming Guide.

提交回复
热议问题