ios - 无法从 NSDictionary 获取 int

标签 ios objective-c nsdictionary

我只想从我的 NSDictionary 中获取一个字段。我想获得整数变量,但有些事情很奇怪。

我想给你看一张 Xcode 的截图,我在那里得到了变量值。变量“价格”是整数,应该等于 0,你能帮帮我吗?

enter image description here

我以这种方式创建这个词典:

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];

最佳答案

price 键的值要么是一个 NSString,其值为 @"0",要么是一个 NSNumber 的值为 0。您没有提供足够的信息来判断它是两者中的哪一个。

在你的调试器中,你首先要做的(我是缩写):

po dict[@"price"]

这给出了预期和正确的输出:

0

因为这是 NSNumberNSString 的值。

然后你做:

po dict[@"price"] == 0

你得到:

false

这又是正确的预期结果。你得到 false 因为 dict[@"price"] 的结果是一个非 nil 对象指针,而你问的是指针是否为 nil(== 0== nil 相同)。由于您不能在字典中存储 nil 对象,因此结果不是 nil 并报告 false

要查看 NSNumberNSString 的值是否为 0,您应该这样做:

po dict[@"price"].intValue == 0

您将收到以下期望结果:

true

您的最后一次尝试:

po dict[@"price"].intValue

结果:

nil

这又是正确的结果,因为 dict[@"price"].intValue 的值是 0int 值。但是您使用了 po,这意味着 print object 因此 0 被解释为 nil。如果你这样做:

p dict[@"price"].intValue

你会得到想要的结果:

0

使用po 打印对象值。使用 p 打印原始值(例如 int)。

关于ios - 无法从 NSDictionary 获取 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502744/

相关文章:

objective-c - AVAudioPlayer 阻塞和 iOS 5 问题

ios - 从现有的 tableView 数据源和 Controller 创建一个 collectionView

ios - 创建 JSON 字符串 - iOS

ios - 如何在后台更新 MPNowPlayingInfoCenter 以及 AVQueuePlayer 中的轨道发生变化

android - 将我的应用添加为 Youtube 应用中的共享选项

ios - 如何在发布数据iOS objective-c 中将图像附件发送到服务器

iphone - 无法在 UITableViewCell 中设置自定义背景颜色

iOS 需要很长时间才能在 HTTP 请求后更新 View ?

ios - 清除 NSDictionary 中的数组

swift - 取消归档 Swift 词典时的 EXC_BAD_INSTRUCTION