// 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),那么我的子弹就会被释放。