开发者

How can I tell if a referenced object has been deallocated in objective-c?

After upgrading to iPhone OS 4.0 the application started to crash after switching between applications. The application crashes in the same place when the application receives a memory warning.

It seems like some objects are automatically deallocated when a memo开发者_开发问答ry warning is received and then when we try to use the deallocated objects the application crashes.

Is it possible to test if an object has been deallocated, so that we can reallocate them?


You can't test whether a specific object has been deallocated because after deallocation, the object no longer exist. The only thing you can do is test whether a reference to the suspected object from another object is still non-nil.

Your problem here isn't deallocation per se but rather mismanaged retention. You have an object that has been marked as no longer being in use and the system is killing it as the system should. The only reason that you see it during low memory is that the system stops and drains all the release pool instantly instead of waiting for the normal cycle.

You need to make sure you have properly retained all the objects you need so they won't be improperly released. A retained object is not deallocated even in low-memory situations.

Edit

I would add that the most common cause of low-memory crashes is assuming that a view or a resource in a view is always present even when the view is not displayed. The system will purge undisplayed views and their resources (like images) in low-memory. Check the didReceiveMemoryWarning of the view controllers.


You can add

-(void)dealloc { ... }

And leave it empty if it's the right to do, and add breakpoint in it.

This answer correct to ARC and NON-ARC


  1. Implement the method dealloc inside a UIViewController to see the moment it is being released from memory

    - (void) dealloc

  2. Print the reference of any object you want to test.

    NSLog("Get pointer: %@", self); // ViewController

Then set a break point at a place where you want to test if the object is still existing. If you ran into the breakpoint, check the objects pointer in the debugger with

`po [pointer_printed_before]

How can I tell if a referenced object has been deallocated in objective-c?

Here you can see, the pointer is not available anymore, there is no object anymore after the dealloc method printed a log.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜