1

The Xcode debugger shows threads with names like "Thread N" if they haven't specifically been renamed by the app. How can I obtain, within my app, the name of the current thread as Xcode would display it?

Alternatively, how does Xcode determine thread indices? Even if the app renames a thread to "Some Name", Xcode still assigns it an index, as a thread will appear in the debugger as "Some Name (N)".

Alternatively, how does Xcode enumerate the active threads?

Kevin Hopps
  • 707
  • 3
  • 10

1 Answers1

1

This is a private/opaque property of the underlying NSThread that you can retrieve with value(forKeyPath:):

if let number = Thread.current.value(forKeyPath: "private.seqNum") as? Int {
    ...
}

You could also get the description of the NSThread:

let string = Thread.current.description    // <NSThread: 0x600003971340>{number = 7, name = foo}

And then parse it out of that:

let regEx = try! NSRegularExpression(pattern: #"number = (\d+),"#, options: [])
if
    let match = regEx.firstMatch(in: Thread.current.description, options: [], range: NSRange(string.startIndex..., in: string)),
    let range = Range(match.range(at: 1), in: string)
{
    let threadNumberString = String(string[range])
    print(threadNumberString)
}

But, I would suggest avoiding both of these techniques in production code. They are fragile, depending upon private implementation details. Also, App Store guidelines prohibit the use of private interfaces.

So, if this is just a matter of intellectual curiosity, that’s fine. But I would advise against doing this in an actual app. Besides, in the world of GCD, we generally work with queues, and abstract our code away from these sorts of thread details.

See:

Rob
  • 415,655
  • 72
  • 787
  • 1,044