【问题标题】:Moving every object in my array?移动数组中的每个对象?
【发布时间】:2009-07-11 18:54:15
【问题描述】:

我有一个数组和一个计时器,它每 5 秒向我的数组添加一个新对象,但遇到了一个小问题。我有一个可重复调用的代码,它移动我的数组中的对象,但由于某种原因,当一个新对象生成到我的数组中时,前一个生成的对象将停止移动。如何使数组中的每个对象都被调用,而不仅仅是最后生成的对象?

这是我用来移动对象的代码:

for (UIView *astroids in astroidArray) {
    int newX = astroids.center.x + 0;
    int newY = astroids.center.y + 1;
    astroids.center = CGPointMake(newX,newY);
}

编辑:抱歉,这是我的数组代码:

// spawn the astroids every few seconds randomly along the x axis
// and remove them once they get off the screen
if ((gameStarted == YES) && (gameOver == NO)) {
    int randomX = arc4random() % 320;

    astroidArray = [[NSMutableArray alloc] init];

    UIImage *astroid = [UIImage imageNamed:@"astroidwhite.png"];
    UIImageView *astroids = [[UIImageView alloc] initWithImage:astroid];

    //set X and Y of the new imageView
    astroids.center = CGPointMake(randomX , -10);

    //add to array
    [astroidArray addObject:astroids];

    //add to the view, so it gets displayed.
    [self.view addSubview: astroids];
    [astroids release];
}

【问题讨论】:

  • 我认为问题在于如何将“机器人”添加到数组中。你能展示一下代码吗?
  • 我更新了标签,因为这不是 iPhone 特有的,只是 Cocoa 内存管理的问题。还格式化了代码并将编辑包含在问题中。 (请删除下面多余的答案——最好在问题中包含完整的上下文。)最后一个建议:拼写为“asteroid”而不是“astroid”。您选择什么变量名称并不重要,但如果您向用户描述它,请注意拼写错误。 :-)

标签: objective-c cocoa arrays memory-management


【解决方案1】:

看起来你每次分配一个新的小行星时都在分配一个新的数组。然后将新的小行星添加到数组中,因此它是数组中唯一的一颗。

因此,当您遍历阵列时,它上面只有一颗小行星。

更新:

因此,要解决此问题,请分配一次数组(在游戏启动期间?)。不要每次都创建一个新数组。

这部分:

astroidArray = [[NSMutableArray alloc] init];

...应该只发生一次,而不是每次你创造一个新的小行星。

【讨论】:

  • 此外,它在每次通过循环时都会泄漏一个数组。
  • 天哪,谢谢!完美地修复了它,抱歉我对数组很陌生,所以这让我失去了平衡。
  • 没问题,传统上此时您点击绿色复选标记!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 2021-07-25
  • 1970-01-01
相关资源
最近更新 更多