我有一个问题,从数组中删除项目..
第一: 我有一个int类型的变量,称为zan。在我的HelloWordScene.h中
int zan;
NSMutableArray * targets;
NSMutableArray *projectiles;
在我的HelloWordScene.m中。我有一个动画的对象:
-(id) init {
if((self = [super init])) {
[self schedule:@selector(update:)];
_targets = [[NSMutableArray alloc] init];
_projectiles = [[NSMutableArray alloc] init];
}
[self schedule:@selector(gameLogic:) interval:3];
return self;
}
在我的选择器中我增加了var:
-(void)gameLogic:(ccTime)dt {
[self addTarget];
zan ++;
}
后来我有一个动画,我有一个addTarget:
// This loads an image of the same name (but ending in png), and goes through the
// plist to add definitions of each frame to the cache.
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"zancudo.plist"];
// Create a sprite sheet with the images
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"zancudo.png"];
[self addChild:spriteSheet];
// Load up the frames of our animation
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 0; i <= 4; ++i) {
[walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"zancu000%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];
// Create a sprite for our bear
CGSize winSize = [CCDirector sharedDirector].winSize;
self.bear = [CCSprite spriteWithSpriteFrameName:@"zancu0001.png"];
//random position
int minY = _bear.contentSize.width/2;
int maxY = winSize.width - _bear.contentSize.width/2;
int rangeY = maxY - minY;
int actualX = (arc4random() % rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
_bear.position = ccp(actualX,winSize.height + (_bear.contentSize.height/2));
self.walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
//animation
[spriteSheet addChild:_bear];
//∫aqui pasar un for para poder saber que position es
CCLOG(@"cantidad de zancudos%d",zan);
[_targets insertObject:_bear atIndex:zan];
我删除了索引的可变_target-我有一个选择器更新。尝试删除一个mutablearray。
for (CCSprite *target in targetsToDelete) {
if (_targets.count!=0) {
for (int j=1; j==_targets.count; j++) {
[_targets removeObjectAtIndex:j];
}
}
我需要帮助
答案 0 :(得分:0)
你的循环将尝试从数组的边界中访问索引...试试这个
for (int j = 0; j == _targets.count - 1; j++)
{
[_targets removeObjectAtIndex:j];
}
但是,由于看起来您只是使用此代码删除数组的最后一个元素,因此可以跳过for循环并使用:
[_targets removeLastObject];
答案 1 :(得分:0)
从_targets中删除对象的那一刻,有效计数实际上会发生变化。因此,如果您以10为计数启动循环,并且最终j的值将超出范围。我没有完全遵循你的if(==)的逻辑,但如果你试图删除所有对象,而不是循环:
[_targets removeAllObjects];
答案 2 :(得分:0)
使用这样的语法进行无崩溃删除;
NSArray *array = [NSArray arrayWithArray: _targets];
for(CCSprite *sprite in array)
{
if(sprite.tag == kToDelete) //mark somewhere in game :or use ur logic here
{
[_targets removeObject: sprite];
[sprite stopAllActions];
[sprite removeFromParentAndCleanup:YES];
}
}