引用计数为0时,对象仍然可用

时间:2013-12-22 04:01:54

标签: objective-c

很抱歉,如果这是一个重复的条目,我是OC的新手 我在构建设置中关闭了“Object-C自动引用计数”。我有两个班GuitarGuitarController GuitarController.m看起来像这样:

#import "GuitarController.h"

@implementation GuitarController

-(void) setGuitar:(Guitar*) newGuitar
{
    guitar = newGuitar; 
    // Yes, i did not retain the guitar object. 
    // I did it on purpose to test whether something will go wrong
}

-(void) playGuitar
{
    [guitar play];
}
@end

Guitar.m看起来像这样:

#import "Guitar.h"

@implementation Guitar
-(void) play
{
    NSLog(@"play guitar!!!");
}
@end

最后,main.m代码:

#import <Foundation/Foundation.h>
#import "GuitarController.h"

int main(int argc, const char * argv[])
{
    Guitar* guitar = [[Guitar alloc] init];
    GuitarController* guitarController = [[GuitarController alloc] init];
    [guitarController setGuitar:guitar];
    [guitar release]; 
    [guitarController playGuitar]; // Expecting an error here
    return 0;
}

上面的代码工作得很好。但这显然是错误的,因为我在引用计数变为0后引用了一个对象。任何线索?谢谢!

1 个答案:

答案 0 :(得分:3)

吉他很可能尚未返回操作系统。那很正常。实内存分配很昂贵。 Cocoa尽可能避免它们。对于这样一个小小的对象,Cocoa几乎可以肯定只是将它放在私有池中以便稍后再分配。这意味着您的应用程序仍然在技术上拥有内存,因此访问它是完全合法的,并且您不会得到例外。有关详细信息,请参阅A look at how malloc works on the Mac

释放内存后访问内存是未定义的行为。在你这样做之后你不能“期待”任何事情。计算机可以着火,这将在规范中考虑。该计划也可以继续完美地运作。这也符合规范。系统不会保证您会收到错误。

我希望您关闭ARC只是为了尝试更多地了解底层系统。如果是这样,那没关系。但对于任何严肃的计划you should turn on ARC

相关问题