【问题标题】:static var or AppDelegate静态变量或 AppDelegate
【发布时间】:2011-08-14 19:57:09
【问题描述】:

我必须在我的程序中使用 NSDate var,并且该 var 将是 dealloc 和 realloc(我必须在该日期添加一些月份和年份,并且没有其他可能性)。

该 var 在许多方法中必须是用户,我想将此 var 放在全局中。还有其他选择吗?不干净,但我不知道该怎么做...

非常感谢帮助我!!!

【问题讨论】:

    标签: iphone objective-c xcode global-variables nsdate


    【解决方案1】:

    我建议将其放入您的 AppDelegate。然后你可以通过

    MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"%@", [appDelegate myGlobalDate]);
    

    当然,您需要在 MyAppDelegate 中为 myGlobalDate 设置 getter 和 setter。

    【讨论】:

    • 我投票反对这种方法。不要让应用程序委托成为“大师级超级无所不能的经理”类。去过那里,做过,从中学习。 :)
    • 不要用这样的废话把你的应用程序代理搞得一团糟。
    • 好的,那么请告诉我们您从这个错误中学到了什么。
    • 好的,谢谢,我会在星期一用这种方法挠头 ;-)
    • @dasdom 我了解到很容易将每一个非常小的片段方便地推送到应用程序委托中,从而逐步降低代码质量。而且一旦你上了那个臭名昭著的大课,就很难再把它拉直了。应用程序委托实际上应该只是管理应用程序生命周期。 (好的,如果该特定属性属于该类别,那很好。)
    【解决方案2】:

    想想这个变量的用途,以及你最常使用它的地方。那么你应该已经为它找到了一个自然的地方。

    全局变量不是绝对可怕的东西,单例也不是(可能很适合这里)。但是,也许它真的属于用户默认值,或者某个视图控制器。

    【讨论】:

      【解决方案3】:

      回答是否有其他选择的问题(而不是说是否应该这样做)。一种选择是专门创建一个类作为保存您需要全局可用的变量的地方。来自blog post的一个例子

      @interface VariableStore : NSObject
      {
          // Place any "global" variables here
      }
      // message from which our instance is obtained
      + (VariableStore *)sharedInstance;
      @end
      
      @implementation VariableStore
      + (VariableStore *)sharedInstance
      {
          // the instance of this class is stored here
          static VariableStore *myInstance = nil;
      
          // check to see if an instance already exists
          if (nil == myInstance) {
              myInstance  = [[[self class] alloc] init];
              // initialize variables here
          }
          // return the instance of this class
          return myInstance;
      }
      @end
      

      然后,从其他地方:

      [[VariableStore sharedInstance] variableName]
      

      当然,如果你不喜欢他们在上面的例子中实例化单例的方式,你可以选择你喜欢的pattern from here。我自己喜欢 dispatch_once 模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多