1

嗨,我有这个代码来初始化我的班级。

- (id)initWithSize:(int)size {

    self = [super init];

    if( self != nil )
    {
        [self setMyVector:[[NSMutableArray alloc] initWithCapacity:size]];

        for ( int i = 0; i < size; i++ ) 
        {
            [myVector addObject: [[NSMutableArray alloc] initWithCapacity:size]];
        }
    }

    return self;
}

我在仪器中得到了这个泄漏!
类别:CFArray (store-deque)
事件类型:Malloc

有人知道我需要解决什么吗?谢谢 !

4

1 回答 1

6

泄漏在您的 for 循环中,也可能在之前的一个。

首先,这一行:

[self setMyVector:[[NSMutableArray alloc] initWithCapacity:size]];

如果setMyVector保留传递的数组(根据惯例,它可能应该保留),那么您已经泄漏了数组。首先你分配并初始化数组。它的保留计数为 +1。然后将其设置到 myVector 实例变量中,这意味着它的保留计数为 +2。当您将其他内容放入 myVector 或在dealloc方法中释放 myVector 变量时,您将减少保留计数,这意味着它的保留计数为 +1。换句话说,它不会被释放,并且您已经泄漏了数组。

另一个明确的泄漏是在你的 for() 循环中,你有:

[myVector addObject: [[NSMutableArray alloc] initWithCapacity:size]];

同样,您创建一个保留计数为 +1 的数组,然后将其添加到 myVector 数组中,该数组将再次保留它 (+2)。但是,您不再拥有指向该数组的指针,因此您已经泄露了它。

Both of these leaks can be solved by using [NSMutableArray arrayWithCapacity:size] instead of the alloc/init approach. This will create an autoreleased array, which will solve your memory leak.

If you don't know what autoreleasing is, then you may want to consider creating the array and storing it into a local variable, adding it to myVector (or setting it into myVector), and then immediately releasing it afterwards.

于 2009-09-06T20:51:31.050 回答