2013-02-16 51 views
1

我想在我的iOS应用程序的常量Singleton类中设置全局常量值,以便导入常量的任何类都可以使用那些价值。在iOS应用程序中设置枚举的枚举,以便可以在整个应用程序中访问

但是,在用这个想法玩了几个小时后,我仍然无法使它工作。

在我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

有人有什么建议吗?

感谢

做,这是简单地把它在你的预编译的头(.PCH),如果你不打算要改变枚举了不少

回答

3

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

更新

的Objective-C不支持命名空间,它并不支持类级别的常量或枚举。

行:

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

应该是:

myDetailButton.tag = mapViewAccessoryButton; 

假设你定义在一些.h文件中的UIBUTTON_TAG枚举。

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

更新2 Objetive-C的结果:

没有得到你想要的东西,但不枚举的一种方式。像这样的东西应该工作:

Constants.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 

Constants.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; 

我不知道是否有虽然这是一个点。

+0

它工作,如果我把它放在.h文件中,但我更喜欢变量封装在常量类。我很难配置。看起来很简单,但由于某种原因,我不能让它工作 – banditKing 2013-02-16 21:21:04

+1

@banditKing你不能同时让枚举对其他类可见,并隐藏它们的存在... – 2013-02-16 21:34:39

+0

我可以封装常量中的枚举,然后通过常量属性只要?这就是我想要做的,但不知道如何 – banditKing 2013-02-17 01:01:36

1

的一种方式。