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

标签 ios objective-c macos memory-leaks automatic-ref-counting

我的原始项目正在泄漏,所以我搜索了泄漏点。当我找到它时,我创建了一个简单的新项目。 该项目使用 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/

相关文章:

ios - 如何使用 Alamofire 关闭证书验证?

ios - 来自 WSDL 的 Objective-C 的 SOAP 客户端生成器?

ios - 从 UIFont 或 .ttf 文件中获取字体的每个字符(带形状)

ios - objective-c - 获取数据(核心数据)

ios - 如何从 Mac OS X 应用程序获取 iPod/iPhone iOS 版本?

objective-c - 使用 iOS api 从北方获取角度

python - 为什么插入和删除在 Windows 7 上比在 Mac 10.9 上花费的时间长 100 多倍?

ios - 选择 iOS 和 Mac 应用程序的包标识符

iphone - 如何根据 NSArray 中自定义对象的日期进行排序...?

java - Jar 文件无法在 SWT Mac 上运行