swift - 使用 swift 添加 NSNotification Observer

标签 swift nsnotification

我正在使用this example其中解释了 NSNotification 的使用。

就我而言,我有一个 UIViewController,其中有一个 UITableView。对于这个 TableView ,我通过实例化我的 UITableViewController 以编程方式分配一个 dataSourcedelegate。到目前为止,我还没有声明任何 init,因此一直使用简单的 init() 来初始化我的 UITableViewController。 (这个 UITableViewController 不在 StoryBoard 上)。

class foo: UIViewController{
      @IBOutlet weak var fooTable: UITableView!
      var fooTableViewController = MyTableViewController()

      override func viewDidLoad(){
             super.viewDidLoad()
             fooTable.delegate = fooTableViewController
             fooTable.dataSource = fooTableViewController
      }
}

class MyTableViewController: UITableViewController {
     override func viewDidLoad(){
           super.viewDidLoad()
           NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived", name: "TEST_NOTIFICATION", object: nil)
     }
}

如果我尝试在 UIViewControllerviewDidLoad() 中添加观察者,它不起作用。

所以我的问题是:使用 NSNotification 是否需要使用 init(coder aDecoder: NSCoder) ?如果是这样,那么在 swift 中使用此 init 进行初始化的正确方法是什么?我应该如何在我的 UIViewController 实例 foo 中实例化 MyTableViewController?

最佳答案

viewDidLoad 仅在加载 View Controller 的 View 时调用 - 在您显示的代码中创建一个 TableView Controller 子类,将其指定为另一个 TableView 的数据源和委托(delegate)(令人困惑,因为它已经是其自己的 TableView 的数据源和委托(delegate)),但实际上从未对 TableView Controller 的 View 执行任何操作。

这意味着 viewDidLoad 将不会被调用。

您可能应该将 TableView Controller 的 tableView 添加为 subview ,并将其添加为 subview Controller ,以便正确转发旋转和外观事件。

请注意,问题和答案与通知中心或 Swift 无关,而只是了解 View Controller 生命周期。

如果您想要一个单独的对象充当 TableView 的数据源和委托(delegate),这是个好主意,但不要使用 UITableViewController 子类。只需创建一个符合数据源和/或委托(delegate)协议(protocol)的普通对象。

关于swift - 使用 swift 添加 NSNotification Observer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536761/

相关文章:

swift - 如何使用选择器: with function that throws exception in Swfit

ios - 如何删除 UITableView 部分标题分隔符

ios - 如何在 IOS Swift 4 的 Uitableviewcell 中递增和递减变量

swift - 倒计时代码在 Swift 2 中不起作用

ios - CollectionView 以 UIScrollView 作为单元格

ios - NSNotification 中心如何管理它观察对象?

ios - 从 SwiftUI 中的导航栏中删除后退按钮文本

swift - 观察员从未调用

ios - 有没有办法限制 NSNotification?

objective-c - NSNotification 是检测变化的正确选择吗?