Difference between release and release then set to nil

前端 未结 5 1791
粉色の甜心
粉色の甜心 2020-12-29 17:14

What is the difference between two snippets?

[myObj release];

and

[myObj release];
myObj = nil;
5条回答
  •  情话喂你
    2020-12-29 17:51

    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.

提交回复
热议问题