码迷,mamicode.com
首页 > 移动开发 > 详细

iOS-观察者设计模式

时间:2015-09-18 13:41:16      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

NSNotificationCenter.defaultCenter().addObserver(<#observer: AnyObject#>, selector: <#Selector#>, name: <#String?#>, object: <#AnyObject?#>)

 

NSNotificationCenter.defaultCenter().addObserver(self自己就是观察者, selector: ""选择处理通知的方法(接收通知的方法), name: ""通知的名字, object: nil对象为空)

 

下面红色标注部分是错的部分

 

import UIKit

class ViewController: UIViewController {
   
   
    @IBAction func onClick(sender: AnyObject) {
        var  resViewController = self.storyboard?.instantiateViewControllerWithIdentifier("navViewController") as UINavigationController
        self.presentViewController(resViewController, animated: true ) { () -> Void in
            NSLog("弹出模态视图")
        }
    }
   
   
    //主要是方法后面没有加上冒号,接收通知的是一个方法,需要加上冒号,不加冒号表示字符串。
    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "registerCompletion:",
            name: "RegisterCompletionNotification", object: nil)
       
        //监听系统通知
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "handleEnterBackground:",
            name: UIApplicationDidEnterBackgroundNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "handleEnterForeground:",
            name: UIApplicationWillEnterForegroundNotification, object: nil)
    }
   
   
   
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
   
   
    //TODO接收通知
   
    func registerCompletion(notification : NSNotification) {
       
        let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
        let username = userInfo["username"]!
        NSLog("username = %@",username)
    }
   
    func handleEnterBackground(notification : NSNotification) {
        NSLog("进入到后台")
    }
    func handleEnterForeground(notification : NSNotification) {
        NSLog("回到前台")
    }
   
   
}

iOS-观察者设计模式

标签:

原文地址:http://www.cnblogs.com/wenios/p/4818830.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!