简体   繁体   English

可可中的单例和内存管理

[英]Singletons and memory management in Cocoa

I have a singleton as class method: 我有一个单例作为类方法:

+(WordsModel *) defaultModel{
    static WordsModel *model = nil;  

    if (!model) {
        model =  [[[self alloc] init] autorelease];
    }

    return model;
}

What happens with the static reference to model inside the method? 在方法内部使用静态引用建模会发生什么? Will it ever get released? 它会被发布吗?

Not only will it get released (because you sent it an -autorelease message), your next attempt to use it will probably lead to a crash because the model pointer wasn't set to nil when the object was released. 它不仅会被释放(因为您发送了-autorelease消息),而且下次尝试使用它可能会导致崩溃,因为释放对象时model指针未设置为nil。 So, it will then point to memory that's either garbage, or (if that memory has been re-used) to a different object than the one you expected. 因此,它然后将指向要么是垃圾的内存,要么指向(如果该内存已被重新使用)指向与您期望的对象不同的对象。

It won't work as you are autoreleasing your instance of your class... 由于您正在自动释放您的课程实例,因此该方法无法正常工作...

On the next runloop, it will be released... 在下一个运行循环中,它将被释放...

Take a look at the standard singleton patterns: http://www.cocoadev.com/index.pl?SingletonDesignPattern 看看标准的单例模式: http : //www.cocoadev.com/index.pl? SingletonDesignPattern

The static instance should be a global variable, that will be freed when your app exits... 静态实例应该是一个全局变量,当您的应用退出时将被释放...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM