In my Objective-C class I alloc and release an object multiple times. I also have to release it in dealloc. But if it has been already released previously I might get crash. Is it legal to set object to nil after releasing it? In what cases this would be wrong and cause even more problems?
In my Objective-C class I alloc and release an object multiple times. I also
Share
Yes yes yes. You almost always should set it to nil after releasing, for exactly the reason you mentioned. You only don’t need to if you’ll never access it again (like in dealloc) or if you set it to something else immediately afterward.
This is extra-useful because Obj-C has the feature of “nil messaging”: if you send a message to nil, it doesn’t crash, it just doesn’t do anything. So:
Another example based on your comment:
Read the Memory Management guidelines!