gpt4 book ai didi

ios - 如何使用 ARC 释放 NSMutableArray 中的对象?

转载 作者:可可西里 更新时间:2023-11-01 03:56:59 27 4
gpt4 key购买 nike

我的原始项目正在泄漏,所以我搜索了泄漏点。当我找到它时,我创建了一个简单的新项目。该项目使用 ARC,我添加的唯一代码如下。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
int elements = 10000000;
//memory usage 5,2 MB

NSMutableArray *array = [NSMutableArray arrayWithCapacity:elements];
//memory usage 81,7 MB

for (int i = 0; i < elements; i++) {
[array addObject:[NSObject new]];
}
//memory usage 234,3 MB

[array removeAllObjects];
//memory usage 234,3 MB

array = nil;
//memory usage 159,5 MB
}

调用 [array removeAllObjects] 后,数组中的所有 NSObject 都应该被释放,内存使用量应该再次为 81.7 MB。我做错了什么?

最佳答案

这里

NSMutableArray *array = [NSMutableArray arrayWithCapacity:elements];

您正在创建自动释放对象 ( autorelease pool )。

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

@autoreleasepool {}方法包装[NSMutableArray arrayWithCapacity:elements]:

NSMutableArray *array;
@autoreleasepool {
array = [NSMutableArray arrayWithCapacity:elements];
// [NSMutableArray arrayWithCapacity:] creates object with retainCount == 1
// and pushes it to autorelease pool

// array = some_object; usually (and in this case also) is transformed by ARC to
// [array release]; [some_object retain]; array = some_object;

// so here array will have retainCount == 2 and 1 reference in autorelease pool

} // here autorelease pool will call `release` for its objects.
// here array will have retainCount == 1

或者改成

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:elements];

关于ios - 如何使用 ARC 释放 NSMutableArray 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23299562/

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