我有a small iPhone app ,它从社交网络中获取用户信息(姓名、城市、性别),然后将其显示在 View 中:
数据以 JSON 格式到达(请注意男性用户的 sex = 0
):
2014-01-22 21:18:42.915 oauthMailru[697:1303] json=(
{
age = 41;
"app_installed" = 1;
birthday = "08.06.1972";
"first_name" = Alexander;
"friends_count" = 17;
"has_pic" = 1;
"is_friend" = 0;
"is_online" = 0;
"is_verified" = 1;
"last_name" = Farber;
"last_visit" = 1390312557;
link = "http://my.mail.ru/mail/farber72/";
location = {
city = {
id = 855;
name = "Dusseldorf";
};
country = {
id = 46;
name = "Germany";
};
};
nick = "Alexander Farber";
pic = "http://avt.appsmail.ru/mail/farber72/_avatar";
"pic_big" = "http://avt.appsmail.ru/mail/farber72/_avatarbig";
"pic_small" = "http://avt.appsmail.ru/mail/farber72/_avatarsmall";
"referer_id" = "";
"referer_type" = "";
sex = 0;
"show_age" = 1;
uid = 17880121030128875114;
vip = 0;
}
)
然后我将其打印在我的 DetailViewController.m 中:
2014-01-22 21:18:42.920 oauthMailru[697:70b] id: 17880121030128875114
2014-01-22 21:18:42.920 oauthMailru[697:70b] first_name: Alexander
2014-01-22 21:18:42.921 oauthMailru[697:70b] last_name: Farber
2014-01-22 21:18:42.921 oauthMailru[697:70b] city: Dusseldorf
2014-01-22 21:18:42.921 oauthMailru[697:70b] female: 1
2014-01-22 21:18:42.922 oauthMailru[697:70b] avatar: http://avt.appsmail.ru/mail/farber72/_avatarbig
我解析 JSON 输入的代码在 ViewController.m 中并将其分配给 User.h属性:
NSDictionary *dict = json[0];
_user = [[User alloc] init];
_user.userId = dict[@"uid"];
_user.firstName = dict[@"first_name"];
_user.lastName = dict[@"last_name"];
_user.city = dict[@"location"][@"city"][@"name"];
_user.avatar = dict[@"pic_big"];
_user.female = !(BOOL)dict[@"sex"];
出于某种原因,最后一个用户属性 - BOOL female
对我来说总是设置错误。
我已经尝试了以下但没有成功:
_user.female = !(BOOL)dict[@"sex"];
_user.female = (0 != dict[@"sex"]);
_user.female = (int)dict[@"sex"];
谁能告诉我,如何在此处正确地将 id
转换为 BOOL
?
最佳答案
您不能将对象转换为 Objective C 中的原语(id
是对象指针)。假设您的 JSON 解析器将数字解析为 NSNumbers,您只需要这样做:
![dict[@"sex"] boolValue]
关于ios - 将 JSON 中的 "sex = 0"转换为 BOOL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293353/