在初始化中引发异常时,如何防止泄漏?

编程入门 行业动态 更新时间:2024-10-27 15:30:12
本文介绍了在初始化中引发异常时,如何防止泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是情况.假设我有一个名为MYFoo的课程.这是初始化程序:

Here's the situation. Let's say I have a class called MYFoo. Here's it's initializer:

-init { self = [super init]; if (self) { // during initialization, something goes wrong and an exception is raised [NSException raise ...]; } return self; }

现在我想在其他地方使用MYFoo对象,所以我使用一种通用模式:

Now somewhere else I want to use a MYFoo object, so I use a common pattern:

MYFoo *foo = [[[MYFoo alloc] init] autorelease];

但是将要发生的是,即使在第二部分周围有try/catch,也要分配MYFoo对象,将抛出异常,错过了自动释放,并且未初始化的MYFoo对象将泄漏.

But what's going to happen is that, even if there's a try/catch around the 2nd part, a MYFoo object is going to be allocated, the exception will be thrown, the autorelease missed, and the uninitialized MYFoo object will leak.

在这里应该采取什么措施来防止这种泄漏?

What should happen here to prevent this leak?

推荐答案

Apple Docs 说最好的做法是不要扔.

The Apple Docs say the best practice is not to throw.

处理初始化失败

通常,如果有问题 在初始化方法期间,您 应该打电话给[自我释放]并返回 没有.

In general, if there is a problem during an initialization method, you should call [self release] and return nil.

如果您需要知道发生了什么,则可以init该对象并具有某种内部状态,调用者将检查该状态以确保该对象可用.

If you need to know what happened, you can init the object and have some kind of internal state that gets checked by the caller to ensure the object is usable.

更多推荐

在初始化中引发异常时,如何防止泄漏?

本文发布于:2023-11-04 01:27:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556573.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   如何防止   异常

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!