如何在NSMutableArray中添加整数值?

use*_*379 17 iphone objective-c

NSMutableArray * val;
val = [[NSMutableArray alloc] initWithCapacity:15];

/*int outlineWidth = barOutlineWidth;
int outlineHalfWidth = (outlineWidth > 1) ? outlineWidth * 0.5f : 0;
 */
for ( Bar * obj in values )
{  
  // calcualte the bar size
  float value  = [obj value];
  float scale  = ( value / maxValue );

  // shift the bar to the top or bottom of the render line
  int pointY   = lineHeight + ( (lineWidth * 0.5f) * ( ( value >= 0.0f ) ? -1 : 1 ) );
  int barHeight = height * scale;
  NSLog(@"%d", barHeight);   
  CGRect barRect = CGRectMake(pointX, pointY, width, -barHeight);
  [val addObject:[NSNumber numberWithInt:barHeight]];
                     NSLog(@"%d", val);
Run Code Online (Sandbox Code Playgroud)

我想将barheight(int)添加到数组val中.这可能吗?在运行代码时

session started at 2010-09-16 13:21:50 +0530.]
2010-09-16 13:21:53.791 BarGraphSample[3168:20b] 78
2010-09-16 13:21:53.797 BarGraphSample[3168:20b] 69398112
2010-09-16 13:21:53.807 BarGraphSample[3168:20b] 235
2010-09-16 13:21:53.812 BarGraphSample[3168:20b] 69398112
2010-09-16 13:21:53.813 BarGraphSample[3168:20b] 156
2010-09-16 13:21:53.814 BarGraphSample[3168:20b] 69398112
Run Code Online (Sandbox Code Playgroud)

这是输出.

这里的实际高度为78,235,156,同时打印数组val.

我像"69398112"这样的价值观

我该怎么办?

Gre*_*ton 50

您只能将对象的指针添加到NSMutableArray.如果您使用NSNumber该类来包装整数,则应该能够将其添加到数组中.

int x = 10;
NSNumber* xWrapped = [NSNumber numberWithInt:x];
NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:15];
[array addObject:xWrapped];
int xOut = [[array lastObject] intValue]; //xOut == x;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


jer*_*jer 19

添加一个数字.

NSNumber* foo = [NSNumber numberWithInteger:42];
Run Code Online (Sandbox Code Playgroud)

或使用盒装文字:

NSNumber* foo = @(42);
Run Code Online (Sandbox Code Playgroud)

然后添加foo.