简体   繁体   English

如何在Swift中获取类实例ID?

[英]How do I get the class instance ID in Swift?

In Objective-C, I would use the following code to identify an instance of a class and the function being called in the console. 在Objective-C中,我将使用以下代码来标识类的实例和在控制台中调用的函数。

NSLog(@"[DMLOG - %@] %@", NSStringFromSelector(_cmd), self);

This would return something like the console out below, where I would get an instance ID to track different instances of an object. 这将返回类似于以下控制台的内容,在该控制台中,我将获得一个实例ID来跟踪对象的不同实例。

[DMLOG - prepForInput] <GridBase: 0x7fb71860a190>

How can I get both the instance ID and the function being called within Swift? 如何获取实例ID和在Swift中被调用的函数? I've tried the following to get the ID in Swift but it only provides the class name and no instance ID value? 我已经尝试了以下方法来在Swift中获取ID,但它仅提供类名而没有实例ID值? Any suggestions would be appreciated. 任何建议,将不胜感激。

print("[DBG] Init: \(self)")

To get current function name use #function literal. 要获取当前函数名称,请使用#function文字。

As for instance ID, looks like you have two options: 至于实例ID,看起来您有两个选择:

  1. Inherit from NSObject (UIKit classes inherit it anyways) so that class instances would have instance IDs: NSObject继承(UIKit类始终继承它),以便类实例具有实例ID:

     class MyClass: NSObject { override init() { super.init() print("[DBG: \\(#function)]: \\(self)") } } 
  2. If your class does not inherit from NSObject you can still identify your instances by memory address: 如果您的类没有从NSObject继承,您仍然可以通过内存地址来标识实例:

     class Jumbo { init() { print("[DBG: \\(#function)]: \\(Unmanaged.passUnretained(self).toOpaque())") } } 

I just ran a quick test using the following: 我只是使用以下命令进行了快速测试:

print("\(self) \(#function) - Count \(count)")

I got the following result: 我得到以下结果:

<XXXXXXX.FeedViewController: 0x7fcebdf05d40> viewWillAppear - Count 3

I would give that a try and see if it helps. 我会尝试一下,看看是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Swift中访问类的实例 - How do I access an instance of a class in Swift 如何快速检查符合协议的实例的类? - How do I check the class of an instance that conforms to a protocol in swift? 如何为每个类实例获取唯一的标识符字符串? - How do I get a unique identifier string for each class instance? 如何在 Swift 的 UIView/Utility 类中获取导航栏 - How do I get Navigation Bar in UIView/Utility class in Swift 如何在swift中使用AS来获取类类型 - How do I use AS with a switch in swift to get the class type 如何在swift文件中获取类的引用,并在另一个swift文件中进行编码? -xcode /迅速 - How do i get a reference of a class in a swift file and code that in another swift file? - xcode / swift 斯威夫特:如果我在变量中有实例的名称,如何创建类的实例? - Swift: How to create instance of a class, if I have the name of the instance in a variable? 如何在Swift 4中获取实例类和调用类函数? - How to get class of instance and call class function in Swift 4? 如何使用 obj-c class 实例删除 swift 非可选解包? - How do I remove swift non-optional unwrapping with obj-c class instance? 如何在Swift中从Mirror对象的子对象创建类的实例 - How do I create an instance of a class from the child of a Mirror object in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM