swiftmemory-managementnszombiedangling-pointer

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:

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?


Solution

  • 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.