Post

Replies

Boosts

Views

Activity

Memory leaks caused by closures
Hi there, this is my first time posting here. I've heard that some of the apple developers are usually active on these forums, so I've decided to shoot my shot, because this question was driving me crazy for a few days now and nobody could yet give me a clear view on what's actually happening. Here is the first snippet of the code class Animal { var name = "Fischer" var command: () -> Void = { } deinit { print(#function, #line) } } do { var pet: Animal? = Animal() pet?.command = { print(pet?.name ?? "Bobby") } } This code causes a memory leak, because Reference 'pet' is created. Independent copy of the reference 'pet' is created inside the closure. now there are two references to the same object, which are 'pet' outside the closure and 'pet' inside the closure. As we exit the 'do' scope, the 'pet' reference is deleted, but ARC does not deallocate the object due to the strong reference 'pet', that is still referencing to the same object. And all of that causes a memory leak. Now here is the code, that is pretty similar, except for the fact, that we assign a nil to the 'pet' reference class Animal { var name = "Fischer" var command: () -> Void = { } deinit { print(#function, #line) } } do { var pet: Animal? = Animal() pet?.command = { print(pet?.name ?? "Bobby") } pet = nil } And boom! deinit is called, meaning that the object was deallocated, but how? Why was the object deallocated? If we are deleting the exact same reference, that was deleted by the end of the 'do' scope in the first snippet? Am I misunderstanding something? I really hope this post will find the right people, since I could not even find appropriate tags for that.
4
0
324
Oct ’24