In objective c, suppose I have an object Obj stored in a NSMutableArray, and the array’s pointer to it is the only strong pointer to Obj in the entire program. Now suppose I call a method on Obj and I run this method in another thread. In this method, if Obj sets the pointer for itself equal to nil will it essentially delete itself? (Because there will be no more strong pointers left) I suspect the answer is no, but why? If this does work, is it bad coding practice (I assume its not good coding, but is it actually bad?)
In objective c, suppose I have an object Obj stored in a NSMutableArray, and
Share
It is highly unlikely that an object would be in a position to cause its own release/deallocation if your code is designed properly. So yes, the situation you describe is indicative of bad coding practice, and can in fact cause the program to crash. Here is an example:
and then this code is in another class:
The second call to NSLog in
removeSelfwill cause an EXC_BAD_ACCESS due to the fact thatarrayhas been deallocated at that point and can’t have methods called on it.There are at least a couple mistakes here. The one that ultimately causes the crash is the fact that whatever class is creating and using the
myWidgetobject releases it before it is finished using it (to call removeSelf). Without this mistake, the code would run fine. However, MyWidget shouldn’t have an instance variable that creates a strong reference to itself in the first place, as this creates a retain cycle. If someone tried to releasemyWidgetwithout first callingremoveSelf, nothing would be deallocated and you’d probably have a memory leak.