为什么“try catch"在Objective-C 中导致内存泄漏? [英] Why does "try catch" in Objective-C cause memory leak?

查看:21
本文介绍了为什么“try catch"在Objective-C 中导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在 Objective-C 中使用 Try-Catch 的优缺点.根据这篇文章Dispelling NSException Myths in iOS: Can We Use @try…@catch, @finally?,try-catch 并没有那么糟糕,除了它会在 ARC 中泄漏内存.

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.

那么try-catch是如何导致内存泄漏的呢?

So how does try-catch cause memory leak?

推荐答案

首先:Objective-C 中的异常有不同的语义.异常意味着由于编程错误而完全出错并且应用程序的进一步执行没有用.终止它!要处理预期错误"(例如用户输入不足或服务器不响应等),请使用 Cocoa 的错误处理模式.(这样做的原因是异常在许多情况下似乎很方便,但在其他情况下很难处理,即在对象构造时.阅读 C++ 中的异常.这很痛苦.)

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, i. e. while object construction. Read about exceptions in C++. It is painful.)

对于您的问题:ARC 添加了额外的代码来处理内存管理.必须执行此代码来处理内存管理,尤其是.释放对象.如果在这之前发生异常,控制流永远不会到达发布语句.内存泄漏.

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.
}

如果出现异常,该方法会立即离开,并且永远不会执行 ARC 代码和释放对象的方法的结尾.这是泄漏.

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.

您可以通过使用 -fobjc-arc-exceptions 选项编译源代码来更改此行为.

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

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

这将添加代码以使 ARC 异常安全,从而导致运行时惩罚.但是正如本答案开头所解释的那样,在 Cocoa 开发中几乎没有理由这样做.

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.

这篇关于为什么“try catch"在Objective-C 中导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆