内在弱参照与非内在弱参照?

时间:2013-01-28 16:34:38

标签: ios objective-c cocos2d-iphone

@interface ....
/* will be the next 'runningScene' in the next frame
     nextScene is a weak reference. */
    CCScene *nextScene_;
@end
@implementation .......
-(void) replaceScene: (CCScene*) scene
{
    NSAssert( scene != nil, @"Argument must be non-nil");

    NSUInteger index = [scenesStack_ count];

    sendCleanupToScene_ = YES;
    [scenesStack_ replaceObjectAtIndex:index-1 withObject:scene];
    nextScene_ = scene; // nextScene_ is a weak ref
}

- (void) pushScene: (CCScene*) scene
{
    NSAssert( scene != nil, @"Argument must be non-nil");

    sendCleanupToScene_ = NO;

    [scenesStack_ addObject: scene];
    nextScene_ = scene; // nextScene_ is a weak ref
}
@end

那些日子我在ubuntu(名为cocostep)上移植了一个cocos2d很有趣。当我深入研究“CCdirector.m”的cocos2d源代码时,我发现了一些有趣的东西,观察了几个评论点“它是弱引用”。因为我对objective-c,ios,osx的了解。一个ref是弱的,必须在__weak关键字之前,但我并没有围绕整个项目做任何事情。所以我想这是一个非内在的弱参考,只是cocos2d设计师的策略。根据我的假设。如果某个变量作为弱引用(非内在)得到释放调用,并在其他地方释放其内存,那么对此引用的后续调用将失败,甚至崩溃,因为引用的值不是nil而是对该内存的无效引用。为了正确使用策略,必须手动将该变量重置为nil。我的推测是对的吗?

2 个答案:

答案 0 :(得分:1)

Cocos2d不使用ARC。注释中标记为弱的任何引用都是非保留引用。这意味着如果引用被取消分配并且未手动设置为nil,则引用可能指向无效内存。

答案 1 :(得分:1)

你的推测是正确的。

Cocos2d不使用ARC,所以当他们说weak时,它不是weak在正确的ARC意义上。

这些变量的正确术语是unsafe_unretained,这意味着不保留不会自动无效。

这些变量可能是悬空指针,因此你最好照顾它并尽快手动使它们无效。

相关问题