Pierre
Pierre

Reputation: 11673

Request traitement crash - Message sent to deallocated instance

I'm executing an asynchronous method on an object and when my request is finish I print the result in a label. My problem is : if I launch my request and then I remove my object, I have a crash on my setText method (because my object is deallocated).

How can I avoid this crash even if my object has been released ?

Is there any test to do ?

Upvotes: 0

Views: 115

Answers (4)

newacct
newacct

Reputation: 122518

The asynchronous request can retain the object until it's done with it.

Upvotes: 0

deleted_user
deleted_user

Reputation: 3805

If your object is deallocated and its currently a subview on a view, then the view itself has been destroyed, you have nowhere to display the label contents. Why this would be depends on the design of your app, but usually the removal of a view is detectable by your code and you should set any references to the view to nil in that case if you know its gone.

If the label hasnt been added to the view yet - then you needed to retain the label, so that you can set the text on it and call addSubview on the containing view.

Also if a user action would be causing the view to be removed - display a spinner and block the user from doing this since a request they invoked is in progress.

Upvotes: 0

David Hoerl
David Hoerl

Reputation: 41672

The solution is to have a NSMutableArray object created in you "init" or in your "viewDidLoad" method. When you want to remove the object, always put it in this array after removing it from its superview. Then in your asynchronous method (which better be running on the main thread to print the result), the last thing it does is [storageArray removeObject:object], to release it.

Upvotes: 0

deanWombourne
deanWombourne

Reputation: 38485

1) Don't remove your object until the request is finished :)

2) Cancel the request (not always possible depending on your object)

Upvotes: 1

Related Questions