0
- (NSArray *) makeKeyValueArray: (NSArray *) arr
{
    NSMutableArray *result = [[NSMutableArray alloc] init];
    for(int i = 0; i < [arr count]; i++)
    {
        [result addObject:[[KeyValue alloc] initWithData:[arr objectAtIndex:i] :[arr objectAtIndex:i]]];
    }
    return result;
}

Instruments 在上面的代码中显示了 188 个泄漏,这是为什么呢?谁能给我解释一下?

4

1 回答 1

5
- (NSArray *) makeKeyValueArray: (NSArray *) arr
{
    NSMutableArray *result = [[NSMutableArray alloc] init];
    for(int i = 0; i < [arr count]; i++)
    {
        id obj = [[KeyValue alloc] initWithData:[arr objectAtIndex:i] :[arr objectAtIndex:i]]; // obj reference count is now 1, you are the owner
        [result addObject:obj]; //reference count is now 2, the array is also an owner as well as you.
        [obj release];// reference count is now 1, you are not the owner anymore
    }
    return [result autorelease];
}  

查看基本内存管理规则

您必须放弃您拥有的对象的所有权

于 2012-12-11T05:53:57.123 回答