[英]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,看起来您有两个选择:
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)") } }
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.