objective-c - NSMutableArray 的 Sprite ,内存问题?

标签 objective-c ios cocoa-touch nsmutablearray cocos2d-iphone

我有一个包含十个 Sprite 的数组;它们都位于屏幕的同一区域 为了便于解释,我会说在底部中间,一个叠放。我需要做的是取出顶部 Sprite 并通过向前滑动(从下到上)将其从屏幕上扔掉。当我有一个 Sprite 时,我对此没有任何问题;当我有多个 Sprite 时,我就有问题了。我将项目添加到图层中,如下所示:

for(int i=0; i<maxCount; i++){
    CCSprite *x = [listOfItems objectAtIndex:i];

    //NSLog(@"(%f, %f)", x.position.x, x.position.y);

    [self addChild:x];
}

它们是在上述步骤中创建的:
for (int i=0; i<maxCount; i++) {
    CCSprite *o = [CCSprite spriteWithFile:@"image.png"];
    o.position = ccp(windowSize.width/2,windowSize.width/2);

    [listOfItems addObject:o];

    [o release];
}

我想真正的问题是我不知道如何处理
“当前”顶部。因此,如果我将数组索引 0 作为顶部,我可以继续使用触摸手势并将其“轻弹”出屏幕。第一个可以正常工作,但是一旦我触摸第二个,它就会因 EXC_BAD_ACCESS 而崩溃。这是 TouchesBegan 方法:
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    startingPoint = location;

    //Trying something here....
    //if(current)
    //    [current release];

    current = [listOfItems objectAtIndex:currentPosition];
    [self reorderChild:current z:2];

    actionStartTime = [NSDate timeIntervalSinceReferenceDate];
}

当“在这里尝试一些东西...”行未注释时,这就是崩溃发生的地方,而当它们被注释掉时,它会在分配 current 时发生.我知道我在这里遗漏了一些东西,但我就是想不通。

最佳答案

如果您的对象都添加到数组中,我发现最简单的方法是为每个对象设置不同的标签。

for(int i = 0; i < NUMOFOBJECTS; i++)
{
    CCSprite *sprite = blah blah whatever;

    // I do something like 100+i so that each time I want to
    // create different types of objects I can subtract the "100"
    // or whatever it is to get a base index value for arrays.
    sprite.tag = 100+i;
}

在您的 CCTouchesBegan 内部,您检查触摸以确保它在项目上,然后您在那里迭代您的项目并仅移动具有正确标签的项目。
for(CCSprite *sprite in objects)
{
     if(sprite.tag - 100 == [objectOrderList objectAtIndex:0].tag)
     {
          // Do whatever
     }
}

将其视为伪代码,因为我只是在脑海中写下。在这种情况下,您将跟踪 NSMutableArray 中的对象顺序,每当顺序更改时删除/替换/添加对象。

关于objective-c - NSMutableArray 的 Sprite ,内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6338478/

相关文章:

ios - 为什么我的 UIScrollView 中的 UIView 不滚动?

ios - 防止 UITableView contentInset 属性影响其 backgroundView?

ios - NSData 与归档

iphone - 设置样式分组表

iphone - 核心数据 : Fetch result from multiple entities or relationship

iphone - 仅在首次打开应用程序时打开的透明覆盖 View

ios - ScrollView -> View (Label + Label + TableView) 和自动布局

objective-c - Objective C 中的舍入时间

ios - 无法使用 ScrollView for IOS 水平滚动

ios - 如何从 NSMutableArray 动态创建 uilabel?