簡體   English   中英

typedef枚舉類型是NSDictionary的關鍵?

[英]typedef enum type as key to NSDictionary?

枚舉不允許作為NSMutableDictionary的鍵嗎?

當我嘗試通過以下方式添加到字典:

[self.allControllers setObject:aController forKey:myKeyType];

我收到錯誤:

錯誤:'setObject:forKey:'的參數2的不兼容類型

通常情況下,我使用NSString作為我的密鑰名稱,不需要強制轉換為“id”,但為了使錯誤消失,我已經這樣做了。 演員陣容在這里是正確的行為還是枚舉作為關鍵是一個壞主意?

我的枚舉定義為:

typedef enum tagMyKeyType
{
  firstItemType = 1,
  secondItemType = 2
} MyKeyType;

並且字典被定義並正確分配如下:

NSMutableDictionary *allControllers;

allControllers = [[NSMutableDictionary alloc] init];

您可以將枚舉存儲在NSNumber中。 (不是枚舉只是整數?)

[allControllers setObject:aController forKey:[NSNumber numberWithInt: firstItemType]];

在Cocoa中,經常使用const NSStrings。 在.h中你會聲明如下:

NSString * const kMyTagFirstItemType;
NSString * const kMyTagSecondtItemType;

在.m文件中你會放

NSString * const kMyTagFirstItemType = @"kMyTagFirstItemType";
NSString * const kMyTagSecondtItemType = @"kMyTagSecondtItemType";

然后,您可以將其用作字典中的鍵。

[allControllers setObject:aController forKey:kMyTagFirstItemType];

這是一個老問題,但可以更新以使用更現代的語法。 首先,從iOS 6開始,Apple建議將枚舉定義為:

typedef NS_ENUM(NSInteger, MyEnum) {
   MyEnumValue1 = -1, // default is 0
   MyEnumValue2,  // = 0 Because the last value is -1, this auto-increments to 0
   MyEnumValue3 // which means, this is 1
};

然后,由於我們在內部將枚舉表示為NSInteger ,我們可以將它們裝入NSNumber以存儲為字典的鍵。

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

// set the value
dictionary[@(MyEnumValue1)] = @"test";

// retrieve the value
NSString *value = dictionary[@(MyEnumValue1)];

編輯:如何為此目的創建單例字典

通過此方法,您可以創建單例字典來協助解決此問題。 在您擁有的任何文件的頂部,您可以使用:

static NSDictionary *enumTranslations;

然后在你的initviewDidLoad (如果你在UI控制器中這樣做),你可以這樣做:

static dispatch_once_t onceToken;
// this, in combination with the token above,
// will ensure that the block is only invoked once
dispatch_async(&onceToken, ^{
    enumTranslations = @{
        @(MyEnumValue1): @"test1",
        @(MyEnumValue2): @"test2"
        // and so on
    };
});




 // alternatively, you can do this as well
static dispatch_once_t onceToken;
// this, in combination with the token above,
// will ensure that the block is only invoked once
dispatch_async(&onceToken, ^{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    mutableDict[@(MyEnumValue1)] = @"test1";
    mutableDict[@(MyEnumValue2)] = @"test2";
    // and so on

    enumTranslations = mutableDict;
});

如果希望外部可以看到此字典,請將靜態聲明移動到標題( .h )文件中。

不,你不能。 查看方法簽名: id指定一個對象。 枚舉類型是標量。 你不能從一個投射到另一個並期望它正常工作。 你必須使用一個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM