ios - Swift - 观察静态成员的变化,而不使用属性观察器
问题描述
我遇到了下一个情况:当应用特殊条件时(静态成员更改为 True,另一个类访问此静态属性并在某些条件适用)
如果我对属性观察者这样做:
//this is property of load view controller
static var isFilled: Bool = false {
didSet{
if isFilled == true {
print("data is Filled")
//load view controller - my present VC, which I want to switch
var loadVC = LoadViewController()
loadVC.changeViewController(vc: loadVC )
这是 changeViewController 函数:
func changeViewController(vc: UIViewController) {
let sb = UIStoryboard(name: "Main", bundle: nil )
//main view controller - controller, which i want to Go to
var mainViewController = sb.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.present(mainViewController, animated: true, completion: nil)
}
它会抛出一个错误尝试呈现视图不在窗口层次结构中的视图控制器
而且,它在 LoadViewController 类中执行
据我了解,避免此错误的唯一方法是从viewDidApper调用该函数,该函数不能在这种情况下使用,因为我必须仅在应用条件时调用它。是否有任何替代方法可以使用属性观察器执行该操作?
我确信有多种方法可以执行此操作,并且我这边可能存在误解。我是一个非常新的开发人员,对 Swift 完全陌生。所有的建议将不胜感激。
解决方案
您可以通过注册通知来使用 NotifiationCenter,然后在您想要更新某些内容时调用它,例如聊天应用程序中的“updateConversations”。例如在 viewDidLoad() 中,注册你的通知:
NotificationCenter.default.addObserver(self, selector: #selector(self.updateConversations(notification:)), name: NSNotification.Name(rawValue: "updateConversations"), object: nil)
将此函数添加到类中:
@objc func updateConversations(notification: NSNotification) {
if let id = notification.userInfo?["id"] as? Int,
let message = notification.userInfo?["message"] as? String {
// do stuff
}
}
在应用程序的任何位置使用通知:
let info = ["id" : 1234, "message" : "I almost went outside today."]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateConversationsList"), object: self, userInfo: info)
推荐阅读
- python-3.x - Python,tkinter 如何防止在主窗口调整大小期间隐藏/调整小部件
- python - 如何创建元组其中输入是列中的文本并输出为行号?
- jxls - JXLS 不可访问或未知属性
- c# - 为什么我的 ListView 没有绑定到 ItemSource?
- aspnetboilerplate - 如何在 ASP.NET Boilerplate 中将 Angular 应用程序部署到 IIS?
- bash - 如何在一个文件中一个一个地运行一组终端命令?
- php - PHP中整数的反向块分割
- powershell - 为什么我的 -match 调用在获取网络驱动器时包含无效项目?
- vba - Excel 2013 VBA 向公式添加新行
- php - 加密事件在 Codeignator 中无法正常工作