ARC 之 NSAutoreleasePool 是怎么工作的?

此文实际成为2015/07/28

The NSAutoreleasePool class is used to support Cocoa's reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained.

在 ARC 的环境下 这样使用

 @autoreleasepool{
   // Code benefitting from local autorelease pool.
 }

它用来替代原来老是的写法:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Code benefitting from a local autorelease pool.
[pool release];

使用上面写法,就算在非 ARC 时也有好处,因为可以避免出现下面的错误代码:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   @try {
       // stuff
   } @finally {
       [pool drain];  WRONG
   }

详情说明见: [objc explain] Exceptions and autorelease

就算是老式的写法也应该是像下面这样写:

  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   @try {
       // stuff
   } @finally {
       // cleanup things other than pool itself
   }
   [pool drain];

autoreleasepool 代码块中间处理异常。

Excption 与异常处理的更多说明

  1. 出现异常后对应的 autorelease pool 会被自动清理

Autorelease pools are automatically cleaned up after exceptions. If you want to write exception-safe code, then autorelease pools are a useful tool.

  1. 异常对象自己会处理 autorelease的问题。
    +[NSException exceptionWithName...]+[NSException raise...] 都是如此。

你可能感兴趣的:(ARC 之 NSAutoreleasePool 是怎么工作的?)