Last active
June 6, 2021 12:58
-
-
Save ayakix/00a38f402f4bf3efb2c8acaad94b4616 to your computer and use it in GitHub Desktop.
Define custom NSNotification.Name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NSNotification.Name拡張 | |
extension NSNotification.Name { | |
static let sample = Notification.Name(rawValue: "sample") | |
// static let hoge = Notification.Name(rawValue: "hoge") | |
// static let fuga = Notification.Name(rawValue: "fuga") | |
} | |
///////////////////////////////////////////////////////////////////////////////////////////// | |
// 通知発行側コード | |
class DetailViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
@IBAction private func onNotifyButtonClick(_ sender: UIButton) { | |
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "sample"), object: nil, userInfo: nil) | |
NotificationCenter.default.post(name: .sample, object: nil) | |
} | |
} | |
///////////////////////////////////////////////////////////////////////////////////////////// | |
// 通知受信側コード | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// NotificationCenter.default.addObserver(self, selector: #selector(onSampleNotified(_:)), name: NSNotification.Name(rawValue: "sample"), object: nil) | |
NotificationCenter.default.addObserver(self, selector: #selector(onSampleNotified(_:)), name: .sample, object: nil) | |
} | |
deinit { | |
// NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "sample"), object: nil) | |
NotificationCenter.default.removeObserver(self, name: .sample, object: nil) | |
} | |
func onSampleNotified(_ notification: NSNotification) { | |
print("Notification button pushed") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment