Having guessed why you might be confused, I would like to add an explanation of what the second code example actually does (and why it is not needed).
NSMutableDictionary *foo = [[NSMutableDictionary alloc] initWithCapacity:0];
I think you are confused by this line, because this line is often called "initialization foo". This is a bit misleading. Currently, 2 different objects are being changed here: a new NSMutableDictionary is being created, and the variable "foo" is assigned its address.
The line actually creates a new NSMutableDictionary object on the heap (application heap). I will name this "Dictionary 1". So that this new Dictionary 1 object on the heap can be found, its memory address is stored in foo. "foo" is a role as an index, so we can find "Dictionary 1".
Although we often say: “foo is a dictionary”, this is because we are lazy - the statement is technically incorrect. That's right: "there is a dictionary on the heap, and foo stores its memory address so that we can find and use it."
When you run the line:
foo = [bar mutableCopy];
you use the address in the “bar” to find another object (I will call it “Dictionary 2”) on the heap and make another object (“Dictionary 3”) on the heap with the same values. If you are counting, now it is 3 objects .
After "Dictionary 3" is done, its memory address is then stored in the variable "foo". This save in "foo" overwrites the existing memory address (the one that points to "Dictionary 1"). This means that we have no other pointers to "Dictionary 1" and, therefore, he can never find it again. That's why we say that Dictionary 1 has leaked.
I hope you see in this situation why Dictionary 1 is never needed (you only ever intended to use foo to access a copy of Dictionary 3).
Matt gallagher
source share