0

I understand about how ARC decrease the reference count every time the strong reference variable is set to nil, or is out of scope. But in this scenario I confused about why ARC doesn't deallocate the object.

Please take a look at this simple code:

class Person {
    var name: String

    init(name: String) {
        self.name = name
    }

    deinit {
        print("deinit person named \(name)")
    }
}

class Main {
    func run() {
        var personArray = [Person(name: "John"), Person(name: "Doe")]

        // This will not deallocate the Person object
        personArray.remove(at: 1)
        personArray.remove(at: 0)

        // This will deallocate the Person Object
        // personArray.removeAll()

        print("\nEnd of run method\n")
    }
}

let main = Main()
main.run()

As you can see here, when I use removeAll() the object is deallocated instantly. You can see the log below:

remove all deallocate object instantly

But when I use remove(at:) the object doesn't get deallocated. As you can see in this log below:

remove at index doesn't deallocate the object

This is just a simple example, but you can see that the ARC doesn't deallocate the object when using remove(at:). Why is that?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Edward Anthony
  • 3,354
  • 3
  • 25
  • 40
  • It works as you expect on Linux: http://swift.sandbox.bluemix.net/#/repl/597da8416eb8da601d247cad – vacawama Jul 30 '17 at 09:35
  • 4
    Are you running this in a playground by any chance? Don't rely on ARC behaving normally in a playground – compare https://stackoverflow.com/q/24363384/2976878. The code you show works as expected in an actual project. – Hamish Jul 30 '17 at 09:42
  • 1
    @Hamish yes. I run it in playground. Going to compare if I run it in a regular cocoa project. – Edward Anthony Jul 30 '17 at 09:45
  • 1
    It works in a project. This does appear to be Playground weirdness. I have usually found that putting code into a function (instead of defining at top level) in the Playground and calling it causes it to behave as expected with respect to ARC. This question shows that even that isn't reliable. – vacawama Jul 30 '17 at 09:53
  • 1
    Sorry for late reply. Yes, you're right. It only happens in Playground. It might be a bug in playground. Thanks for your help. There is no answer so I can't accept one. – Edward Anthony Jul 30 '17 at 17:49

0 Answers0