这是情况.假设我有一个名为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.
更多推荐
在初始化中引发异常时,如何防止泄漏?
发布评论