【问题标题】:setting up enum in a singleton within an ios app such that it can be accessed throughout the app在 ios 应用程序中的单例中设置枚举,以便可以在整个应用程序中访问它
【发布时间】:2013-02-16 20:16:53
【问题描述】:

我想在我的 iOS 应用程序的 Constants Singleton 类中设置我的全局常量值,以便任何导入常量的类都可以使用这些值。

但是,在这个想法玩了几个小时之后,我仍然无法实现它。

在我的 Constants.m 文件中

 @interface Constants()
 {
    @private
    int _NumBackgroundNetworkTasks;
    NSDateFormatter *_formatter;
 }
 @end

 @implementation Constants

 static Constants *constantSingleton = nil;
 //Categories of entries
 typedef enum
 {
   mapViewAccessoryButton = 999

  } UIBUTTON_TAG;


 +(id)getSingleton
 {

   .....
  }

我有另一个类 MapViewController,我在其中引用了常量单例,我试图访问这样的枚举

 myDetailButton.tag =  self.constSingleton.UIBUTTON_TAG.mapViewAccessoryButton;

但是,这不起作用。我无法访问 mapviewcontroller 中的 UIBUTTON_TAG

有人有什么建议吗?

谢谢

【问题讨论】:

    标签: ios enums singleton global-variables


    【解决方案1】:

    如果您希望枚举在整个应用程序中可用,请将枚举定义放在 .h 文件中,而不是 .m 文件中。

    更新

    Objective-C 不支持命名空间,也不支持类级常量或枚举。

    行:

    myDetailButton.tag =  self.constSingleton.UIBUTTON_TAG.mapViewAccessoryButton;
    

    应该是:

    myDetailButton.tag =  mapViewAccessoryButton;
    

    假设您在某个 .h 文件中定义了 UIBUTTON_TAG 枚举。

    当您编译一个 Objective-C 应用程序时,所有枚举的所有值都必须具有唯一的名称。这是 Objetive-C 基于 C 的结果。

    更新 2

    有一种方法可以得到你想要的,但不是用枚举。像这样的东西应该可以工作:

    常量.h:

    @interface UIBUTTON_TAG_ENUM : NSObject
    
    @property (nonatomic, readonly) int mapViewAccessoryButton;
    // define any other "enum values" as additional properties
    
    @end
    
    @interface Constants : NSObject
    
    @property (nonatomic, readonly) UIBUTTON_TAG_ENUM *UIBUTTON_TAG;
    
    + (id)getSingleton;
    
    // anything else you want in Constants
    
    @end
    

    常量.m

    @implementation UIBUTTON_TAG_ENUM
    
    - (int)mapViewAccessoryButton {
        return 999;
    }
    
    @end
    
    @implementation Constants {
        int _NumBackgroundNetworkTasks;
        NSDateFormatter *_formatter;
        UIBUTTON_TAG_ENUM *_uiButtonTag;
    }
    
    @synthesize UIBUTTON_TAG = _uiButtonTag;
    
    - (id)init {
        self = [super init];
        if (self) {
            _uiButtonTag = [[UIBUTTON_TAG_ENUM alloc] init];
        }
    
        return self;
    }
    
    // all of your other code for Constants
    
    @end
    

    现在你可以这样做了:

    myDetailButton.tag =  self.constSingleton.UIBUTTON_TAG.mapViewAccessoryButton;
    

    我不确定这是否有道理。

    【讨论】:

    • 如果我把它放在 .h 文件中就可以了,但我更喜欢封装在常量类中的变量。我很难配置它。看起来很简单,但由于某种原因我无法让它工作
    • @banditKing 你不能同时让枚举对其他类可见并隐藏它的存在......
    • 我可以将枚举封装在常量中,然后仅通过常量属性访问它吗?这就是我想做的,但不知道怎么做
    • 谢谢。 +1 以获得详细答案
    【解决方案2】:

    如果您不打算对枚举进行大量更改,那么一种方法就是将其粘贴到您的预编译头文件 (.pch) 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-09
      • 2011-03-08
      • 2020-12-28
      • 2014-08-05
      • 2012-03-28
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多