Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

iphone - What's the difference between setting an object to nil vs. sending it a release message in dealloc

I have Object:

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

What's the difference between:

[obj release]; // Only obj own this object.

and:

obj = nil;

Does iOS deallocs obj when i set obj = nil?

I have a pointer, sometime i set it point to an object, sometime do not. So, when i want release a pointer i must check is it nil?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This answer from the previous decade,

is now only of historic interest.

Today, you must use ARC.

Cheers


The very short answer is DO NOT just set it to nil. You must release it. Setting it to nil has no connection to releasing it. You must release it.

However it's worth remembering that if it is a property, then

self.obj = nil;

will in a fact release it for you. Of course, you must not forget the "self." part !!!!

Indeed,

self.obj = anyNewValue;

will indeed release the old memory for you, clean everything up magically and set it up with the new value. So, self.obj = nil is just a special case of that, it releases and cleanses everything and then just leaves it at nil.

So if anyone reading this is new and completely confused by memory,

  1. You must release it, [x release] before setting it to nil x=nil

  2. IF you are using a property, "don't forget the self. thingy"

  3. IF you are using a property, you can just say self.x=nil or indeed self.x=somethingNew and it will take care of releasing and all that other complicated annoying stuff.

  4. Eventually you will have to learn all the complicated stuff about release, autorelease, blah blah blah. But life is short, forget about it for now :-/

Hope it helps someone.

Again note, this post is now totally wrong. Use ARC.

Historic interest only.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...