简体   繁体   English

为什么Objective-C中的“ try catch”会导致内存泄漏?

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

I am thinking about pros and cons of Try-Catch in Objective-C. 我在考虑在Objective-C中Try-Catch的优缺点。 According to this article Dispelling NSException Myths in iOS: Can We Use @try…@catch, @finally? 根据这篇文章, 消除iOS中的NSException神话:我们可以使用@ try…@ catch,@ finally吗? , try-catch isn't that bad, except for it leaks memory in ARC. ,try-catch并没有那么糟糕,除了它会泄漏ARC中的内存。

So how does try-catch cause memory leak? 那么try-catch如何导致内存泄漏?

First of all: Exceptions have different semantics in Objective-C. 首先:异常在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 . 要处理“预期的错误”(例如用户输入不足或服务器没有响应等),请使用Cocoa的错误处理模式 (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.) (这样做的原因是,在许多情况下异常似乎很方便,但在其他情况下(即在对象构造时)很难处理。请阅读C ++中的异常。这很痛苦。)

To your Q: ARC adds additional code to handle memory management. 问:ARC添加了其他代码来处理内存管理。 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. 如果在此之前发生异常,则控制流将永远不会到达release语句。 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. 如果有异常,则该方法将立即保留,并且永远不会执行ARC代码以及该方法的结尾以释放对象。 This is the leak. 这就是泄漏。

You can change this behavior by compiling the source with -fobjc-arc-exceptions option. 您可以通过使用-fobjc-arc-exceptions选项编译源来更改此行为。

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

This will add code to make ARC exception-safe causing a runtime penalty. 这将添加代码以使ARC异常安全,从而导致运行时损失。 But there is little reason to do so in Cocoa development, as explained at the beginning of this answer. 但是,正如该答案开头所解释的,在可可粉开发中没有理由这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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