我需要向 nsmutablearray 添加一个 double 组(如 double 示例 [number of capacity];),但它似乎比我想象的要难。所以我有:
NSMutableArray *sample;
double ex[2];
作为我的 .m 文件中的全局变量
在 void 方法中,我正在尝试使用两个双参数 example1 和 example2
ex[0] = example1;
ex[1] = example2;
然后将这个 ex 数组添加到 nsmutablearray,但是,如果我这样做,我会收到错误消息:
[sample addObject:ex];
有人请帮助,我也是这个新手所以我不太清楚如何。提前致谢!
我觉得我没有把自己解释得那么清楚,所以我会添加这个。
So basically, I want my mutablearray to look like this:
[[3.78,2.00], [4.6,8.90098], [67.9099, 56.788] ...]
like that
最佳答案
除了 Dasblinkenlight 的回答,您还可以使用 NSNumbers 的 NSArray 并将其添加到您的 NSMutableArray。
double example1 = 1.113;
double example2 = 129.74;
NSMutableArray *sample = [[NSMutableArray alloc] init];
NSArray *ex = @[[NSNumber numberWithDouble: example1], [NSNumber numberWithDouble: example2]];
[sample addObject: ex];
NSLog(@"example1: %f, example2: %f", ((NSNumber*)sample[0][0]).doubleValue, ((NSNumber*)sample[0][1]).doubleValue);
//logs example1: 1.113000, example2: 129.740000
您可以根据需要添加任意数量的 NSNumber NSArray,并使用 sample[][]
获取 NSNumber,然后使用 doubleValue
轻松解包。
如果您希望两个维度都是可变的,只需将 NSNumber 放在可变数组中即可。
改变这个:
NSArray *ex = @[[NSNumber numberWithDouble: example1], [NSNumber numberWithDouble: example2]];
为此:
NSMutableArray* ex = [NSMutableArray arrayWithObjects: [NSNumber numberWithDouble: example1], [NSNumber numberWithDouble: example2], nil];
关于ios - 将双数组添加到 nsmutablearray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643573/