0

I try to allocate and release a mutable array in Xcode

NSMutableArray *inventory = [[NSMutableArray alloc] init];

[inventory addObject:@"one"];

[inventory release];

Does anyone help me to explain why after "inventory" was released, it still store 1 objects?

Community
  • 1
  • 1
Nguyen Tho
  • 89
  • 7

1 Answers1

1

Assuming you are working without Automatic Reference Counting (ARC):

When you release an object, that marks the memory that the object was previously occupying as free. However, it does not necessarily immediately destroy what was in that memory.

If you try to (improperly) access what was at your array's memory address, you may very well find the array members still there. But be warned, this is not safe, and the array and its members can (and will) be overwritten at any time.

You should use ARC for any production code to avoid the dangers of memory mismanagement. It works very well.

justinpawela
  • 1,968
  • 1
  • 14
  • 18
  • No problem! If you really want to understand the details of how Apple implements ARC, I **highly** recommend [this article](https://mikeash.com/pyblog/friday-qa-2011-09-30-automatic-reference-counting.html). – justinpawela Jul 11 '15 at 03:36
  • There are 2 sides when we allocate an object : first, creare a pointer in stack memory to point to a memory address. Second, claiming ownership of that memory address. After "release", we relinquish ownership (mark memory that we do not use that memory address anymore) but the pointer still point to that address memory. that's why "inventory" still store 1 object – Nguyen Tho Jul 11 '15 at 03:54