无法从 NSDictionary 获取 int
Can't get int from NSDictionary
我只想从我的 NSDictionary 中获取一个字段。我想获得整数变量,但有些事情很奇怪。
我想给你看一张来自 Xcode 的截图,我在那里得到了变量值。变量 'price' 是整数,应该等于 0,你能帮帮我吗?
我是这样创建这个词典的:
NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"price"]], @"price",
pairedData2, @"uniqueName",
[NSString stringWithFormat:@"0"],@"wasPurchased",
[dictionary objectForKey:@"link"],@"videoLink",
[NSString stringWithFormat:@"%@", [dictionary objectForKey:@"enable"]], @"enable",
nil];
可变价格不能为整数。
NSDictionary 中的每个键和值都必须是一个 NSObject。
因此它可能是一个 NSNumber。检索 NSNumber 值是这样完成的:
NSNumber *number = @(2);
int numberAsInt = number.intValue;
希望对您有所帮助
price
键的值是一个 NSString
值 @"0"
或者它是一个 NSNumber
值 0
.您没有提供足够的信息来判断它是两者中的哪一个。
在你的调试器中,你首先做(我是缩写):
po dict[@"price"]
这给出了预期的正确输出:
0
因为这是 NSNumber
或 NSString
的值。
然后你做:
po dict[@"price"] == 0
你得到:
false
这又是正确的预期结果。你得到 false
因为 dict[@"price"]
的结果是一个非零对象指针,你问的是指针是否是 nil
(== 0
与 == nil
).由于您无法在字典中存储 nil
个对象,因此结果不是 nil
并且报告了 false
。
要查看 NSNumber
或 NSString
的值是否为 0
,您应该这样做:
po dict[@"price"].intValue == 0
你会收到想要的结果:
true
您的最后一次尝试:
po dict[@"price"].intValue
结果:
nil
这又是正确的结果,因为 dict[@"price"].intValue
的值是 0
的 int
值。但是您使用了 po
,这意味着 print object
,因此 0
被解释为 nil
。如果你这样做:
p dict[@"price"].intValue
您将得到想要的结果:
0
使用po
打印对象值。使用 p
打印原始值(例如 int
)。
我只想从我的 NSDictionary 中获取一个字段。我想获得整数变量,但有些事情很奇怪。
我想给你看一张来自 Xcode 的截图,我在那里得到了变量值。变量 'price' 是整数,应该等于 0,你能帮帮我吗?
我是这样创建这个词典的:
NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"price"]], @"price",
pairedData2, @"uniqueName",
[NSString stringWithFormat:@"0"],@"wasPurchased",
[dictionary objectForKey:@"link"],@"videoLink",
[NSString stringWithFormat:@"%@", [dictionary objectForKey:@"enable"]], @"enable",
nil];
可变价格不能为整数。 NSDictionary 中的每个键和值都必须是一个 NSObject。 因此它可能是一个 NSNumber。检索 NSNumber 值是这样完成的:
NSNumber *number = @(2);
int numberAsInt = number.intValue;
希望对您有所帮助
price
键的值是一个 NSString
值 @"0"
或者它是一个 NSNumber
值 0
.您没有提供足够的信息来判断它是两者中的哪一个。
在你的调试器中,你首先做(我是缩写):
po dict[@"price"]
这给出了预期的正确输出:
0
因为这是 NSNumber
或 NSString
的值。
然后你做:
po dict[@"price"] == 0
你得到:
false
这又是正确的预期结果。你得到 false
因为 dict[@"price"]
的结果是一个非零对象指针,你问的是指针是否是 nil
(== 0
与 == nil
).由于您无法在字典中存储 nil
个对象,因此结果不是 nil
并且报告了 false
。
要查看 NSNumber
或 NSString
的值是否为 0
,您应该这样做:
po dict[@"price"].intValue == 0
你会收到想要的结果:
true
您的最后一次尝试:
po dict[@"price"].intValue
结果:
nil
这又是正确的结果,因为 dict[@"price"].intValue
的值是 0
的 int
值。但是您使用了 po
,这意味着 print object
,因此 0
被解释为 nil
。如果你这样做:
p dict[@"price"].intValue
您将得到想要的结果:
0
使用po
打印对象值。使用 p
打印原始值(例如 int
)。