繁体   English   中英

如何在NSMutableArray中添加整数值?

[英]How to add an integer value into NSMutableArray?

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);

我想将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

这是输出。

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

我像“69398112”这样的价值观

我该怎么办?

您只能将对象的指针添加到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;

希望这可以帮助。

添加一个数字。

NSNumber* foo = [NSNumber numberWithInteger:42];

或使用盒装文字:

NSNumber* foo = @(42);

然后添加foo。

将Int转换为NSNumber,然后添加到您的数组

问题出在你的NSLog字符串上

NSLog(@"%d", val);

%d实际上是integer (int)的格式说明符。 您正在传递一个NSMutableArray对象。

NSLog更改为

NSLog(@"%@", val);

%@期望一个对象,这通常会打印出[myObject description] ,在这种情况下是对val数组的描述。

这是一个简单的方法: @(yourInt)

int value = 5;
NSMutableArray * anArray  = [[NSMutableArray alloc] init];
[anArray addObject: @(value)];

有关at-compiler-directives的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM