如何在Swift中演示僵尸对象

如何在Swift中演示僵尸对象

本文介绍了如何在Swift中演示僵尸对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读如何演示是Xcode Instruments中的内存泄漏和僵尸对象?,但这是针对Objective-C的.这些步骤不适用.

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.

我的意思是在Swift中您可以做到:

I mean in Swift you can do:

var person : Person? = Person(name: "John")
person = nil
print(person!.name)

人被释放了吗?是的!

我们是否要指出这一点?是的!

Are we trying to point to it? Yes!

那么有人可以分享导致创建悬空指针的最常见错误吗?

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

推荐答案

这不是悬挂指针或僵尸.当您使用!时,您说的是如果为零,则崩溃."您不应将person视为Swift中的指针.这是一个价值.该值可以是.some(T),也可以是.none(也称为nil).这些都没有晃来晃去.它们只是两个不同的显式值. Swift的nil与其他语言中的空指针完全不同.当您明确要求它时,它只会像空指针一样崩溃.

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.

要创建僵尸,您需要使用Unmanaged之类的东西.这在Swift中非常罕见.

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

这篇关于如何在Swift中演示僵尸对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:21