有条件分配/释放? [Objective-c 和 Cocos2D]
如果我想在另一个类中分配一个类并且我想轻松地引用它,但有时不需要分配该类,因此不需要释放该类,该怎么办?这是怎么做到的?我可以在 dealloc 中放置一个条件,这样就不必释放它吗?
更详细地说,我正在使用 Cocos2D。我有可能需要也可能不需要分配的玩家能力类别。在我的 init 中:
// Abilities
if(abilityRushH == 0){
objects = [theMap objectGroupNamed:@"oj"];
startPoint = [objects objectNamed:@"item_ability_rushH"];
x = [[startPoint valueForKey:@"x"] intValue];
y = [[startPoint valueForKey:@"y"] intValue];
rushH = [[RushHorizontal alloc] init];
[self addChild:rushH.rushHSpriteSheet];
rushH.rushHSprite.position = ccp(x,y);
}
if(abilityRushV == 0){
objects = [theMap objectGroupNamed:@"oj"];
startPoint = [objects objectNamed:@"item_ability_rushV"];
x = [[startPoint valueForKey:@"x"] intValue];
y = [[startPoint valueForKey:@"y"] intValue];
rushV = [[RushVertical alloc] init];
[self addChild:rushV.rushVSpriteSheet];
rushV.rushVSprite.position = ccp(x,y);
}
Cocos2D 需要保留引用,以便它可以随地图滚动。但如果我不分配它,我如何才能不释放呢?
What if I want to alloc a class inside another and I want to reference it easily, but sometimes this class would not need to be alloc'd, therefore not dealloc'd. How is this done? Can I put a conditional inside dealloc so it doesn't have to be released?
In more detail, I'm using Cocos2D. I have player ability classes that may or may not need to be allocated. In my init:
// Abilities
if(abilityRushH == 0){
objects = [theMap objectGroupNamed:@"oj"];
startPoint = [objects objectNamed:@"item_ability_rushH"];
x = [[startPoint valueForKey:@"x"] intValue];
y = [[startPoint valueForKey:@"y"] intValue];
rushH = [[RushHorizontal alloc] init];
[self addChild:rushH.rushHSpriteSheet];
rushH.rushHSprite.position = ccp(x,y);
}
if(abilityRushV == 0){
objects = [theMap objectGroupNamed:@"oj"];
startPoint = [objects objectNamed:@"item_ability_rushV"];
x = [[startPoint valueForKey:@"x"] intValue];
y = [[startPoint valueForKey:@"y"] intValue];
rushV = [[RushVertical alloc] init];
[self addChild:rushV.rushVSpriteSheet];
rushV.rushVSprite.position = ccp(x,y);
}
Cocos2D needs to keep the reference so it can scroll with the map. But if I'm not alloc'ing it, how do I NOT dealloc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您正在谈论在dealloc中释放它,因此将有一个实例变量。现在,当分配 Objective-C 类的任何实例时,其所有对象都为 nil,并且 c 类型被设置为 0(或等效值)。因此,如果您的类的对象未实例化,则无需付出任何额外的努力,因为实例变量在
dealloc
处将为nil
,因此release发送给它的
消息将不起作用。Since you are talking of releasing it in
dealloc
, there will be an instance variable for this. Now when any instance of an Objective-C class is allocated, all its objects arenil
and c types are set to 0 (or equivalent values). So you don't need to put any extra effort if the object of your class isn't instantiated as the instance variable will benil
atdealloc
and sorelease
message sent to it will have no effect.确保可选变量在不需要时为 nil,并在释放之前进行 nil 检查。
Make sure the optional variable is nil when its not needed, and do a nil check before dealloc'ing.