开发者

Singletons and memory management in Cocoa

I have a singleton as class method:

+(WordsModel *) defaultModel{
 开发者_JAVA百科   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. 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

The static instance should be a global variable, that will be freed when your app exits...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜