2012-09-03 38 views
0

我的代碼如下:雖然它有數據,但無法從NSMutableDictionary中檢索密鑰的值

1.我有一個按鈕的操作方法如下。

(IBAction)enableDisableFB:(id)sender {//have below local variable 
NSMutableDictionary *fbLocationLatitude = [[NSMutableDictionary alloc] init]; 

2.有一個循環,我在這個字典中設置對象,如

[fbLocationLatitude setObject:latitude forKey:locID]; //here latitude and locID both are NSString 

3.In在同一方法的另一種循環,我試圖找回價值,但它給了(空)在NSLog的

NSLog(@"latitude for key %@ = %@",locID, [fbLocationLatitude objectForKey:locID]); 
//above statement gives me output -> latitude for key 114943251851302 = (null) 

但環之後我打印使用

NSLog(@"location dictionary = %@",fbLocationLatitude); 
//which gives me below output. Sample given 

location dictionary = { 
    114943251851302 = "40.4414"; 
    109782595706984 = "38.9966"; 
    108867759137051 = "22.47"; 
    110148382341970 = "25.7877"; 
    107611279261754 = "43.1655"; 
    111803735513513 = "27.1828"; 
    109155699106505 = "18.3167"; 
    103734539665100 = "19.09"; 
完整詞典

這有我正在尋找的鍵值,但同樣我無法使用objectForKey。 請幫我解決這個問題。

for (NSUInteger i =0; i< [fbLocationID count];i++) 
{ 
    // NSLog(@"person creation"); 
    NSString *locID = [NSString stringWithString:[fbLocationID objectAtIndex:i]]; 
    NSLog(@"latitude for key %@ = %@",locID, [fbLocationLatitude objectForKey:locID]);        
} 
NSLog(@"location dictionary = %@",fbLocationLatitude); 

這是代碼是如何。我也嘗試使用下面的代碼

for (id ik in [fbLocationLatitude allKeys]) 
{ 
const char* classname=class_getName([ik class]); 
NSLog(@"class of key %s",classname); 
} 

打印類鍵和我得到ANS爲:類鍵NSDecimalNumber 雖然類型轉換的LOCID到NSDecimalNumber,我沒有得到的關鍵,但只有空精確值。 請幫忙解決這個問題。

+0

當你向字典中添加值時,你是否正面'latitude'不是'nil'? –

+0

在哪個循環之後,字典的日誌會爲您提供正確的值?第一個添加值的位置,或第二個您嘗試檢索它們的位置? – rdelmar

+0

在你的NSLog調用之前設置一個斷點並檢查gdb中字典內容的類型和值。 – Samir

回答

0

檢查這樣的:

if([[fbLocationLatitude objectForKey:locID] isKindofClass:[NSNumber class]]) 
{ 
    NSNumber *num = fbLocationLatitude objectForKey:locID]; 
} 
else if([[fbLocationLatitude objectForKey:locID] isKindofClass:[NSString class]]) 
{ 
    NSString *strnum = fbLocationLatitude objectForKey:locID]; 
} 
+0

@亞當:是的,我相信,因爲我在同一本字典NSlog結束,我看到它的所有值。 –

+0

@rdelmer第一次循環後,如果我得到的值我得到他們正確的,但在第二次循環後,字典有像上面給出的值,但objectForKey無法檢索它們。 –

+0

@sameer:我從數組中獲取String locID並使用它來搜索此字典以獲取相關值...希望我很清楚。我有一個NSArray,我存儲所有locID值。 –

1

的關鍵是NSDecimalNumber,但你開始一個NSString,這樣你就可以提取數據是這樣的:

NSDecimalNumber locIDnumber = [NSDecimalNumber decimalNumberWithString: locID]; 
id latitude = [fbLocationLatitude objectForKey:locIDnumber]; 
NSLog(@"latitude for key %@ = %@", locID, latitude); 

你說你嘗試了投,但是這不會執行從一個對象類型到另一個對象類型的任何轉換;你需要一種方法,如decimalNumberWithString:

+0

完美我看到它的工作。非常感謝。對不起,我是新來的,所以不會投票給你的答案。 –

相關問題