是否有任何方式来模拟[NSString stringWithFormat:@“%p”,myVar],从Objective-C,在新的Swift语言?
例如:
let str = "A String"
println(" str value \(str) has address: ?")
是否有任何方式来模拟[NSString stringWithFormat:@“%p”,myVar],从Objective-C,在新的Swift语言?
例如:
let str = "A String"
println(" str value \(str) has address: ?")
当前回答
我对Swift 3的解决方案
extension MyClass: CustomStringConvertible {
var description: String {
return "<\(type(of: self)): 0x\(String(unsafeBitCast(self, to: Int.self), radix: 16, uppercase: false))>"
}
}
这段代码创建的描述类似于默认描述 < MyClass: 0 x610000223340 >
其他回答
其他答案都很好,尽管我正在寻找一种方法来获取整数形式的指针地址:
let ptr = unsafeAddressOf(obj)
let nullPtr = UnsafePointer<Void>(bitPattern: 0)
/// This gets the address of pointer
let address = nullPtr.distanceTo(ptr) // This is Int
只是跟进一下。
斯威夫特5
extension String {
static func pointer(_ object: AnyObject?) -> String {
guard let object = object else { return "nil" }
let opaque: UnsafeMutableRawPointer = Unmanaged.passUnretained(object).toOpaque()
return String(describing: opaque)
}
}
用法:
print("FileManager.default: \(String.pointer(FileManager.default))")
// FileManager.default: 0x00007fff5c287698
print("nil: \(String.pointer(nil))")
// nil: nil
如果你只是想在调试器中看到这个,而不做任何其他事情,实际上没有必要获得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)")
}
这当然不是最快或最安全的方法。但这对我很管用。这将允许任何nsobject子类采用此属性。
public extension NSObject {
public var memoryAddress : String? {
let str = "\(self.self)".components(separatedBy: ": ")
guard str.count > 1 else { return nil }
return str[1].replacingOccurrences(of: ">", with: "")
}
}
//usage
let foo : String! = "hello"
Swift.print(foo.memoryAddress) // prints 0x100f12980