Objective-c数组在删除时不释放对象

时间:2012-05-04 18:58:33

标签: objective-c

// AClass.m
// init
enemyBullets = [[NSMutableArray alloc] initWithCapacity:0];
enemy1 = [[Enemy alloc] initWithBullets:enemyBullets];

// At some point
NSMutableArray *bulletsToDelete = [NSMutableArray array];
for(BulletEnemy *thisBullet in enemyBullets)
{
    // If I have to delete
    [bulletsToDelete addObject: thisBullet];
}
[enemyBullets removeObjectsInArray:bulletsToDelete];

//dealloc method
[enemyBullets release];
[enemy1 release];

现在在敌人的某个时间点,我会做以下事情:

// Enemy.m
- (id)initWithBullets:(NSMutableArray*) _bullets{
     // Enemybullets is a var of Enemy
     enemyBullets = _bullets;
}

// At some point...
myBullet = [[BulletEnemy alloc] init];
[enemyBullets addObject:myBullet];
[myBullet release];

问题是当我在Aclass执行以下操作时:

[enemyBullets removeObjectsInArray:bulletsToDelete];

BulletEnemy中的dealloc方法没有被调用,因为保留计数不是0.为什么?但是,如果我释放ACLass(释放enemyBullets),那么我的子弹将被解除分配。

2 个答案:

答案 0 :(得分:0)

让敌人拥有敌人的阵营。并使用reverseObjectEnumerator

// AClass.m
// init
enemy1 = [[Enemy alloc] init];

// At some point
for(BulletEnemy *thisBullet in enemy1.enemyBullets.reverseObjectEnumerator)
{
    // If I have to delete
    [enemy1.enemyBullets removeObject:thisBullet];
}

//dealloc method
[enemy1 release];

//Enemy.h
@property (retain) NSMutableArray* enemyBullets;


// Enemy.m
@synthesize enemyBullets = _enemyBullets;

- (id)init{
     // Enemybullets is a var of Enemy
     _enemyBullets = [[NSMutableArray alloc] init];
}

// At some point...
myBullet = [[BulletEnemy alloc] init];
[enemyBullets addObject:myBullet];
[myBullet release];

-(void) dealloc{
    [_enemyBullets release];
}

答案 1 :(得分:0)

显然,我正在使用retain属性签名,这使得对象+1因此不会解除分配。刚改变了分配并且它有效。