2012-09-03 36 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

完美我看到它的工作。非常感谢。对不起,我是新来的,所以不会投票给你的答案。 –

相关问题