简体   繁体   中英

Why does “try catch” in Objective-C cause memory leak?

I am thinking about pros and cons of Try-Catch in Objective-C. According to this article Dispelling NSException Myths in iOS: Can We Use @try…@catch, @finally? , try-catch isn't that bad, except for it leaks memory in ARC.

So how does try-catch cause memory leak?

First of all: Exceptions have different semantics in Objective-C. An exception means that something went completely wrong because of a programming mistake and the further execution of the application is not useful. Terminate it! To handle "expected errors" (like insufficient user input or not responding servers et al.) use Cocoa's error handling pattern . (The reason for this is that exceptions seems to be convenient in many situation, but are very hard to handle in other situations, ie while object construction. Read about exceptions in C++. It is painful.)

To your Q: ARC adds additional code to handle memory management. This code has to be executed to handle the memory management, esp. to release objects. If an exception occurs before this is done, the control flow never reaches the release statement. Memory leaks.

- (void)method
{
   id reference = …;
   // Some ARC code to retain the object, reference points to.
   … 
   @throw …
   …
   // reference loses its extent, because of method termination
   // Some ARC code to release the object, reference points to.
}

If you have an exception, the method is left immediately and the ARC code and the end of the method to release the object is never executed. This is the leak.

You can change this behavior by compiling the source with -fobjc-arc-exceptions option.

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#exceptions

This will add code to make ARC exception-safe causing a runtime penalty. But there is little reason to do so in Cocoa development, as explained at the beginning of this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM