clearAll method in Leaks


#1

Hi, in testing the Leaks instrument we changed clearAll code to the following

[code]

  • (void)clearAll
    {
    [linesInProcess removeAllObjects];
    // [completeLines removeAllObjects];
    completeLines = [[NSMutableArray alloc] init];

    // Redraw
    [self setNeedsDisplay];
    }[/code]

My question is, why did we have to call [[NSMutableArray alloc] init]? Would
not following code (or leaving clearAll as it was) also cause a memory leak??? (due to retain cycle)

[code]

  • (void)clearAll
    {
    [linesInProcess removeAllObjects];
    [completeLines removeAllObjects];
    // completeLines = [[NSMutableArray alloc] init];

    // Redraw
    [self setNeedsDisplay];
    }[/code]


#2

No, because originally, the objects within the array would be set nil. So the lines lose the array as an owner, the owner count is nil and they get deallocated. A strong reference of the lines back to the array doesn´t matter.
If you set the array nil or make a new one, the lines still have an owner: the old array. And the old array does not get deallocated, because it still has at least one owner: the line(s). That´s a cycle.

To describe it another way:
You leave the clearAll Method like it was. After calling “removeAllObjects” the Object diagram is like this:

Objects: Line==>Array<==TouchDrawView Owners: 0 1+ 1

The lines get deallocated so

Objects: Array<==TouchDrawView Owners: 1 1

You change the clearAll Method to make a new Array:

Objects: Line==>Array Array<==TouchDraw ^===" Owners: 1 1+ 1 1