开发者

How should I handle a possible memory leak because of an exception in Objective-C?

I have a method which allocates an object and then releases it at the end. In between, the method calls another method which could possibly raise an exception, and the exception will probably be caught by the method calling my method. If开发者_如何学Go this happens, the object will never get released (or will it?). How should I prevent this from happening?


You could always auto-release it before calling methods that possibly throw - that way you can be sure it will be released wether an exception will be thrown or not.

If that is not sensible for some reason, you could do the release in a @finally block1:

A @finally block contains code that must be executed whether an exception is thrown or not.

Note that using a @finally block without @catch is fine:

Resource *resource = [[Resource alloc] init];
@try {
    [obj someMethodThatMayThrow];
}
@finally {
    [resource release];
}


Do not throw exceptions for anything but fatal, non-recoverable, errors

That is the Cocoa design pattern employed across the frameworks and system. If you decide you want to use exceptions for flow control then:

  • you are going against the Cocoa pattern and your code will be a misfit amongst the system APIs

  • if there are any frames in the system frameworks across which the exception was thrown, those frameworks will be left in an undefined state

Exceptions in Mac OS X and iOS are used only to indicate programmer error; to indicate that the app has entered into a state for which recovery isn't possible. Don't waste your time trying to support exceptions beyond that mode, you'll just be wasting your time and creating code that doesn't work like the system frameworks.

Note that throwing an exception on iOS is actually quite expensive (both CPU and memory). As well, @finally doesn't come for free, either, though the overhead of @finally is relatively minor by comparison.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜