Application crashes#168

Labels

Milestone

Assignee

4 participants

I have a navigation based app. Press a button on main view, then I push a new view to the navigation controller. All pretty basic stuff.

When the new view is loaded, I do an ASIHTTPRequest to fetch some json data, which is a list of image urls.
Then I do a for loop, create a bunch of ASIHTTPRequests, add them to a queue and then run the queue.

But if I click on the back button before the queue is finished, the app crashes.

The way I consider ugly is that you make a universal delegate that does all network traffic and is instantiated when the app is first run. I actually used the app delegate and listen to nsnotification center messages. It works like a charm, the app never crashes, but I think it is not optimal.

The best way is to not set the delegate and not use "setDidFinishSelector", but instead use "setCompletionBlock:^". This will only work on devices running iOS 4.0 and up, which is more than 90-95% and growing. This is just an awesome way and will not crash the application.

@Ricardo1980 It's because your ASIHTTPRequest instance is still has it's delegate property pointing to an object that is now gone.

Typically this happens when you've got transient delegates (like view controllers) making requests and (even if called -clearDelegatesAndCancel on ASI in dealloc or viewDidUnload), the response has has already been passed to the main thread. So the transient delegate gets dealloc'd, and the main thread tries to call the selector on it's invalid pointer. You can verify if this is your problem by setting an exception breakpoint and typing po $eax in gdb.

You can shut down the window for failure by calling -clearDelegatesAndCancel as early as possible, or as @traustitjmentions: if you're set on delegation, either make sure your ASI delegate is guaranteed to be there when the response executes (usually by making it a shared instance via dispatch_once_t), or just get comfortable with blocks. If you need more powerful block handlers than ASI, AFNetworking has some nice block-based APIs.