Swift-use Nsnotificationcenter to send notifications and receive notifications

Source: Internet
Author: User
Tags uikit

Reprinted from: http://www.mamicode.com/info-detail-1069228.html

Label:

1, notice (nsnotification) describes the notice here does not mean to the user to see the notification message, but the system inside the message delivery notification. 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, System notification registration and response For 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 importUIKitclass ViewControllerUIViewController{        overridefuncviewDidLoad() {        super.viewDidLoad()                 letnotificationCenter = NSNotificationCenter.defaultCenter()                letoperationQueue = NSOperationQueue.mainQueue()                 letapplicationDidEnterBackgroundObserver =            notificationCenter.addObserverForName(UIApplicationDidEnterBackgroundNotification,                object: nil, queue: operationQueue, usingBlock: {                (notification: NSNotification!) in                    print("程序进入到后台了")        })                 //如果不需要的话,记得把相应的通知注册给取消,避免内存浪费或奔溃        //notificationCenter.removeObserver(applicationDidEnterBackgroundObserver)    }        overridefuncdidReceiveMemoryWarning() {        super.didReceiveMemoryWarning()    }}

3, the use of a custom notification notification type is actually a string, so we can also use our own defined notifications (also can pass the user custom 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 importUIKitclassViewControllerUIViewController{        letobservers = [MyObserver(name: "观察器1"),MyObserver(name: "观察器2")]    overridefuncviewDidLoad() {        super.viewDidLoad()                print("发送通知")        NSNotificationCenter.defaultCenter().postNotificationName("DownloadImageNotification",            object: self, userInfo: ["value1":"hangge.com""value2": 12345])        print("通知完毕")    }        overridefuncdidReceiveMemoryWarning() {        super.didReceiveMemoryWarning()    }}

---myobserver.swift---
1234567891011121314151617181920212223242526272829303132 importUIKitclassMyObserverNSObject{        varname:String ""    init(name:String){        super.init()                self.name = name        NSNotificationCenter.defaultCenter().addObserver(self, selector:"downloadImage:",            name: "DownloadImageNotification", object: nil)    }        funcdownloadImage(notification: NSNotification) {        letuserInfo = notification.userInfo as! [StringAnyObject]        letvalue1 = userInfo["value1"asString        letvalue2 = userInfo["value2"asInt                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

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.