是否有任何方式来模拟[NSString stringWithFormat:@“%p”,myVar],从Objective-C,在新的Swift语言?

例如:

let str = "A String"
println(" str value \(str) has address: ?")

当前回答

如果你只是想在调试器中看到这个,而不做任何其他事情,实际上没有必要获得Int指针。要在内存中获取对象地址的字符串表示形式,只需使用如下方法:

public extension NSObject { // Extension syntax is cleaner for my use. If your needs stem outside NSObject, you may change the extension's target or place the logic in a global function
    public var pointerString: String {
        return String(format: "%p", self)
    }
}

使用示例:

print(self.pointerString, "Doing something...")
// Prints like: 0x7fd190d0f270 Doing something...

此外,请记住,你可以简单地打印一个对象,而不重写它的描述,它将显示它的指针地址与更多的描述性(如果经常是隐晦的)文本。

print(self, "Doing something else...")
// Prints like: <MyModule.MyClass: 0x7fd190d0f270> Doing something else...
// Sometimes like: <_TtCC14__lldb_expr_668MyModule7MyClass: 0x7fd190d0f270> Doing something else...

其他回答

斯威夫特2

这现在是标准库的一部分:unsafeAddressOf。

/// Return an UnsafePointer to the storage used for `object`.  There's
/// not much you can do with this other than use it to identify the
/// object

斯威夫特3

对于Swift 3,使用withUnsafePointer:

var str = "A String"
withUnsafePointer(to: &str) {
    print(" str value \(str) has address: \($0)")
}

就用这个吧:

print(String(format: "%p", object))

其他答案都很好,尽管我正在寻找一种方法来获取整数形式的指针地址:

let ptr = unsafeAddressOf(obj)
let nullPtr = UnsafePointer<Void>(bitPattern: 0)

/// This gets the address of pointer
let address = nullPtr.distanceTo(ptr) // This is Int

只是跟进一下。

引用类型:

获取引用类型的内存地址是有意义的,因为它表示标识。 ===标识运算符用于检查两个对象是否指向同一个引用。 使用ObjectIdentifier获取内存地址

代码:

class C {}

let c1 = C()
let c2 = c1

//Option 1:
print("c1 address: \(Unmanaged.passUnretained(c1).toOpaque())") 

//Option 2:
let o1 = ObjectIdentifier(c1)
let o2 = ObjectIdentifier(c2)

print("o1 -> c1 = \(o1)")
print("o2 -> c2 = \(o2)")

if o1 == o2 {
    print("c1 = c2")
} else {
    print("c1 != c2")
}

//Output:
//c1 address: 0x000060c000005b10
//o1 -> c1 = ObjectIdentifier(0x000060c000005b10)
//o2 -> c2 = ObjectIdentifier(0x000060c000005b10)
//c1 = c2

值类型:

获取值类型的内存地址的需求并不太重要(因为它是一个值),重点将更多地放在值的相等性上。

@Drew提供的答案只能用于类类型。 @nschum提供的答案只能用于结构类型。

但是,如果使用第二种方法获取值类型为element的数组的地址。Swift会复制整个数组,因为在Swift数组是写时复制,Swift不能确保它的行为一旦它把控制权传递给C/ c++(这是通过使用&来获取地址触发)。如果你用第一个方法,它会自动把数组转换成NSArray这当然是我们不想要的。

所以我发现最简单和统一的方法是使用lldb指令帧变量-L yourVariableName。

或者你可以把他们的答案结合起来:

func address(o: UnsafePointer<Void>) {
    let addr = unsafeBitCast(o, Int.self)
    print(NSString(format: "%p", addr))
}

func address<T: AnyObject>(o: T) -> String{
    let addr = unsafeBitCast(o, Int.self)
    return NSString(format: "%p", addr) as String
}