iOS Swift 中对象发生更改时如何调用通知中心?

问题描述 投票:0回答:4

我试图实现当对象更新时,Notificationcenter Post Message 应该触发并在通知观察者处接收。但就我而言,通知帖子位于一个控制器中,观察者位于另一个控制器中。

这是我从 webViewController 发布通知的代码:

  if let jsonData = jsonString.data(using: .utf8) {
              do {
                let decoder = JSONDecoder()
                let mainObject = try decoder.decode(DynamicTabsModel.self, from: jsonData)

                print("tab model:::", mainObject)


                let dataDict:[AnyObject] = mainObject.tabInfo.tabList as [AnyObject]

                print("data object for tab", dataDict)


                NotificationCenter.default.post(name: Notification.Name("updateParentViewController"), object: mainObject)



              } catch {

                print(error.localizedDescription)

              }
            }

这是 CreateCardViewController 的代码,我在其中接收通知观察者:

 NotificationCenter.default.addObserver(self, selector: #selector(self.updateParentViewController(_:)), name: Notification.Name(rawValue: "updateParentViewController"), object: nil)


   @objc func updateParentViewController(_ notification: NSNotification){


    if let receivedData = notification.object as? DynamicTabsModel {
    //use received data
        print("recieved back data:::", receivedData)

        for d in receivedData.tabInfo.tabList {

            print(d.label )
            self.tabMenuAry.append(d.label)


        }
        initCarbonKitTab()

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "updateParentViewController"), object: nil)

        print("tab menu array::", self.tabMenuAry)


    }

}

我的问题是,每当对象模型发生更改时,它都应该触发通知 post 方法,并且它应该接收观察者。

我尝试在viewdidload、viewdidappear和viewwillappear中调用通知观察者。什么也没收到。

任何帮助,非常感谢...

ios swift xcode nsuserdefaults nsnotificationcenter
4个回答
1
投票

确保您的视图控制器已注册观察者。分享我的代码,运行良好。我在 viewDidLoad 中添加了观察者。您可以在其他ViewController中调用fetchDate来传递该观察者中的流。

import Foundation
import UIKit
// MARK: - Observers

class MyViewController: UIViewController {
    override func viewDidLoad() {
        addObservers()
    }
    deinit {
        removeObservers()
    }
    @objc func notificationAction() {

    }
}

// MARK:- APIHandler
extension MyViewController {
    func fetchData() {
        // Call API when you get success response, post notification
        // NotificationCenter.default.post(name: NSNotification.Name(rawValue: NOTIFICATION_NAME.MY_NOTIFICATION), object: nil)
    }
}
extension MyViewController {
    func addObservers(){
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(notificationAction),
            name: NSNotification.Name(rawValue: NOTIFICATION_NAME.MY_NOTIFICATION) ,
            object: nil
        )
    }
    func removeObservers(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue:NOTIFICATION_NAME.MY_NOTIFICATION), object: nil)
    }
}

enum NOTIFICATION_NAME{
    static let MY_NOTIFICATION = "myNotification"
}

1
投票

从您的

viewDidLoad()

调用这些方法
 NotificationCenter.default.addObserver(
      self,
      selector: #selector(appDidEnterBackground),
      name: UIApplication.didEnterBackgroundNotification,
      object: nil
 )
            
 NotificationCenter.default.addObserver(
       self,
       selector: #selector(appWillEnterForeground),
       name: UIApplication.willEnterForegroundNotification,
       object: nil
 )
 // This code is executed when the app goes to the background
 @objc func appDidEnterBackground() {
    //
 }
    
 // This code is executed when the app goes to the foreground
 @objc func appWillEnterForeground() {
    //
 }

0
投票

你的视图控制器是该通知的观察者吗?

如果没有:

NotificationCenter.default.addObserver(self, selector: #selector(myactionWhenReceivePost()), name: NSNotification.Name(rawValue: "updateParentViewController"), object: nil)

@objc func myactionWhenReceivePost() {

}

答案更新后编辑:

当您添加观察者时,如果您注册了对象参数,则它需要等于发送通知的对象。就像

Notification.Name
一样,如果不相等,您将不会收到任何通知。

此外:将操作的参数从

NSNotification
更改为
Notification
,因为我认为你正在使用 Swift 5.0

如果您想传递数据,请使用以

[AnyHashable:Any]?
作为输入的 userInfo:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateParentViewController"), object: nil, userInfo: yourDictionary)

并在你的行动中:

@objc func myactionWhenReceivePost(_ notification: Notification) {
      guard let myObject = notification.userInfo?["myObject"] as? MyObject else {return }

}

0
投票

好了,因为您已经知道如何注册和取消注册通知,所以让我们从通知中获取自定义 userInfo

首先使用自定义用户信息发布通知:

let customUserInfo: [AnyHashable: Any] = ["value": YOUR_CUSTOM_OBJECT]
NotificationCenter.default.post(name: .myNotificationName, object: nil, userInfo: customUserInfo)

现在,当您想捕获此通知并需要该信息时,请在接收器控制器中使用此信息

@objc func onNotificationCatched(notification:NSNotification) {
    let userInfo:Dictionary<String, YOUR_CUSTOM_OBJECT > = notification.userInfo as! Dictionary<String, YOUR_CUSTOM_OBJECT>
    let value = userInfo["value"]! as YOUR_CUSTOM_OBJECT
    print(value)

}

在接收器控制器的viewDidLoad中使用这个

NotificationCenter.default.addObserver(self, selector: #selector(onNotificationCatched(notification:)), name: .myNotificationName, object: nil)

为了方便使用 NSNotifications Name ,请进行扩展

extension NSNotification.Name {

static let myNotificationName = NSNotification.Name(rawValue: "My-Custom-Notification_String-Name")

}

© www.soinside.com 2019 - 2024. All rights reserved.