0

I have a question for you guys. I was wondering I generate another thread and set NSNotificationCenter to observe a event in the main thread?, what will be the best of doing this?

I'll really appreciate your help

Till
  • 27,559
  • 13
  • 88
  • 122
Renata
  • 205
  • 2
  • 9
  • check this out. http://stackoverflow.com/questions/1973106/nsoperation-and-nsnotificationcenter-on-the-main-thread – madmik3 Aug 22 '13 at 02:45
  • in this case they trying to take the notification to the main thread to update UI. In my case I need to observer something in the main thread from different thread. – Renata Aug 22 '13 at 02:52

2 Answers2

2

Notifications are delivered synchronously by the poster. There are no queues involved. When you call postNotification:, it will run all the observer code right then, sequentially for all observers, on the current thread, before returning.

If the observer wants to handle the observation on a different queue, then you should use dispatch_async or an NSOperation in the observer method to move the processing to the appropriate queue and then return.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • in my case if use dispatch_async to create the observer can I observe and event on the main thread? – Renata Aug 22 '13 at 03:00
  • Yes. Your notification callback will be called on whatever thread posts the notification. You can then use `dispatch_async` to move your processing over to whatever queue you would like. – Rob Napier Aug 22 '13 at 03:36
0

You can handle notifications on a specific thread by using - (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block.

As the documentation states, regarding the queue parameter:

The operation queue to which block should be added. If you pass nil, the block is run synchronously on the posting thread.

jrturton
  • 118,105
  • 32
  • 252
  • 268