我试图检查objectForKey的返回值是否为NULL
if([[fbResult objectForKey:@"current_location"]objectForKey:@"country"])
formViewController.country=[[fbResult objectForKey:@"current_location"]objectForKey:@"country"];
但我在第一行有错误
更新
fbResult是一个JSON字符串,如果用户在facebook中将他的城市及其国家/地区列入其中,那么它就像:
"birthday_date" = "07/*****9";
"contact_email" = "***mehdi@hotmail.fr";
"current_location" = {
city = Tunis;
country = Tunisia;
id = 11166369***;
name = "Tunis, Tunisia";
state = Qabis;
zip = "";
};
locale = "fr_FR";
name = "Mehdi ****el";
pic = "https://fbcdn-profile-a.akamaihd.net/hprofile-********_s.jpg";
sex = male;
uid = 530****;
}
如果用户没有把他的国家和城市看起来像:
{ "birthday_date" = "02/*3/19**";
"contact_email" = "kev**kevin@gmail.com";
"current_location" = "<null>";
locale = "fr_FR";
name = "Aude ***";
pic = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/4***2_**8_1112_s.jpg";
sex = female;
uid = 11***04*;
}
错误是
- [NSObject(NSObject)doesNotRecognizeSelector:] + 96
答案 0 :(得分:8)
检查字典中是否存在嵌套在另一个字典中的对象不会捕获所有出现的错误数据。
使您的代码更加稳固
id current_location = [fbResult objectForKey:@"current_location"];
if (current_location != nil && [current_location class] != [NSNull class]) {
id country = [current_location objectForKey:@"country"];
if (country != nil) {
formViewController.country= country;
} else {
// current_location has no country
}
} else {
// fbResult has no current_location
}
如果current_location应该是字典,您可以用id currentLocation
替换NSDictionary * currentLocation
,您的current_location可能是NSNull
您可以使用
进行检查[yourObject class]!= [NSNull class]