简体   繁体   中英

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.

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.

[DMLOG - prepForInput] <GridBase: 0x7fb71860a190>

How can I get both the instance ID and the function being called within Swift? I've tried the following to get the ID in Swift but it only provides the class name and no instance ID value? Any suggestions would be appreciated.

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

To get current function name use #function literal.

As for instance ID, looks like you have two options:

  1. Inherit from NSObject (UIKit classes inherit it anyways) so that class instances would have instance IDs:

     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:

     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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM