0

Let's say I have a class Animal

class Animal: NSObject {
  var name: String = ""
  var weight: Double = 0
}

In my view controller #1, I have an array of these objects:

class ViewController1: UIViewController {
  var animals: [Animal] = [ .... ]

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let v = segue.destination as? ViewController2 {
      v.mammals = self.animals.filter(...) // Are my objects duplicated?
    }
  }
}

class ViewController2: UIViewController {
  var mammals: [Animal] = [ .... ]
}

Are my Animal objects duplicated when I filter them from VC1 and pass a subset of them to VC2? When I go back from VC2 to VC1 (i.e. popping the navigation stack), are the objects in mammals deallocated, freeing memory?

EDIT: Will this create any retain cycle of any kind??

7ball
  • 2,183
  • 4
  • 26
  • 61

2 Answers2

1

In Swift, classes are reference types so they are not copied. Array is a struct which is a value type so they are copied.

So while the array is copied, the Animal objects in it are not. Both arrays will have references to a single set of Animal objects. If you change one of the Animal objects, you will see the change regardless of which array you access it from.

When ViewController2 is dismissed, and as long as there is no other strong references to it, it will be deallocated as will all of its properties. The mammals array will be freed. Whether the Animal objects in it are freed or not depends on whether those objects have any other strong references to them or not.

There is no reference cycle being caused by filtering your array of Animal objects.

Further reading from the Swift book:

Structures and Enumerations Are Value Types

Classes Are Reference Types

Automatic Reference Counting

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

You're totally safe to do a thing like this. What is going to be duplicated as you said is the array. The array itself is a value type but it stores class types or references to your objects. So values (addresses) will be copied but still, those addresses point to the same objects you have in animals array. After mammals is removed from memory only its values are removed, and values are addresses to your objects but NOT OBJECTS.

Ivan
  • 264
  • 3
  • 14