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

4

2 回答 2

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];
}
于 2012-05-04T19:14:17.160 回答
0

显然,我用保留属性分配了一些东西,这使得对象 +1 因此不会释放。只需更改要分配的属性,它就可以工作。

于 2012-10-29T14:22:24.003 回答