ios - 每当iOS Swift中的对象发生更改时如何调用notificationCenter?
问题描述
我试图实现当对象更新时,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)
}
}
我的问题是,每当对象模型发生更改时,它应该触发通知发布方法并且它应该接收观察者。
我曾尝试在 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"
}
推荐阅读
- node.js - Nodejs并发请求覆盖变量
- android - 安全异常 App.Utils.getDeviceSerial 错误。如何解决?
- reactjs - 导航时反应本机组件安装问题
- android - android studio 中的倒计时
- java - 将多个 pdf 文件上传到 Firebase 存储 - Android
- javascript - Cryptonoob 尝试在 .NET 上加密并在 Javascript 上解密
- java - 以编程方式更改视图边距
- c# - 如何从字符“/u”之后的字符串中删除所有内容?
- module - esphome 如何为带有集成 4 继电器的模块 esp01 编写配置
- javascript - 使用 FlatList 的 React-Native for 循环给出错误