Swift中的NSNotifications 3 [英] NSNotifications in Swift 3

查看:108
本文介绍了Swift中的NSNotifications 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新通知目前是否在Swift 3中无效?我正在做:

Are the new notifications not currently working in Swift 3? I am doing:

NotificationCenter.default().post(name: DidTouchParticleView, 
                                  object: self.particle as? AnyObject)

在自定义视图的touchesBegan()中我需要发送 particle 视图控制器的对象(如果有)。所以我这样做:

in a custom view's touchesBegan() and I need to send the particle object to the view controller if there is one. So I do this:

NotificationCenter.default().addObserver(forName: DidTouchParticleView, 
                                         object: self,
                                         queue: OperationQueue.main(),
                                         using: presentParticleDisplayView(notification:))

在视图控制器的viewDidLoad()中。我确定当我点击我的自定义视图时,会显示该特定视图控制器,但是,从不调用函数 presentParticleDisplayView(notification :)

in a view controller's viewDidLoad(). I am certain that that particular view controller is the one presented when I tap my custom view, however, the function presentParticleDisplayView(notification:) is never called.

此外, DidTouchParticleView 在全球范围内定义如下:

Also, DidTouchParticleView is defined globally like this:

let DidTouchParticleView = NSNotification.Name("didTouchParticleView")

这是由于测试版,或者我做错了什么?

Is this due to the beta, or am I doing something wrong?

推荐答案

听起来你可能打算打电话给 addObserver(_:selector:name:object:),其中第二个参数消息(选择器:)被发送到第一个参数(目标)。

It sounds like you may be intending to call addObserver(_:selector:name:object:), where the second parameter message (the selector:) is sent to the first parameter (the target).

相反,你正在调用错误的方法, addObserver(forName:object:queue:using :) ,效果完全不同。

Instead, you are calling the wrong method, addObserver(forName:object:queue:using:), which works quite differently.

此外,关于问题的第二部分:

Also, as to the second part of your question:

let DidTouchParticleView = NSNotification.Name("didTouchParticleView")

这是正确的(差不多);它应该是

That is correct (almost); it should be

let DidTouchParticleView = Notification.Name("didTouchParticleView")

所有通知名称现在都是 Notification.Name 个实例。这样做的正确方法是:

All notification names are now Notification.Name instances. The proper way to do this is to say:

extension Notification.Name {
    static let didTouchParticleView = Notification.Name("didTouchParticleView")
}

然后,您可以将通知的名称称为<$你的代码中有c $ c> .didTouchParticleView 。

You can then refer to the notification's name as .didTouchParticleView throughout your code.

这篇关于Swift中的NSNotifications 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆