asedra_le
asedra_le

Reputation: 3067

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?

Upvotes: 6

Views: 3861

Answers (4)

Fattie
Fattie

Reputation: 12631

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.

Upvotes: 13

Vikas Jindal
Vikas Jindal

Reputation: 21

Setting an object nil will create a memory leak(if you are taking ownership by alloc,retain or copy) because we are not having a pointer to that particular memory location.

so if you want to dealloc an object you have to take out all ownership of an object before making it nil by calling release method.

[obj release];
obj=nil;

Upvotes: 2

Moshe Gottlieb
Moshe Gottlieb

Reputation: 4003

iOS does not support garbage collection, which means that doing obj = nil would result in a memory leak. If you want automatic control over deallocation, you should do something like: obj = [[[NSObject alloc] init] autorelease] (you must NOT release it if you do that). Autorelease would cause the object to be automatically released when the current NSRunloop event ends. The NSRunloop automatically drains it's NSAutoReleasePool for each event iteration, which is usually very helpful.

Upvotes: 5

Related Questions