【问题标题】:How to access properties on AppDelegate from classes owned by it?如何从 AppDelegate 拥有的类访问属性?
【发布时间】:2015-07-08 20:38:19
【问题描述】:

我正在编写一个简单的 OS X 应用程序,到目前为止的结构如下:

  • 主要业务逻辑在AppDelegate.m
  • AppDelegate 拥有 2 个带有 xib 的 ViewControllers,并在窗口中显示

我有时需要从 ViewControllers 访问 AppDelegate 上的属性,我这样做是这样的:

AppDelegate *delegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
delegate.someProperty = someValue;

这“感觉”很老套。这是正确的模式还是真的很愚蠢?

我想出的两种替代架构是:

  1. 使用委托并在 VC 中定义某种“UI Delegate”协议并使 AppDelegate 符合它
  2. 让 VC 发布 AppDelegate 监听的通知

第一个感觉纠结脏乱,第二个感觉不靠谱。

这里的正确模式是什么? AppDelegate拥有的VC应该如何访问其属性?

【问题讨论】:

    标签: objective-c macos cocoa


    【解决方案1】:

    试试这个

    AppDelegate *app = [NSApp delegate];
    

    不是这个

    AppDelegate *delegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
    

    【讨论】:

      【解决方案2】:

      您可以在NSObject 上定义一个类别,这将允许您从项目中的任何对象中获取AppDelegate 的实例。

      @interface NSObject (AppDelegate)
      
      - (AppDelegate *)appDelegate;
      
      @end
      

      然后您可以在您的项目 .pch 文件中包含该类别,以便它在任何地方都可用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 2014-08-10
        相关资源
        最近更新 更多