macOS

MacOS中Swift使用Notifications的方法

2016-09-20  本文已影响202人  冷大大_hawkleng

1. 介绍

1.1. Notifications能做什么

每个运行中的Application都有一个NSNotificationCenter的实体,其功能就类似于一个公告栏。某些实体(objects)在NSNotificationCenter注册为 observer ,表明其关注某个或某些Notifications。其他objects可以作为 poster 向NSNotificationCenter推送Notifications。当NSNotificationCenter收到Notifications时,NSNotificationCenter则随即将Notifications转发给相应的 observer

1.2. Notifications不能做什么

NSNotificationCenter允许objects向同一个Application中的其他objects发送Notifications,即:NSNotificationCenter可以进行进程内通信,而不能进行进程间通信。
注:如果需要进行进程间通信,可参考NSDistributedNotificationCenter

1.3. NSNotification

NSNotification包含两个主要属性:nameobject,还有一个可选的字典userInfo。其中:name是NSNotification对象的标识;object可以是poster想要发送给observer的任何对象,通常可以是poster对象本身;userInfo则可以用来存储其他任何objects。

1.4. NSNotificationCenter

NSNotificationCenter是整个操作的核心,可以用来做三件事情:

通常使用的方法包括:

  • class func defaultCenter() -> NSNotificationCenter
  • func addObserver(observer: AnyObject, selector aSelector: Selector, name aName: String?, object anObject: AnyObject?)
  • func postNotification(notification: NSNotification)
  • func postNotificationName(aName: String, object anObject: AnyObject?)
  • func removeObserver(observer: AnyObject)

2. 示例

2.1. 定义notification名称

为方便起见,新建一个NSObject类,命名为AppNotification,并定义一个静态常量用来存储notification的名称如下:

class AppNotification: NSObject {
    static let TestMessageNotification = "com.test.TestMessageNotification"
}

2.2. 定义observer

新建一个NSWindowController,命名为ObserverTester,在windowDidLoad中注册observer 如下:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("receiveTestMessageNotification:"), name: AppNotification.TestMessageNotification, object: nil)

定义Selector方法如下:

func receiveTestMessageNotification(note: NSNotification) {
    NSLog(note.description)
}

2.3. 定义poster

新建一个NSWindowController,命名为PosterTester,在窗口上添加一个按钮,并绑定Action如下:

@IBAction func btnPostClick(sender: AnyObject) {
    NSNotificationCenter.defaultCenter().postNotificationName(AppNotification.TestMessageNotification, object: self)
}

2.4. 编译运行

编译运行示例,点击PosterTester的按钮,输出窗口显示如下:

NSConcreteNotification 0xXXXXXXXXXXXX {
name = com.test.TestMessageNotification;
object =<PosterTester: 0xXXXXXXXXXXXX>}

注:该示例中poster发送notification时,只是将PosterTester实例本身作为内容发送,实际项目中可通过获取notification的object来获取相应信息。

Swift Dev for MacOS
上一篇 下一篇

猜你喜欢

热点阅读