joan
joan

Reputation: 2551

Manual memory management explanation

I got this image from Apple docs: enter image description here

Sorry for this stupid question. Someone can give an explanation of this image?. My interpretation:

  1. We create an instance of an Object of class A.
  2. After [[ClassA alloc]init] the object has a retain count of 1.
  3. After this, we create an instance of ClassB and add him to Class A as an iVar ¿it is correct? Instantiation means a retain count of 1, and the relation of ownership (now A owns B) means an increment of 1 of the retain count. (1+1 = 2) Now B has a retain count of 2. ¿it is correct? Anynone?

Upvotes: 2

Views: 146

Answers (3)

Matteo Gobbi
Matteo Gobbi

Reputation: 17717

So, is really simple, follow this points whose explain the main line:

1- An instance of class A allocs and initializes an object of class X --> X retain count = 1;

2- An instance of class B retain X. It is not important how B obtain X. The important is that want have the ownership of the object to maintains it alive --> X retain count = 2;

3- A release X --> X retain count = 1;

4- B release X --> X retain count = 0; --> X is deallocated

The second part instead is just to explain that copying an object, another object is allocated, and so, the same mechanism on this new object has not effects on the first object.

Upvotes: 1

jrturton
jrturton

Reputation: 119292

You've misunderstood the diagram. Going from left to right:

  • An instance of Class A creates a new object - it has a retain count of one.
  • An instance of Class B retains the new object - it now has a retain count of 2.
  • An instance of class C makes a copy of the new object - this is another new object, with a retain count of one.
  • The instance of Class A releases the new object - it now has a retain count of 1, so is not deallocated.
  • Class C releases its copy - the copied instance is deallocated
  • Class B releases its reference to the new object. The reference count returns to zero and it is deallocated.

Upvotes: 1

erkanyildiz
erkanyildiz

Reputation: 13234

1) We create an instance of an Object of class A. FALSE

ClassA creates an instance of just another class, let's call it ClassZ.

2) After [[ClassA alloc]init] the object has a retain count of 1. FALSE

It is not [[ClassA alloc]init], it is [[ClassZ alloc]init]. Now the instance of ClassZ has retain count of 1.

3) After this, we create an instance of ClassB and add him to Class A as an iVar FALSE

An instance of ClassB just retains the instance of ClassZ created on step 1. And retain count of the instance of ClassZ becomes 2.

4) Instantiation means a retain count of 1, and the relation of ownership (now A owns B) means an increment of 1 of the retain count. (1+1 = 2) Now B has a retain count of 2. FALSE

Here it is not important who created ClassB and what its retain count at the moment. It is just another object claiming ownership on the instance of ClassZ.

Upvotes: 1

Related Questions