2013-02-16 55 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

的一種方式。