虽然它有数据,但无法从NSMutableDictionary检索密钥的值

时间:2012-09-03 20:47:09

标签: objective-c 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.在同一方法的另一个循环中,我试图检索值,但它在NSLog中给出(null)

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的类 虽然类型转换为NSDecimalNumber的locID,但我没有得到key的确切值但只是null。 请帮忙解决这个问题。

2 个答案:

答案 0 :(得分:1)

键是NSDecimalNumber,但是你从一个NSString开始,所以你可以像这样提取数据:

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

你说你试过一个演员,但这不会执行从一种对象类型到另一种对象类型的任何转换;你需要像decimalNumberWithString:

这样的方法

答案 1 :(得分: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];
}