Get current dispatch queue?

后端 未结 11 1316
难免孤独
难免孤独 2020-12-23 16:28

I have a method which should support being called from any queue, and should expect to.

It runs some code in a background thread itself, and then uses dispatch

11条回答
  •  没有蜡笔的小新
    2020-12-23 17:04

    As an alternative approach to this NSOBject's method performSelector:withObject:afterDelay: dispatches the call on the current thread's run loop. According to the docs:

    This method sets up a timer to perform the aSelector message on the current thread’s run loop.

    Obviously I'm suggesting using this with a delay of zero, which, according to the docs again:

    Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

    Unfortunately it requires exactly one argument, so some workarounds might be needed if your method takes more or less.

    One other thing I noted is that this method is not available for protocols, but implementations alone. This is due to this method living in an NSObject category, and not in the NSObject interface (see PS below). This can easily be fixed by casting to id.

    PS: Two different NSObjects exist, a protocol and an implementation. Notice NSObject declaration:

    @interface NSObject  { ... }
    

    It might seem odd, but one is being declared (after @interface) and the other one is a previously declared protocol (between < and >). When declaring a protocol that extends NSObject (ie., @protocol Foo ) the protocol inherits the methods from the later, but not the former. Eventually the protocol is implemented by some class that inherits from the NSObject implementation, so all instances inheriting from the NSObject implementation still holds. But I'm getting off topic.

提交回复
热议问题