iOS:什么时候最好在视图控制器中释放模型对象?
我这里有一个相当基本的问题。我发现我经常在视图控制器的 viewDidLoad: 方法中实例化模型对象,例如用于填充视图控制器中表的元素的 Web 服务对象:
- (void)viewDidLoad {
[super viewDidLoad];
itemService = [[BlogItemService alloc] init];
}
我应该在哪里释放 itemService?在 viewDidUnload 或 dealloc 中?
此外,在 viewDidLoad 中分配这样的对象很常见吗?难道就没有更合适的init类型方法吗?
更新:我有一个特别担心的问题。假设我在 dealloc 中释放了 itemService。如果卸载视图然后重新加载,但视图控制器未释放,是否会出现内存泄漏,因为在实例化新实例时,前一个 itemService 实例会被孤立?
I've got a fairly basic question here. I find that quite often I instantiate model objects in the viewDidLoad: method of view controllers, say in the case of a web service object that is used to populate the elements of a table in the view controller:
- (void)viewDidLoad {
[super viewDidLoad];
itemService = [[BlogItemService alloc] init];
}
Where should I release itemService? In viewDidUnload or dealloc?
Furthermore, is it common to allocate objects like this in viewDidLoad? Is there not a more suitable init type method?
Update: I have a particular concern. Let's say I deallocate itemService in dealloc. If the view is unloaded and then reloaded, but the view controller is not deallocated, won't I have a memory leak as the previous instance of itemService is orphaned when the new one is instantiated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果对象是轻量级的或者需要很长时间来创建,则在dealloc中进行。如果消耗大量内存,则在 viewDidLoad/viewDidUnload 中使用匹配对。
是的
指定的初始值设定项(在某些情况下)
为了避免这种情况,请使用:
if the object is lightweight or takes a long time to create, do it in dealloc. if it consumes a lot of memory, then use matching pairs in viewDidLoad/viewDidUnload.
yes
the designated initializer (in some cases)
to avoid this, use:
这是非常罕见的情况,但是如果您卸载然后再次加载视图,您将按照您的建议进行泄漏。因此,在哪里分配对象是一个很好的问题,这取决于您的选择。当对象非常重时,可能最好在每次加载视图时加载对象,并且一些小对象可能会更容易在 init 中加载。但是,如果您想多次加载和卸载视图,您也必须小心处理视图控制器,因为常见的模式是每次视图消失时销毁控制器(大多数情况下这是一个很好的解决方案)。
It is very uncommon situation, but if you unload and then load view again you will have leak just as you suggested. So where to allocate objects it is a good question and it rather depends on your choice. Probably it is better to load objects every time view is loaded when they are very heavy and some small objects will probably be easier to load in init. But you have also handle your view controller carefully if you want to load and unload view many times, beacuse common pattern is to destroy controller every time the view dissapears (and mostly it is a good solution).
您应该在 dealloc 中释放对象
您可以使用以下方式分配内存:
You should release the object in dealloc
You can allocate memory using :
如果您问我,初始化模型对象的最佳位置是在类的
init
方法中,并在dealloc
中release
方法。If you would ask me the best place to initialize model objects is in the
init
method of the class andrelease
it indealloc
.