2017-02-28 62 views
0

这是我的代码:由单重复创建对象,但该对象的地址是不同的

class Test { 
    static let sharedInstance = Test() 
    private init() {} 
} 

var obj1 = Test.sharedInstance 
var obj2 = Test.sharedInstance 

withUnsafePointer(to: &obj1) { 
    print(" obj1 value \(obj1) has address: \($0)") 
} 

withUnsafePointer(to: &obj2) { 
    print(" obj2 value \(obj2) has address: \($0)") 
} 

登录:

OBJ1值测试地址为:0x0000000112cc5bf8

obj2的值测试地址为:0x0000000112cc5c00

在此先感谢!

回答

2

您的代码显示了两个变量obj1obj2的地址。

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 

如果要包含的引用在obj1obj2比较,使用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 
+0

我知道了,非常感谢你! – fzh