您的代码显示了两个变量obj1
和obj2
的地址。
import Foundation
class Test {
static let sharedInstance = Test()
init() {} //Make initializer accessible for testing.
}
var obj1 = Test.sharedInstance
var obj2 = Test.sharedInstance
withUnsafePointer(to: &obj1) {
print(" var obj1 is located at address: \($0)")
}
withUnsafePointer(to: &obj2) {
print(" var obj2 is located at address: \($0)")
}
obj2 = Test() //Create new instance.
withUnsafePointer(to: &obj2) {
print(" var obj2 is still located at address: \($0)")
}
输出:
var obj1 is located at address: 0x00000001003e4398
var obj2 is located at address: 0x00000001003e43a0
var obj2 is still located at address: 0x00000001003e43a0
如果要包含的引用在obj1
和obj2
比较,使用ObjectIdentifier
将是一个简单的方法:
obj2 = Test.sharedInstance
print(" ObjectIdentifier of obj1 is \(ObjectIdentifier(obj1))")
print(" ObjectIdentifier of obj2 is \(ObjectIdentifier(obj2))")
obj2 = Test()
print(" ObjectIdentifier of obj2 is now \(ObjectIdentifier(obj2))")
输出:
ObjectIdentifier of obj1 is ObjectIdentifier(0x0000000100e04a80)
ObjectIdentifier of obj2 is ObjectIdentifier(0x0000000100e04a80)
ObjectIdentifier of obj2 is now ObjectIdentifier(0x0000000100e075f0)
或者,你可以转换到OpaquePointers引用,然后INTS是这样的:
let addrInt1 = Int(bitPattern: Unmanaged.passRetained(obj1).toOpaque())
print("Address of obj1 = \(String(format: "%016lX", addrInt1))")
let addrInt2 = Int(bitPattern: Unmanaged.passRetained(obj2).toOpaque())
print("Address of obj2 = \(String(format: "%016lX", addrInt2))")
输出:
Address of obj1 = 0000000100E04A50
Address of obj2 = 0000000100E049E0
我知道了,非常感谢你! – fzh