0

我有如下代码:

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);
}

我得到的答案是:键类 NSDecimalNumber 虽然将 locID 类型转换为 NSDecimalNumber,但我没有得到键的确切值,而只有 null。请帮助解决这个问题。

4

2 回答 2

1

键是 NSDecimalNumber,但您从 NSString 开始,因此您可以像这样提取数据:

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

您说您尝试了强制转换,但这不会执行从一种对象类型到另一种对象类型的任何转换;你需要一个方法decimalNumberWithString:

于 2012-09-08T06:33:53.883 回答
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];
}
于 2012-09-04T04:33:06.530 回答