【问题标题】:objective c arrays of floats and booleans possible?可能的浮点数和布尔值的目标 c 数组?
【发布时间】:2011-03-20 13:21:28
【问题描述】:
NSArray chemConstantArray = [[NSArray alloc] initWithObjects:0.0021400, 0.0012840, 0.0010700, nil];

给我四个错误:

Incompatible type for argument 1 of 'initWithObjects:'

Invalid initializer

Statically allocated instance of Objective-C class 'NSArray' x 2

这是有道理的,因为浮点数不是对象,但我怎样才能制作一组浮点数。我也需要一个用于 BOOL 的。

【问题讨论】:

标签: iphone objective-c arrays floating-point boolean


【解决方案1】:

如果您只需要在自己的代码中使用数组,则可以使用常规 C 数组:

float chemConstantArray[] = {0.0021400, 0.0012840, 0.0010700};

如果您需要 NSArray* 来做某事,您需要将每个值包装到 NSNumber 中。

NSArray *chemConstantArray = [[NSArray alloc] initWithObjects:
    [NSNumber numberWithFloat: 0.0021400],
    [NSNumber numberWithFloat: 0.0012840],
    [NSNumber numberWithFloat: 0.0010700],
    nil];

您可以将numberWithBool 类似地用于 BOOL。

【讨论】:

  • 谢谢 - 我使用了你建议的 C 数组,并通过引用 chemConstant[i] 来使用它,其中 i 是我的 for loop 中的索引,用于构建我的 Chemical 对象。
【解决方案2】:

你想要NSNumber,它可以保存浮点数、整数等。

【讨论】:

    猜你喜欢
    • 2020-03-16
    • 2016-12-08
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 2018-04-15
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多