Sunday, March 31, 2019

memory management - How can I demonstrate a zombie object in Swift?



I've read How to demonstrate memory leak and zombie objects in Xcode Instruments? but that's for objective-c. The steps don't apply.



From reading here I've understood zombies are objects which are:





  • deallocated

  • but something pointer is still trying to point to them and send messages to them.



not exactly sure how that's different from accessing a deallocated object.



I mean in Swift you can do:



var person : Person? = Person(name: "John")

person = nil
print(person!.name)


Is person deallocated? Yes!



Are we trying to point to it? Yes!



So can someone share the most common mistake which leads to creating a dangling pointer?


Answer




This is not a dangling pointer or a zombie. When you use ! you're saying "if this is nil, then crash." You should not think of person as a pointer in Swift. It's a value. That value may be .some(T) or it may be .none (also called nil). Neither of those is dangling. They're just two different explicit values. Swift's nil is nothing like null pointers in other languages. It only crashes like null pointers when you explicitly ask it to.



To create zombies, you'll need to be using something like Unmanaged. This is extremely uncommon in Swift.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...