Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming Threads in an NSOperationQueue

NSOperationQueue creates many threads, as you'd expect, and desire. But when you pause the app and debug it in Xcode, it's unclear which threads belong to one operation queue and which belong to another.

I've tried:

[NSThread currentThread] setName: @"My amazing operation thread"]

but as threads are reused, this just means that many threads get this name and then never lose it. I've tried setting the thread name in -start and unsetting it in -finish, but the thread names never show up in the Xcode debugging thread list.

What's a good way of naming threads/operations to make them easier to debug in Xcode?

like image 655
Nick Locking Avatar asked Mar 21 '13 23:03

Nick Locking


2 Answers

To name your NSOperationQueue, you can use:

- (void)setName:(NSString *)newName

When debugging, the name of the thread appears un light gray under the thread.

Example: (thread 3 is mine)

enter image description here

From Apple's documentation:

Discussion

Names provide a way for you to identify your operation queues at run time. Tools may also use this name to provide additional context during debugging or analysis of your code.

Xcode is one of the "tools" that uses this information to provide additional context during debugging.

like image 136
Jean Avatar answered Sep 21 '22 11:09

Jean


(This answer is tested only with Xcode 10.1)

To answer the question in the body of the post (not the title), you need to set the name of the OperationQueue's underlying queue. By doing so, that queue name will show in Xcode while debugging (just like the main or global DispatchQueues).

For example:

var queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .background
queue.underlyingQueue = DispatchQueue(
    label: "my-queue-dispatch-queue", qos: .background)

This example will yield the following in Xcode 10.1: Example Xcode 10.1 Debug View

Reference to the underlyingQueue property: https://developer.apple.com/documentation/foundation/operationqueue/1415344-underlyingqueue

Sidenote: From experience, the "queue.qualityOfService = .SOMETHING" is necessary. See: https://bugs.swift.org/browse/SR-9742

like image 33
martian111 Avatar answered Sep 23 '22 11:09

martian111