首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将整数值添加到NSMutableArray中?

如何将整数值添加到NSMutableArray中?
EN

Stack Overflow用户
提问于 2010-09-16 15:58:55
回答 5查看 55.5K关注 0票数 19
代码语言:javascript
复制
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中。这个是可能的吗?在运行代码时,

代码语言:javascript
复制
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

这是输出。

在这里,当打印数组val时,实际的barheight是78,235,156。

我越来越喜欢像"69398112“这样的值了

我该怎么办?

EN

回答 5

Stack Overflow用户

发布于 2010-09-16 16:04:07

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

代码语言:javascript
复制
int x = 10;
NSNumber* xWrapped = [NSNumber numberWithInt:x];
NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:15];
[array addObject:xWrapped];
int xOut = [[array lastObject] intValue]; //xOut == x;

希望这能有所帮助。

票数 50
EN

Stack Overflow用户

发布于 2010-09-16 16:02:08

改为添加一个数字。

代码语言:javascript
复制
NSNumber* foo = [NSNumber numberWithInteger:42];

或者使用盒装文字:

代码语言:javascript
复制
NSNumber* foo = @(42);

然后添加foo。

票数 20
EN

Stack Overflow用户

发布于 2010-09-17 23:09:10

问题出在NSLog字符串上,即

代码语言:javascript
复制
NSLog(@"%d", val);

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

NSLog更改为

代码语言:javascript
复制
NSLog(@"%@", val);

%@需要一个对象,这通常会打印出[myObject description],在本例中是val数组的描述。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3724757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档