【问题标题】:NotificationCenter: How to add a notification in BaseController without it being added multiple times?NotificationCenter:如何在 BaseController 中添加通知而不添加多次?
【发布时间】:2022-01-08 19:27:16
【问题描述】:

我有一个 BaseViewController,我的应用程序中的所有视图控制器都继承自这个 BaseViewController 类。我想在我的一些视图控制器中收听自定义通知。我在 BaseViewController 的 viewWillAppear 和 viewWillDisappear 方法中添加了以下代码

    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(self.actOnNotification), name: NSNotification.Name("MyNotification"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(NSNotification.Name("MyNotification"))
    }

我的应用程序的设计方式是在自定义启动视图控制器和另一个视图控制器(这两个都继承自 BaseViewController)之后加载主页。基本上,它是堆栈中的第三个视图控制器。

现在,当我的应用主页加载时,actOnNotification 方法被调用了 3 次。有没有一种方法可以让我在主页加载时只调用一次?

如果我直接在应用程序的主页上收听通知,它显然可以工作。

【问题讨论】:

  • 如果您在基类中添加通知观察者,那么所有实例都将观察通知。如您所说,解决方案是仅在需要观察通知的视图控制器中添加观察者。您的基类应该只包含常见的功能。如果你想在几个控制器中观察通知,那么你可以在你的基类中添加一个函数来添加观察者并从相关的子类viewWillAppear 调用该函数。您可以设置一个布尔属性,以便超级“viewWillDisappear”删除观察者
  • 谢谢,Hoseinali Alborzi 的回答实际上帮助我解决了这个问题。

标签: ios swift nsnotificationcenter notificationcenter


【解决方案1】:

在navigationController中实现addObserver之后,您可以为mainViewController使用navigationController

class MainNavigationViewController: UINavigationController {

      override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(self.actOnNotification), name: NSNotification.Name("MyNotification"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(NSNotification.Name("MyNotification"))
    }
}

你也可以获取 currentViewcontroller

    guard let currentViewcontroller = self.viewControllers.last() else { return}

【讨论】:

  • 谢谢。就我而言,它是一个 TabBarController,我最终在其中完成了上述操作。我已经接受了这个作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 2020-10-01
  • 2023-03-06
相关资源
最近更新 更多