Posting NSNotification in the main topic

I found the following code snippet that allows NSNotification to be placed in the main thread from any background thread. I would like to know if this is a safe and acceptable practice, please?

 dispatch_async(dispatch_get_main_queue(),^{ [[NSNotificationCenter defaultCenter] postNotificationName:@"ImageRetrieved" object:nil userInfo:imageDict]; }); 
+51
ios objective-c cocoa nsnotificationcenter
Apr 04 '13 at 14:15
source share
4 answers

Yes you can .

Typically, you want NSNotifications to be sent mainly, especially if they trigger user interface actions, such as rejecting a modal login dialog.

Providing notifications on specific topics

Regular notification centers provide notifications about the stream to which it was sent. Distributed notification centers deliver notifications over the main stream. Sometimes you may need notifications that must be delivered through a specific stream, which you defined instead of the notification center. For example, if an object running in a background thread listens for notifications from the user interface, such as closing a window, you would like to receive notifications in the background thread instead of the main thread. In these cases, you need notifications because they are delivered by default flow and redirect them to the corresponding topic.

+43
Apr 04 '13 at 14:19
source share

Yes

This is - you get into the main stream and publish your notification. It can't be safer than that.

+15
Apr 04 '13 at 14:17
source share

Yes

Syntax

Swift 2

 dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName("updateSpinner", object: nil, userInfo: ["percent":15]) } 
Syntax

Swift 3

 DispatchQueue.main.async { NotificationCenter.default.post(name: "updateSpinner", object: nil, userInfo: ["percent":15]) } 
+11
Nov 11 '15 at 10:28
source share

Somewhere along the line this became possible:

 addObserver(forName:object:queue:using:) 

which is here , but the whole point is the queue object.

The operational queue to which the block should be added. If you pass nil , the block runs synchronously in the posting thread.

So how do you get a queue that matches the main runloop?

let mainQueue = OperationQueue.main

Note: this is when you sign up for notifications, so you do it once, and you're done. Doing this with every call is terribly redundant.

+2
Mar 15 '17 at 4:03 on
source share



All Articles