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

从昨天开始我一直在与这一行代码进行斗争。我从服务器nad获取JSON提要。我的问题是,十个tokenData中有一次返回0而不是Dictionary,我不知道为什么。当它返回为0时,编译器也将其视为布尔值(无法找出原因之一),并且我收到了-[NSCFBoolean objectForKey:]: unrecognized selector sent to instance 0x81aa20错误

我试图做这样的事情if(!tokenData) { NSLog(@"This is going to crash"); }但是当tokenData返回0时,不会调用if

我得到esponseDict JSON:{ code = 200; data = { multipass = { CardPhoneBarcodeToken = 562431; CardPhoneToken = 23221; errorMessage = ""; operationResult = 0; }; };}
这是崩溃前的样子:{ code = 200; data = { multipass = 0; }; }
更新:如果tokenData不是NSDictionary,我已经设法采取了措施,现在我在else部分遇到了另一个问题。如果不是NSDictionary,如何重新加载tokenData?我尝试调用* tokenData = [[responseDict objectForKey:@“data”] objectForKey:@“multipass”];在else里面,但我一直在获取tokenData = 0
谢谢

最佳答案

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

    });
}

10-05 20:21