2012-06-02 29 views
0

我試圖從一個NSDictionaryNSNumber s作爲關鍵獲取和設置。我想我正在根據這個答案https://stackoverflow.com/a/6891489/194309做的事情,但我的代碼下面返回空值。我怎麼能從一個NSDictionary int的關鍵是NSNumbers

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSInteger const SET1 = 1; 
    NSInteger const SET2 = 2; 


    videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys: 
        [NSNumber numberWithInt:SET1], @"well", 
        [NSNumber numberWithInt:SET2], @"great", 
        nil]; 
    NSLog(@"to see well: %@",[videoKeyOfTag objectForKey:[NSNumber numberWithInt:SET1]]); 

} 

我希望在日誌中to see well: well而是我看我不想要什麼:

to see well: (null) 

int開始,我怎麼能叫objectForKeyNSDictionary,其中鍵是NSNumber小號?

(我最終想[sender tag]作爲元鍵提取從NSDictionary值)

回答

1

如果你想要的數字是按鍵,您需要反轉構造函數中的順序:

videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys: 
        @"well", [NSNumber numberWithInt:SET1], 
        @"great", [NSNumber numberWithInt:SET2], 
        nil]; 
+0

令人震驚的指控!!! –

+0

好消息:我也錯誤地聲明tagOfVideoKeys,所以修復只是切換接收新構建的NSDictionaries –

1

initWithObjectsAndKeys - 這裏第一個參數是value,第二個參數是key。你正在做相反的事情。您已將@"well"@"great"用作鍵,而不是值。你應該寫:

videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys: 
        @"well", [NSNumber numberWithInt:SET1], 
        @"great", [NSNumber numberWithInt:SET2], 
        nil]; 
+0

令人震驚的指控的變量! –

+0

電腦*是如此*迂腐! –

1

還有一個原因初始化方法被調用initWithObjectsAndKeys:,而不是initWithKeysAndObjects:(儘管後者會更有意義,對我來說這是蘋果......) 無論如何,奇數參數(第一,第三等)是值,偶數(第二,第四等)是鍵。因此請嘗試:

videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys: 
       @"well", [NSNumber numberWithInt:SET1], 
       @"great", [NSNumber numberWithInt:SET2], 
       nil]; 

改爲。

+1

是的,這個方法被命名爲它的工作原理,但是它讓我的小兔子大腦很困惑! –