0

也许我工作时间太长了,但有这个问题......让我们抽象一下,真名并不重要。

我有 20 多个类继承自它的超类 Car

@interface Car : NSObject;
@interface Volvo : Car;
@interface BMW : Car; etc...

在我的游戏课上,我有沃尔沃、宝马的财产

@property (nonatomic, strong) Volvo *volvo;
@property (nonatomic, strong) BMW *bmw;
@property (nonatomic, strong) Car *activeCar;

我动态创建这些对象并将activeCar存储在属性activeCar中

_bmw = [[BMW alloc] init];    
_activeCar = _bmw;

现在在重新启动方法中,我希望能够 nil active car,但即使在日志中我看到两者都指向同一个地址,它也不是 wokring:

_activeCar = nil; // dealloc on BMW and Car is not called
// _bmw = nil; // dealloc is called properly on BMW and Car class

怎么能管得住?这是唯一的解决方案吗?

if ([_activeGame isKindOfClass:[BMW class]])
_bmw = nil;
4

2 回答 2

2

If you want to destroy the BMW when you destroy the activeCar, then there's no sense in keeping BMW around as an ivar anyway.

_activeCar = [[BMW alloc] init];

Your current implementation wont nil out the BMW because self.bmw still has a reference to it.

于 2013-07-10T21:28:32.023 回答
2

activeCar实际上总是保留两次,因为您有 2 个strong属性引用它。因此,您可以将 设为 nil activeCar,但仍会设置其他属性。

如果您不想在汽车变成 后将其设置为 ,activeCar那么您可以在将其设置为 后直接将其他参考设为activeCar

于 2013-07-10T21:23:29.027 回答