【问题标题】:NSNotificationCenter addObserver in Swift while call a private methodNSNotificationCenter addObserver 在 Swift 中调用私有方法
【发布时间】:2014-10-21 09:15:56
【问题描述】:

我使用addObserver API 接收通知:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)    

我的方法是:

func methodOFReceivedNotication(notification: NSNotification){
//Action take on Notification
}    

是的,它有效! 但是当我将方法 methodOFReceivedNotication 更改为私有时:

private func methodOFReceivedNotication(notification: NSNotification){
//Action take on Notification
}    

xCode 发给我一个错误:unrecognized selector sent to instance

如何在目标为self 时调用私有方法?我不想将methodOFReceivedNotication 方法暴露给任何其他人。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    只需使用dynamic 修饰符标记它或在方法声明中使用@objc 属性

    dynamic private func methodOFReceivedNotication(notification: NSNotification){
        //Action take on Notification
    }
    

    @objc private func methodOFReceivedNotication(notification: NSNotification){
        //Action take on Notification
    }
    

    【讨论】:

    • 这对我有用,添加了动态,但为什么呢?这是怎么回事?
    • @StevenMarlowe,这篇文章(link) 可能会有所帮助。
    • 好答案+文章@YiminLin 我只是认为动态关键字应该是第一个选项(因为它不是“解决方法”)
    【解决方案2】:

    您是否考虑过使用-addObserverForName:object:queue:usingBlock:

    NSNotificationCenter.defaultCenter().addObserverForName("NotificationIdentifier", object: nil, queue: nil, usingBlock: {
        [unowned self] note in
        self.methodOFReceivedNotication(note)
    })
    

    或者不调用私有方法,只执行操作。

    NSNotificationCenter.defaultCenter().addObserverForName("NotificationIdentifier", object: nil, queue: nil, usingBlock: {
        [unowned self] note in
        // Action take on Notification
    })
    

    【讨论】:

    • 我喜欢这个解决方案,因为 Swift 非常重视“安全”,并且能够显式调用方法而不是为方法名称提供带引号的字符串(对于选择器)更安全.那么如果你稍后更改方法签名,你实际上会遇到编译错误而不是运行时错误。
    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2014-11-22
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多