NSDictionary被视为布尔值 - 无法调试

时间:2013-01-09 08:17:22

标签: ios objective-c xcode debugging

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提要nad我的问题是,有一次tokenData中有一次返回{{1而不是0而我无法找出原因。当它以Dictionary返回时,它也被编译器视为布尔值(无法弄清楚为什么)并且我得到错误0

我尝试过做这样的事情 -[NSCFBoolean objectForKey:]: unrecognized selector sent to instance 0x81aa20但当if(!tokenData) { NSLog(@"This is going to crash"); }返回tokenData时,0无法被调用。

esponseDict JSON我得到: if

这就是它崩溃前的样子:{ code = 200; data = { multipass = { CardPhoneBarcodeToken = 562431; CardPhoneToken = 23221; errorMessage = ""; operationResult = 0; }; }; }

更新:如果{ code = 200; data = { multipass = 0; }; }不是tokenData,我已设法采取行动我现在面临NSDictionary的另一个问题部分。如果tokenData不是else,我如何重新加载tokenData?我试着调用* tokenData = [[responseDict objectForKey:@&#34; data&#34;] objectForKey:@&#34; multipass&#34;];在其他内部但我不断获得tokenData = 0 谢谢

2 个答案:

答案 0 :(得分:3)

在解析之前,我会检查tokenData是否为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];

    });
}

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

}