Swift 的内存管理 [英] Swift's memory management

查看:57
本文介绍了Swift 的内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Swift 的内存管理有点困惑.有人可以向我解释为什么 Kid1 总是停留在相同的内存地址吗?即使我执行 Kid1=kid2 或初始化一个新对象?

I'm a little confused regarding Swift's memory management. Can someone explain to me how come kid1 always stays at the same memory address? Even when I do kid1=kid2 or initialize a new object?

推荐答案

你的代码打印了 kid1 变量的内存位置,如果您为变量分配一个新值,这不会改变.

Your code prints the memory location of the kid1 variable, and that does not change if you assign a new value to the variable.

如果 Kid 是一个引用类型(类),那么你可以使用ObjectIdentifier 获取类实例的唯一标识符变量引用:

If Kid is a reference type (class) then you can use ObjectIdentifier to get a unique identifier for the class instance that the variable references:

var kid1 = Kid(name: "A")
var kid2 = Kid(name: "B")

print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06220)
print(ObjectIdentifier(kid2)) // ObjectIdentifier(0x0000000100b06250)

kid1 = kid2
print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06250)

对象标识符恰好是指向的地址实例,但这是一个未记录的实现细节.如果您需要将对象引用转换为真正的指针然后你可以做(​​比较 How to cast self to UnsafeMutablePointer<Void> 快速输入)

The object identifier happens to be the address of the pointed-to instance, but that is an undocumented implementation detail. If you need to convert an object reference to a real pointer then you can do (compare How to cast self to UnsafeMutablePointer<Void> type in swift)

print(Unmanaged.passUnretained(kid1).toOpaque())

这篇关于Swift 的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆