开发者

Difference between release and release then set to nil

开发者 https://www.devze.com 2022-12-29 17:34 出处:网络
What is the difference between two snippets? [myObj release]; 开发者_运维知识库 and [myObj release];

What is the difference between two snippets?

[myObj release];
开发者_运维知识库

and

[myObj release];
myObj = nil;


If you just release an object, then it will become freed object.

And if you try to perform any sort of operation on freed object then your app crashes. To avoid such accidents, it is always preferred "assign your object to nil after releasing it". Because we all know any operations performed on nil will not be executed :)


It is a great problem in memory management. If you are using a property then you can use nil without using release. Because the setter method of a property works as follows:

- (void)setObjTypes:(NSArray *)ObjTypes {
    [ObjTypes retain];
    [_ObjTypes release];
    _ObjTypes = ObjTypes;
}

The setters increase the reference count of the passed-in variable, decrease the reference count of the old instance variable, and then set the instance variable to the passed-in variable. This way, the object correctly has a reference count for the object stored in the instance variable as long as it is set.

The setter method automatically applies release method and then set the value of instance variable with nil. But if you are not using property then it is a great experience that before setting nil we have to set release first.If we set a pointer to nil means it is not pointing to any memory address so if we try to access that memory using above pointer then it will crashes. And if we call release method on a instance variable then it frees the memory.


Not much. The second form just prevents you from accidentally trying to reuse the memory as if it was still an object. (As if it was the same object, to be precise. The memory address is likely to be reused for a new object shortly thereafter.)


You have to be careful with the first one, because after you release, the pointer still points to some garbaged memory and can contains some other object. So, in the first one, if you try [myObj release] then [myObj doSomething], the application can crash

My advice is that you should always set it to nil after you release.


when calling release on object the reference-count is decremented. when calling retain the reference-count is incremented.

So as the guys mentioned the pointer will still point to the same place.

0

精彩评论

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