Re: Async NSURLConnection and blocks (was: Running NSURLConnection from within an NSOperation?)
Re: Async NSURLConnection and blocks (was: Running NSURLConnection from within an NSOperation?)
- Subject: Re: Async NSURLConnection and blocks (was: Running NSURLConnection from within an NSOperation?)
- From: Keith Duncan <email@hidden>
- Date: Tue, 22 Jun 2010 09:58:00 +0100
On 20 Jun 2010, at 21:42, John Heitmann wrote:
>
> On Feb 9, 2010, at 3:01 PM, Keith Duncan wrote:
>
>> ...you should create a 'concurrent' NSOperation as described in the documentation, and schedule your NSURLConnection on +[NSRunLoop mainRunLoop]. This will allow your NSOperation -start method to exit immediately and the thread to return to the pool.
>
> My first question is: doesn't this block the main loop with io?
Nope, it places the file descriptor for your socket into a select/kqueue loop somewhere that the system manages.
> With that code I get "attempt to pop an unknown autorelease pool". When I drop the release altogether the error goes away, but that seems like a leak.
Fixed version below:
> I have another version which uses a block to manually pump, but then this ties up an automatic block thread, which are supposed to be short-lived. Is it really a good practice to drive the NSURLConnection from the main loop?
>
> dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
> dispatch_async(queue, ^ {
> NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init];
>
> ResponseHandler *handler = [[ResponseHandler alloc] init];
> [handler initWithDelegate:delegate completionBlock:^ {
> dispatch_async(queue, ^ {
> NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
>
> […]
>
> [innerPool release];
> });
> }];
>
> NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:handler startImmediately:NO];
> [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
> [connection start];
>
> [outerPool release];
> });
Your autorelease pools are in different scopes. Autorelease pools are per-thread state and you need to return it to the default state (blank) at the end of your blocks. Your blocks are being executed on different threads.
Keith
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden