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
谢谢
答案 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
}