Difference between revisions of "Swift:Notification Observer Using NSNotificationCenter"
From Hawk Wiki
(Created page with "Listen notification in swift <pre class="brush:swift"> func tweetSent(notification: NSNotification) { let newTweet:Dictionary<String, Tweet> = notification.userInfo as Dic...") |
(→Listen Notification in Swift) |
||
(5 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | Listen | + | ==Listen Notification in Swift== |
<pre class="brush:swift"> | <pre class="brush:swift"> | ||
func tweetSent(notification: NSNotification) { | func tweetSent(notification: NSNotification) { | ||
let newTweet:Dictionary<String, Tweet> = notification.userInfo as Dictionary<String, Tweet> | let newTweet:Dictionary<String, Tweet> = notification.userInfo as Dictionary<String, Tweet> | ||
} | } | ||
− | NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetSent:", name: "newTweetNotification", object: nil) | + | //The colon in "tweetSent:" is not a typo. It indicates the function will take a parameter |
+ | NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetSent:", name: "newTweetNotification", object: nil) | ||
</pre> | </pre> | ||
− | Send/Post | + | |
+ | ==Send/Post Notification in Swift== | ||
<pre class="brush:swift"> | <pre class="brush:swift"> | ||
var userInfo: Dictionary<String, Tweet> = ["tweet": newTweet] | var userInfo: Dictionary<String, Tweet> = ["tweet": newTweet] | ||
NSNotificationCenter.defaultCenter().postNotificationName("newTweetNotification", object: nil, userInfo: userInfo) | NSNotificationCenter.defaultCenter().postNotificationName("newTweetNotification", object: nil, userInfo: userInfo) | ||
</pre> | </pre> | ||
− | Remove | + | ==Remove Notification Observer== |
<pre class="brush:swift"> | <pre class="brush:swift"> | ||
deinit { | deinit { |
Latest revision as of 06:50, 23 March 2015
Listen Notification in Swift
func tweetSent(notification: NSNotification) { let newTweet:Dictionary<String, Tweet> = notification.userInfo as Dictionary<String, Tweet> } //The colon in "tweetSent:" is not a typo. It indicates the function will take a parameter NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetSent:", name: "newTweetNotification", object: nil)
Send/Post Notification in Swift
var userInfo: Dictionary<String, Tweet> = ["tweet": newTweet] NSNotificationCenter.defaultCenter().postNotificationName("newTweetNotification", object: nil, userInfo: userInfo)
Remove Notification Observer
deinit { NSNotificationCenter.defaultCenter().removeObserver(self) }