gpt4 book ai didi

objective-c - 什么是自动释放池?

转载 作者:IT老高 更新时间:2023-10-28 11:30:37 25 4
gpt4 key购买 nike

Possible Duplicate:
Why use Autorelease pool?

所有 Objective-C 起始页面都会在主函数声明下打开默认的 @autoreleasepool{...} 语句。但是这个声明实际上在做什么?新的 Objective-C 自动释放对象并且删除该行对程序没有任何改变。这个命令真的有必要吗?

最佳答案

@autoreleasepool 语句的作用与以前相同,而不是使用 NSAutoreleasePool类(class)。 NSAutoreleasePool 的工作方式有点奇怪,因为创建它会在整个应用程序中产生影响; @autoreleasepool 创建一个范围区域,并使其更清楚池内的内容以及它何时耗尽(当它超出范围时)。根据 Apple 的说法,它的效率也更高。

自动释放池的概念很简单,只要一个对象实例被标记为自动释放(例如 NSString* str = [[[NSString alloc] initWithString:@"hello"] autorelease]; ),此时它的保留计数为 +1,但在运行循环结束时,池被耗尽,任何标记为 autorelease 的对象的保留计数都会减少。这是一种在您准备任何可以为自己保留的东西时保留对象的方法。

使用 ARC,虽然开发人员不使用 autorelease 方法,但管理 ARC 的底层系统会为您插入该方法。 (记住: ARC 所做的只是在适当的时候为您插入 retainreleaseautorelease 调用) .因此,现有的 AutoreleasePool 概念需要保留。

如果您删除自动释放池,您的对象将开始泄漏

In a reference counted environment, Cocoa expects there to be an autorelease pool always available. If a pool is not available, autoreleased objects do not get released and you leak memory. In this situation, your program will typically log suitable warning messages.

关于objective-c - 什么是自动释放池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14677049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com