【问题标题】:Adding the integer 0 as a value of key in NSDictionary在 NSDictionary 中添加整数 0 作为键的值
【发布时间】:2015-05-01 02:51:00
【问题描述】:

我正在创建字典NSMutableDictionary* parameters = [[NSMutableDictionary alloc] init]; 并希望将 0 作为有效整数值分配给它,如下所示:parameters[@"size"] = 0; 但由于 nil/NULL 的值为 0,我收到以下警告:"Value stored into 'NSMutableDictionary' cannot be nil"

我该如何解决这个问题?

【问题讨论】:

  • 尝试@0 而不是0
  • @godel9 谢谢,@ 不在字符串之前是什么意思?它还有哪些其他实现方式
  • @liva @ 表示编译器会将0 转换为代表0NSNumber 对象,允许将其存储在数组和字典中。这与@"Hello" 在编译时变成NSString 相同。关于对象文字有一个很好的部分on NSHipster
  • 该值必须是一个对象。您不能使用裸整数值,无论是零还是 837450126。请使用 NSNumber 或 NSString。

标签: objective-c integer nsmutabledictionary null


【解决方案1】:

您可以将整数包装为NSNumber@(0)(或[NSNumber numberWithInteger:0])。这会将您的整数值转换为可以添加到 NSMutableDictionary 或任何其他集合的对象。

在进行比较之前,请确保使用 NSInteger value = [wrappedNumber integerValue] 解开字典值。

【讨论】:

  • 数字文字不需要括号——如果是数字表达式,该语法。 @0 就足够了。
【解决方案2】:

免责声明:我个人认为括号括起来的数字更容易阅读,尽管它是可选的

NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

parameters[@"size"] = @(0);
NSInteger sizeInt = [parameters[@"size"] integerValue];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多