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

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

问题描述

我正在考虑Objective-C中Try-Catch的优缺点。
根据这篇文章消除NSException在iOS中的神话:我们可以使用@ try ... @ catch,@finally?,try-catch没有那么糟糕,除了它在ARC中泄漏内存



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

解决方案

首先:Objective-C中的异常具有不同的语义。一个例外意味着由于编程错误而导致错误,因为应用程序的进一步执行并不实用。终止它使用可可的错误处理模式(如可用的错误处理模式)一>。 (其原因是在许多情况下异常似乎很方便,但在其他情况下很难处理,即对象构造。请阅读C ++中的异常,这很痛苦。)



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

   - (void)方法
{
id reference = ...;
//某些ARC代码保留对象,参考点。
...
@throw ...
...
//引用失去其范围,因为方法终止
//某些ARC代码释放对象,引用指向。
}

如果有异常,该方法立即保留,ARC代码和从而不会执行释放对象的方法的结束。这是泄漏。



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



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



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


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, i. e. 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.

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

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