【问题标题】:Access object in AppDelegate from ViewController从 ViewController 访问 AppDelegate 中的对象
【发布时间】:2019-05-27 14:42:57
【问题描述】:

AppDelegate.swift 中,我声明了一个 NSStatusBar 对象,如下所示:

var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.title = "chess"
statusItem.button?.target = self
statusItem.button?.action = #selector(showSettings)

并且工作正常,但我想更改 viewController.swift

中的标题

我在尝试这个(在视图控制器中):

var appd = AppDelegate()
appd.statusItem.button?.title = "ELO: \(parsing2.chess_daily.last.rating)"

但标题没有改变......我该怎么做???

【问题讨论】:

  • 尝试在 AppDelegate 中创建一个更改标题的函数,然后从您的 vc 中调用它:AppDelegate().changeStatusTitle("ELO")
  • 我不认为从另一个类调用属于你的 AppDelegate 的函数会是好的编码风格
  • 嗨@Koen 我得到的结果与上面的代码相同
  • @RX9 应用程序委托是应用程序的根单例,它在很大程度上用于处理没有任何其他更好的拥有视图控制器的对象和函数。从应用程序委托中访问数据和调用函数是一种非常标准的编码实践。 OP 遇到的问题是他没有访问单例实例。

标签: swift macos viewcontroller appdelegate


【解决方案1】:

NSApplication获取委托对象,默认初始化器AppDelegate()创建一个新的无关实例。

let appDelegate = NSApp.delegate as! AppDelegate
appDelegate.statusItem.button?.title = "ELO: \(parsing2.chess_daily.last.rating)"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多