Quote:
Originally Posted by Robby
Why are you calling Release before you alloc the object?
Release should only be called after alloc, and once you no longer need the memory.
Rob.
|
It's easy to see how you might be confused by the posted code, since nearly all memory-management articles describe an "alloc then release" strategy, e.g. if you alloc/init it, you should later release it. I can't think of a single Obj-C/Cocoa memory management discussion that I've seen that doesn't take this same approach.
But in practice, the "release the old thing, then alloc the new thing" strategy is quite common. The basic thinking here is that the first time through the code, the "old thing" is nil, so releasing it does absolutely nothing, then the alloc/init (or the 'malloc', in plain C) makes the initial "new thing" assignment. Subsequent trips through the code will release the current member, then assign a new one.
One caveat of this "release then alloc" approach is that there really needs to be another release somewhere in the code to release the member when it's no longer needed, or the memory may be held onto longer than necessary and might possibly never be released. A problem arises when this alternate release doesn't put things into the proper state for the next trip through the "release then alloc" code. Specifically, if the member is released but is allowed to remain pointing at the released object, the app will crash the next time through the "release then alloc" code. This is because the member is again released, but it's not actually pointing to a valid object. Setting the member to nil after the alternate release properly fixes the member so the release then alloc code works properly without crashing.