【问题标题】:Retrieving "int" from NSMutableArray?从 NSMutableArray 中检索“int”?
【发布时间】:2012-04-21 00:08:29
【问题描述】:

我正在读取一些 json 输出...只是一些整数。第一个 NSLog 完美地输出了东西。在这种情况下,有 3 个元素。我不明白如何访问我猜的特定元素。

NSMutableArray *json = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:data   options:kNilOptions error:&error];

NSLog(@"json: %@ \n",json);

int count = (int)[json objectAtIndex:0];
int count1 = (int)[json objectAtIndex:1];
int count2 = (int)[json objectAtIndex:2];
NSLog(@"count %i %i %i\n",count,count1,count2);

【问题讨论】:

  • 如果 id 声明了方法 -intValue,为什么要转换为 int?

标签: objective-c nsmutablearray int


【解决方案1】:

这些很可能是 NSNumber。试试这个:

int count = [[json objectAtIndex:0] intValue];
int count1 = [[json objectAtIndex:1] intValue];
int count2 = [[json objectAtIndex:2] intValue];
NSLog(@"count %i %i %i\n",count,count1,count2);

【讨论】:

    【解决方案2】:

    NSArray 包含一个对象,您不应该将其转换为 int,这将不起作用。查看您的代码并确定NSJSONSerialization 的输出。如果是整数,一般是NSNumber的实例,所以试试:

    int count = [[json objectAtIndex:0] intValue];
    

    【讨论】:

      【解决方案3】:

      NSArrayNSMutableArray 不能使用 ints 和其他非 id 对象作为键或值,因此强制转换不起作用。这些值很可能是NSNumber 类型,因此您需要对它们调用intValue

      int count = [[json objectAtIndex:0] intValue];
      int count1 = [[json objectAtIndex:1] intValue];
      int count2 = [[json objectAtIndex:2] intValue];
      

      【讨论】:

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