Using Autorelease Pool Blocks
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-CJBFBEDI
Using Autorelease Pool Blocks
Autorelease pool blocks provide a mechanism whereby you can relinquish ownership of an object, but avoid the possibility of it being deallocated immediately (such as when you return an object from a method). Typically, you don’t need to create your own autorelease pool blocks, but there are some situations in which either you must or it is beneficial to do so.
About Autorelease Pool Blocks
An autorelease pool block is marked using @autoreleasepool
, as illustrated in the following example:
@autoreleasepool { |
// Code that creates autoreleased objects. |
} |
At the end of the autorelease pool block, objects that received an autorelease
message within the block are sent a release
message—an object receives a release
message for each time it was sent an autorelease
message within the block.
Like any other code block, autorelease pool blocks can be nested:
@autoreleasepool { |
// . . . |
@autoreleasepool { |
// . . . |
} |
. . . |
} |
(You wouldn’t normally see code exactly as above; typically code within an autorelease pool block in one source file would invoke code in another source file that is contained within another autorelease pool block.) For a given autorelease
message, the corresponding release
message is sent at the end of the autorelease pool block in which the autorelease
message was sent.
Cocoa always expects code to be executed within an autorelease pool block, otherwise autoreleased objects do not get released and your application leaks memory. (If you send an autorelease
message outside of an autorelease pool block, Cocoa logs a suitable error message.) The AppKit and UIKit frameworks process each event-loop iteration (such as a mouse down event or a tap) within an autorelease pool block. Therefore you typically do not have to create an autorelease pool block yourself, or even see the code that is used to create one. There are, however, three occasions when you might use your own autorelease pool blocks:
If you are writing a program that is not based on a UI framework, such as a command-line tool.
If you write a loop that creates many temporary objects.
You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.
If you spawn a secondary thread.
You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects. (See Autorelease Pool Blocks and Threads for details.)
Use Local Autorelease Pool Blocks to Reduce Peak Memory Footprint
Many programs create temporary objects that are autoreleased. These objects add to the program’s memory footprint until the end of the block. In many situations, allowing temporary objects to accumulate until the end of the current event-loop iteration does not result in excessive overhead; in some situations, however, you may create a large number of temporary objects that add substantially to memory footprint and that you want to dispose of more quickly. In these latter cases, you can create your own autorelease pool block. At the end of the block, the temporary objects are released, which typically results in their deallocation thereby reducing the program’s memory footprint.
The following example shows how you might use a local autorelease pool block in a for
loop.
NSArray *urls = <# An array of file URLs #>; |
for (NSURL *url in urls) { |
@autoreleasepool { |
NSError *error; |
NSString *fileContents = [NSString stringWithContentsOfURL:url |
encoding:NSUTF8StringEncoding error:&error]; |
/* Process the string, creating and autoreleasing more objects. */ |
} |
} |
The for
loop processes one file at a time. Any object (such as fileContents
) sent an autorelease
message inside the autorelease pool block is released at the end of the block.
After an autorelease pool block, you should regard any object that was autoreleased within the block as “disposed of.” Do not send a message to that object or return it to the invoker of your method. If you must use a temporary object beyond an autorelease pool block, you can do so by sending a retain
message to the object within the block and then send it autorelease
after the block, as illustrated in this example:
– (id)findMatchingObject:(id)anObject { |
id match; |
while (match == nil) { |
@autoreleasepool { |
/* Do a search that creates a lot of temporary objects. */ |
match = [self expensiveSearchForObject:anObject]; |
if (match != nil) { |
[match retain]; /* Keep match around. */ |
} |
} |
} |
return [match autorelease]; /* Let match go and return it. */ |
} |
Sending retain
to match
within the autorelease pool block the and sending autorelease
to it after the autorelease pool block extends the lifetime of match
and allows it to receive messages outside the loop and be returned to the invoker of findMatchingObject:
.
Autorelease Pool Blocks and Threads
Each thread in a Cocoa application maintains its own stack of autorelease pool blocks. If you are writing a Foundation-only program or if you detach a thread, you need to create your own autorelease pool block.
If your application or thread is long-lived and potentially generates a lot of autoreleased objects, you should use autorelease pool blocks (like AppKit and UIKit do on the main thread); otherwise, autoreleased objects accumulate and your memory footprint grows. If your detached thread does not make Cocoa calls, you do not need to use an autorelease pool block.
Note: If you create secondary threads using the POSIX thread APIs instead of NSThread
, you cannot use Cocoa unless Cocoa is in multithreading mode. Cocoa enters multithreading mode only after detaching its first NSThread
object. To use Cocoa on secondary POSIX threads, your application must first detach at least one NSThread
object, which can immediately exit. You can test whether Cocoa is in multithreading mode with the NSThread
class method isMultiThreaded
.
Using Autorelease Pool Blocks的更多相关文章
- Autorelease pool
根据苹果官方文档中对 Using Autorelease Pool Blocks 的描述,我们知道在下面三种情况下是需要我们手动添加 autoreleasepool 的: 如果你编写的程序不是基于 U ...
- Objective-C Autorelease Pool 的实现原理
内存管理一直是学习 Objective-C 的重点和难点之一,尽管现在已经是 ARC 时代了,但是了解 Objective-C 的内存管理机制仍然是十分必要的.其中,弄清楚 autorelease 的 ...
- 【引】objective-c,6:Autorelease Pool
参考博客: http://blog.leichunfeng.com/blog/2015/05/31/objective-c-autorelease-pool-implementation-princi ...
- 黑马程序员-autorelease pool
Autorelease:可以延迟给对象发送release消息.发送一个autorelease消息给对象,证明该对象在一定时间内有效,一定时间后会对该对象进行释放,进行一次release. 一个auto ...
- RunLoop总结:RunLoop 与GCD 、Autorelease Pool之间的关系
如果在面试中问到RunLoop相关的知识,很有可能也会问到RunLoop与GCD.Autorelease Pool有没有关系,哪些地方用到了GCD.Autorelease Pool等. So,本文就总 ...
- objective-C 的内存管理之-自动释放池(autorelease pool)
如果一个对象的生命周期显而易见,很容易就知道什么时候该new一个对象,什么时候不再需要使用,这种情况下,直接用手动的retain和release来判定其生死足矣.但是有些时候,想知道某个对象在什么时候 ...
- 什么时候应该使用Autorelease Pool
csdn首发:http://blog.csdn.net/guijiewan/article/details/46470285 Objective c使用ARC之后,一般都不需要再手动调用retain, ...
- ios学习笔记
1.对于autorelease的理解 Each thread in a Cocoa application maintains its own stack of autorelease pool bl ...
- ios专题 -内存管理 研究
[原创]http://www.cnblogs.com/luoguoqiang1985 ARC [新的规则] 1. you cannot explicitly invoke dealloc, or im ...
随机推荐
- iOS 面试全方位剖析 -- Block篇
1.Block的本意 block本质上也是一个OC对象,它内部也有个isa指针, block是封装了函数调用以及函数调用环境的OC对象, block是封装函数及其上下文的OC对象 2.block截获变 ...
- PHP 预定义常量(魔术常量)
显示当前代码在多少行__LINE__ echo __LINE__; 获取当前文件绝对路径 __FILE__ echo __FILE__; //结果为: // D:\xxxx\xxxx\xxxx\ind ...
- 在JAVA中自定义连接数据库的工具类
为什么要自定义数据库连接的工具类: 在开发中,我们在对数据库进行操作时,必须要先获取数据库的连接,在上一篇随笔中提到的获取数据库连接的步骤为: 1.定义好4个参数并赋值 2.加载驱动类 3.获取数据库 ...
- SpringMVC 思想介绍
MVC 思想简介 博客园好像不支持发布markdown的时序图, 如果你会markdown并且不太熟悉Springmvc执行流程, 照着图在Markdown上面敲一遍执行流程,这是我经历过的最快的记忆 ...
- 1、python简单介绍
写在前面:曾经与java擦肩而过,现在懊悔很深,希望自己通过学习python,熟练掌握python,来弥补曾经的愚蠢.python简单介绍 python 1989年年底诞生,截止2017年,已经是IT ...
- Luogu P2973 [USACO10HOL]赶小猪Driving Out the Piggi 后效性DP
有后效性的DP:$f[u]$表示到$u$的期望次数,$f[u]=\Sigma_{(u,v)} (1-\frac{p}{q})*f[v]*deg[v]$,最后答案就是$f[u]*p/q$ 刚开始$f[1 ...
- HDU 5908 Abelian Period 可以直接用multiset
http://acm.hdu.edu.cn/showproblem.php?pid=5908 要求把数组分成k组使得每组中的元素出现次数相同 就是分成k个集合,那么直接用multiset判定就可以 有 ...
- Microsoft JET Database Engine (0x80004005)未指定的错误解决
Microsoft JET Database Engine (0x80004005)未指定的错误,这个错误只有在使用Access数据库时才能出现 出现以上问题,可以使用以下步骤进行解决问题: 1.系统 ...
- easyUI 鼠标悬停某行提示
最近参与公司的电子档案系统的开发,需求是需要用户鼠标悬停某一行时,需要根据后台业务数据进行提示. 档案系统开发采用的框架是struts2+mybatis+spring+easyUI开发,而前端的e ...
- 安装xenserver过程中出现的问题
运行环境:win10系统,神舟战神z7m-KP7GT型号笔记本,VMWare虚拟机,XenServer7.2.0,XenCenter7.2.0 5月22日下午安装上xenserver虚拟机,发现虚拟机 ...