1
NSDictionary *tokenData = [[responseDict objectForKey:@"data"] objectForKey:@"multipass"];
dispatch_async(dispatch_get_main_queue(), ^{
    NSString *card = [NSString stringWithFormat:@"%@-%@",
        [[UserAccount sharedInstance] cardNumber],
        [tokenData objectForKey:@"CardPhoneToken"]]; //<-- problem
});

从昨天开始,我一直在与这行代码作斗争。我从服务器获取 JSON 提要,我的问题是,十分之一的tokenData返回是用0而不是 a Dictionary,我不知道为什么。当它返回时,0它也被编译器视为布尔值(也不知道为什么),我得到了错误-[NSCFBoolean objectForKey:]: unrecognized selector sent to instance 0x81aa20

我试过做这样 的事情if(!tokenData) { NSLog(@"This is going to crash"); }但是当tokenData返回0if没有被调用。

esponseDict JSON 我得到: { code = 200; data = { multipass = { CardPhoneBarcodeToken = 562431; CardPhoneToken = 23221; errorMessage = ""; operationResult = 0; }; }; }

这是它在崩溃之前的样子:{ code = 200; data = { multipass = 0; }; }

更新:我已经设法采取行动,如果tokenData不是NSDictionary现在我正面临该else部分的另一个问题。如果 tokenData 不是,我该如何重新加载NSDictionary?我尝试调用 *tokenData = [[responseDict objectForKey:@"data"] objectForKey:@"multipass"]; 在 else 里面,但我不断得到 tokenData = 0 谢谢

4

2 回答 2

3

我会在解析它之前检查它是否tokenData是 a 。NSDictionary

-(void)loadData
{
    NSDictionary *tokenData = [[responseDict objectForKey:@"data"] objectForKey:@"multipass"];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *cardPhoneToken = @"";
        if( [tokenData isKindOfClass:[NSDictionary class]] ){
            retryCount = 0;
            cardPhoneToken = [tokenData objectForKey:@"CardPhoneToken"];
        } else {
            NSLog(@"failed to load data, retrying...");
            retryCount++;
            if( retryCount < 5 ){
                [self loadData];
                return;
            } else {
                NSLog(@"failed after 5 retries");
            }

        }
        NSString *card = [NSString stringWithFormat:@"%@-%@",
                          [[UserAccount sharedInstance] cardNumber],
                          cardPhoneToken];

    });
}
于 2013-01-09T08:30:58.003 回答
1

听起来很熟悉。:)

将块更改为:

^{
    NSString *card;
    if ([tokenData isKindOfClass [NSDictionary class]) {

      card = [NSString stringWithFormat:@"%@-%@",
          [[UserAccount sharedInstance] cardNumber],
          [tokenData objectForKey:@"CardPhoneToken"]]; // <<-- No Problem anymore
     } else {
       // deal with the situation. Probably do: 
      card = [NSString stringWithFormat:"%@-no phone number given", [UserAccount sharedInstance] cardNumber]];
}

选择:

^{
    id cardPhoneToken;
    if ([tokenData]) {
       cardPhoneToken = [tokenData objectForKey:@"CardPhoneToken"];
    } else {
       cardPhoneToken = @"no Phone Token"; // Or what ever you think is appropriate
    }
    NSString *card = [NSString stringWithFormat:@"%@-%@",
        [[UserAccount sharedInstance] cardNumber],
        cardPhoneToken]; // <<-- No Problem anymore

}
于 2013-01-09T08:34:00.410 回答