0

I was trying to understand memory management concept, and start digging from Apple docs and many articles regarding Memory management in Objective-C. When I start searching from Apple docs I was send back to object copying and messaging concept.

While reading about copying object I hit one question and I was trying to find the solution but fail to get satisfactory solution. It will be honor if someone will help me out. Question is:

 array1 = {obj1,obj2,obj3}
 array2 = {obj4,obj5,obj6}
 array2 = array1 -- Shallow Copy

What happened to the memory which was associated with array2? How to release if there is a leak? What is better practice to perform such shallow copy in ARC and NonARC environment?

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Saheb Singh
  • 555
  • 4
  • 18
  • if you perform this operation then in Objective-C compiler will simply save memory pointer of array1 in variable to access array1 objects... because objective-C compiler never allocate memory to same type of object which have same values... instead of this it simply take a reference of this... so it will take reference of this array – Divyanshu Sharma Apr 15 '16 at 11:08
  • 1
    `array2` now points to the same memory as `array1`. Under ARC, the reference count to the old `array2` object will be decremented. If there are no more strong references to the old `array2` it will be `dealloc`ed and the memory "released". Once the old `array2` is `dealloc`ed, the reference counts for `obj4`, `obj5` and `obj6` will be decremented. For each of `obj4`, `obj5` and `obj6`, if there are no more strong references to that object it will be `dealloc`ed and the memory "released". If you are worried about a leak then you can directly set any of `obj4`, `obj5` and `obj6` to `nil`. – Robotic Cat Apr 15 '16 at 11:13
  • Possible duplicate of [Deep Copy and Shallow Copy](http://stackoverflow.com/questions/9912794/deep-copy-and-shallow-copy) – Robotic Cat Apr 15 '16 at 11:15

1 Answers1

0

When you assign array2 = array1 you are actually assigning an array reference, you are not copying anything, shallow or otherwise.

The array that was referenced array2 will be released if there is no other strong reference to this array. As a result of the array being released, the objects in the array (obj4, obj5 & obj6) will be released if there is no other variable holding a strong reference to any of them

So, initially you have

array1 = {obj1,obj2,obj3}
array2 = {obj4,obj5,obj6}

After the assignment you have

array1      array2
  \\         //
 {obj1,obj2,obj3}

and objects 4-6 have been released along with the array that held them

Paulw11
  • 108,386
  • 14
  • 159
  • 186