【问题标题】:Objective-C, unsigned long _NullableObjective-C,无符号长 _Nullable
【发布时间】:2020-02-23 09:41:11
【问题描述】:

我在编译代码时收到警告,但不知道如何解决。

警告:不兼容的整数到指针转换初始化 'unsigned long *' 带有 'unsigned long 类型的表达式 _Nullable'

NSDictionary *dict = @{@"foo": @420};
unsigned long *num = [[dict objectForKey:@"foo"] unsignedLongValue];
NSString *oct = [NSString stringWithFormat:@"%o", num];
NSLog(@"%04u", [oct intValue]); // 0644

输出是正确的(我正在将数字转换为八进制格式),但我猜我的代码与编译器不符。

【问题讨论】:

    标签: objective-c integer clang


    【解决方案1】:

    这里有两个错误 -

    1) unsigned long 不是对象而是原始的。 您只需删除 num 之前的“*”,如下所示 -

    unsigned long num = [[dict objectForKey:@"foo"] unsignedLongValue];
    

    2) unsigned long 的格式是 %lu 而不是你提到的 %o 。

    NSString *oct = [NSString stringWithFormat:@"%lu", num];
    

    所以,正确的代码应该是 -

    NSDictionary *dict = @{@"foo": @420};
    unsigned long num = [[dict objectForKey:@"foo"] unsignedLongValue];
    NSString *oct = [NSString stringWithFormat:@"%lu", num];
    NSLog(@"%04u", [oct intValue]); // 0644
    

    【讨论】:

      【解决方案2】:

      我相信这应该可行(警告消失了):

      unsigned long num = (unsigned long)[[dict objectForKey:@"foo"] unsignedLongValue];
      NSString *oct = [NSString stringWithFormat:@"%lo", num];
      

      【讨论】:

      • (unsigned long) 不是必需的。
      猜你喜欢
      • 2011-10-26
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      相关资源
      最近更新 更多