This question already has an answer here:
- NSNotificationCenter addObserver in Swift 11 answers
I'm learning Swift 3 and I'm trying to using NSNotificationCenter
. Here is my code:
func savePost(){
let postData = NSKeyedArchiver.archivedData(withRootObject: _loadedpost)
UserDefaults.standard().object(forKey: KEY_POST)
}
func loadPost(){
if let postData = UserDefaults.standard().object(forKey: KEY_POST) as? NSData{
if let postArray = NSKeyedUnarchiver.unarchiveObject(with: postData as Data) as? [Post]{
_loadedpost = postArray
}
}
//codeerror
NotificationCenter.default().post(NSNotification(name: "loadedPost" as NSNotification.Name, object: nil) as Notification)
}
and this is the observer:
override func viewDidLoad() {
super.viewDidLoad()
//codeerorr
NotificationCenter.default().addObserver(self, selector: Selector(("onPostLoaded")), name: "loadedPost", object: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
It always gives me the error "signal SIGBRT". When I try to change the name in the observer, it's not an error, but obviously it didn't show anything. How do I fix this?
Swift 3 & 4
Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with
struct
"wrapper types", as is the case with NotificationCenter. Notifications are now identified by astruct Notfication.Name
rather than byString
. For more details see the now legacy Migrating to Swift 3 guideSwift 2.2 usage:
Swift 3 & 4 usage:
All of the system notification types are now defined as static constants on
Notification.Name
; i.e..UIApplicationDidFinishLaunching
,.UITextFieldTextDidChange
, etc.You can extend
Notification.Name
with your own custom notifications in order to stay consistent with the system notifications:Swift 4.2 usage:
Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend
UIApplication
with your own custom notifications instead of Notification.Name :Notifications appear to have changed again (October 2016).
// Register to receive notification
// Post notification
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
I think it has changed again.
For posting this works in Xcode 8.2.