繁体   English   中英

每当在 iOS Swift 中对对象进行更改时如何调用通知中心?

[英]How to call notificationCenter whenever changes made in object in iOS Swift?

我试图实现当对象更新时,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 中调用通知观察者。 什么都没收到。

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

确保您的视图控制器已注册观察者。 分享我的工作正常的代码。 我在 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"
}

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

如果不:

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 [AnyHashable:Any]? 作为输入:

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 }

}

在这里,您已经知道如何注册和取消注册通知,让我们从通知中获取自定义 userInfo

首先使用自定义 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")

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM