开发者

Any way to check if an instance is still in memory?

Example: I have a view controller and get rid of it. But there's still an variable holding it's memory address. Accessing that results in EXEC_BAD_ACCESS. Of course. But: Is there any way to check if that variable is still 开发者_StackOverflowvalid? i.e. if it's still pointing to something that exists in memory?


You need to read this again:

Cocoa Memory Management Guidelines

In short, if you want something to stick around you must retain it.

If you want something to go away and you have previously retained it, you must release or autorelease it.

You must never call dealloc directly (except [super dealloc]; at the end of every one of your dealloc methods).

You must never release or autorelease an object that you did not retain.

Note that some methods do return retained objects that you must release. If you alloc an instance of a class, that implies a retain. If you copy and instance, the copy is retained.

If you are ever tempted to use the retainCount method, don't. It isn't useful. Only consider retain counts as a delta; if you add, you must subtract, but the absolute value is an implementation detail that should be ignored.

(In other words, even if there were ways to check for an object's validity definitively -- there aren't -- it would be the wrong answer.)

Oh, and use the Build and Analyze feature in Xcode. It does a very good -- but not quite perfect -- job of identifying memory management problems, amongst other things.


That's what the entire memory management model is set up for - if you call retain at the right times, and release and autorelease at the right times, that can't happen. You can use NSZombie to help you debug.


Use "NSZombieEnabled" break point.

For this reason only all strongly recommend us to use accessors. If your object is released anywhere, it will get assigned to nil, and there will be no harm if you call any API or method on Nil object. So please make a habit of using Accessors.

you just add this NSZombieEnabled Flag as an argument to your application in build settings. and enable it. Now you run your application in debug mode. If any such crash is about to occur, this breakpoint will show you which object is freed and where it is crashing.

Cheers, Manjunath


If by variable, you mean whether the pointer to your object still references valid memory then:

MyClass *myVariable = [[MyClass alloc] init];

//Tons of stuff happens...

if (myVariable != nil) //Do more stuff

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜