Swift-use Nsnotificationcenter to send notifications and receive notifications

Source: Internet
Author: User
Tags uikit

1, notice (nsnotification) IntroductionThe notification mentioned here does not refer to the notification message sent to the user, but rather to the notification of message delivery within the system. Before we introduce the notification, we need to understand what the observer pattern is.
Observer Mode (Observer): Refers to an object that notifies another object when the state changes. The participant does not need to know what other objects are specifically doing. This is a design that reduces the coupling degree. A common use is for observers to register for monitoring, and then all observers will be notified when the state changes. In MVC, the observer pattern means that the model object and the View object need to be allowed to communicate without having a direct association.
COCOA implements the Observer pattern in two ways: one is Key-value observing (KVO) and the other is notification.
2, registration and response of system notificationsFor example, we want to perform certain actions when the user presses the home key of the device and the program enters the background. One way is to do it in the Applicationdidenterbackground method in Appdelegate.swift. In addition, as the program enters the background will send uiapplicationdidenterbackgroundnotification notification, we can register a listener to listen to this Notice "observer" to deal with.
1234567891011121314151617181920212223242526 import UIKitclass ViewController: UIViewController {        override func viewDidLoad() {        super.viewDidLoad()                let notificationCenter = NSNotificationCenter.defaultCenter()                let operationQueue = NSOperationQueue.mainQueue()                let applicationDidEnterBackgroundObserver =            notificationCenter.addObserverForName(UIApplicationDidEnterBackgroundNotification,                object: nil, queue: operationQueue, usingBlock: {                (notification: NSNotification!) in                    print("程序进入到后台了")        })                //如果不需要的话,记得把相应的通知注册给取消,避免内存浪费或奔溃        //notificationCenter.removeObserver(applicationDidEnterBackgroundObserver)    }        override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()    }}

3, using a custom notification The notification type is actually a string, so we can also use our own defined notifications (as well as passing user-defined data). Below, two observers were created to get the download picture notification, and a 3 second wait was added inside the processing function after receiving the notification.
---viewcontroller.swift---
12345678910111213141516171819 import UIKitclass ViewController: UIViewController {        let observers = [MyObserver(name: "观察器1"),MyObserver(name: "观察器2")]    override func viewDidLoad() {        super.viewDidLoad()                print("发送通知")        NSNotificationCenter.defaultCenter().postNotificationName("DownloadImageNotification",            object: self, userInfo: ["value1":"hangge.com", "value2" : 12345])        print("通知完毕")    }        override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()    }}

---myobserver.swift---
1234567891011121314151617181920212223242526272829303132 import UIKitclass MyObserver: NSObject {         var name:String = ""    init(name:String){        super.init()                self.name = name        NSNotificationCenter.defaultCenter().addObserver(self, selector:"downloadImage:",            name: "DownloadImageNotification", object: nil)    }        func downloadImage(notification: NSNotification) {        let userInfo = notification.userInfo as! [String: AnyObject]        let value1 = userInfo["value1"] as! String        let value2 = userInfo["value2"] as! Int                print("\(name) 获取到通知,用户数据是[\(value1),\(value2)]")                sleep(3)                print("\(name) 执行完毕")    }    deinit {        //记得移除通知监听        NSNotificationCenter.defaultCenter().removeObserver(self)    }   }

The results of the operation are as follows: Send Notifications
Observer 1 gets to the notification that the user data is [hangge.com,12345]
Observer 1 Execution complete
Observer 2 gets to the notification that the user data is [hangge.com,12345]
Observer 2 Execution complete
Notification complete( through the operation can be seen, the notification after the execution of the synchronization, that is, after all the observers have finished, the main line friend continue to go down. )
Original from: www.hangge.com reprint please keep the original link: http://www.hangge.com/blog/cache/detail_828.html

Swift-use Nsnotificationcenter to send notifications and receive notifications

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.