gpt4 book ai didi

ios - 需要有关@autoreleasepool 的帮助

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:17:41 26 4
gpt4 key购买 nike

Advanced Memory Management Programming Guide关于@autoreleasepool 说:

使用本地自动释放池 block 减少峰值内存占用量

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

这段代码是否也可以在没有自动释放池的情况下编写并有效地管理?

比如创建一个 fileContents 的属性 并在处理后将其设置为 nil

self.filecontents = nil;

最佳答案

问题是 stringWithContentsOfURL 可以返回一个自动释放的对象。但你可以使用initWithContentsOfURL 改为:

NSArray *urls = <# An array of file URLs #>;
for (NSURL *url in urls) {
NSError *error;
NSString *fileContents = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:&error];
/* Process the string ... */
fileContents = nil;
}

init... 方法返回 (+1) 保留对象而不是自动释放对象,因此fileContents = nil 释放对象并销毁它(如果没有其他对它的强烈引用)。

当然这只有在“字符串处理代码”不产生时才有用其他自动释放的对象。 (此外,如果设置了 error,将是一个自动释放的对象。)

(实际上,stringWithContentsOfURL 不“保证”返回一个自动释放的目的。特别是在 Release 模式下,ARC 编译器去除了许多不必要的保留/自动释放/释放操作。)

我不知道建立本地自动释放池是否是一项昂贵的操作(我假设没有)。如果您在循环中处理许多对象并且您不知道究竟是否创建了自动释放的对象,这可能是明智的只使用本地自动释放池并且“不关心它”。使用“仪器”进行分析也可以提供更多见解。

有关详细信息,请参阅“保留的返回值”和“未保留的返回值”在Clang ARC documentation .

关于ios - 需要有关@autoreleasepool 的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18170163/

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