Cocoa 中的单例和内存管理
我有一个单例作为类方法:
+(WordsModel *) defaultModel{
static WordsModel *model = nil;
if (!model) {
model = [[[self alloc] init] autorelease];
}
return model;
}
方法内对模型的静态引用会发生什么?它会被释放吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不仅会被释放(因为您向它发送了
-autorelease
消息),您下次尝试使用它可能会导致崩溃,因为model
指针没有被释放。当对象被释放时设置为零。因此,它将指向垃圾内存,或者(如果该内存已被重新使用)指向与您预期不同的对象。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 themodel
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.当您自动释放类的实例时,它将不起作用...
在下一个运行循环中,它将被释放...
看看标准的单例模式:
http://www.cocoadev.com/index.pl?SingletonDesignPattern
静态实例应该是一个全局变量,当您的应用程序退出时它将被释放......
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...