I have Object:
MyClass *obj= [[MyClass alloc] init];
What\'s the difference between:
[obj release]; // Only obj own this ob
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,
You must release it, [x release] before setting it to nil x=nil
IF you are using a property, "don't forget the self. thingy"
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.
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.
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.
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;
Is It Necessary to Set Pointers to nil in Objective-C After release?
Release, Dealloc, and the Self reference
Setting an object nil versus release+realloc
Read the above. They answer your Q comprehensively