Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all NSTableColumns from an NSTableView?

I am trying to implement a method to clear the NSTableView of all items AND columns. But I get a crash when I try to implement the following:

- (void)clearResultData
{
    [resultArray removeAllObjects];
    NSArray *tableCols = [resultTableView tableColumns];
    if ([tableCols count] > 0)
    {
        id object;
        NSEnumerator *e = [tableCols objectEnumerator];
        while (object = [e nextObject])
        {
            NSTableColumn *col = (NSTableColumn*)object;
            [resultTableView removeTableColumn:col];
        }
    }
    [resultTableView reloadData];
}
like image 955
Ronaldo Nascimento Avatar asked Dec 22 '11 18:12

Ronaldo Nascimento


2 Answers

Well, if it's any help you can remove all the columns like this:

- (void)removeAllColumns
{
    while([[tableView tableColumns] count] > 0) {
        [tableView removeTableColumn:[[tableView tableColumns] lastObject]];
    }
}
like image 77
Angus Glashier Avatar answered Nov 15 '22 09:11

Angus Glashier


The NSArray returned by tableColumns is changed by removeTableColumn. Do not assume it is unchanged.

Although it is returned as a non-mutable NSArray, the underlying implementation is being modified and it is not safe to use NSEnumerator with collections that are modified. In the while loop, you are sending a nextObject message to an enumerator whose current object was just deleted -- so bad things can happen!

Here's a more efficient implementation:

NSTableColumn* col;
while ((col = [[tableView tableColumns] lastObject])) {
    [tableView removeTableColumn:col];
}

When there are no columns in the table view: tableColumns returns an empty array, lastObject on an empty array returns nil, col is assigned the value of nil, the condition is false and the while loop finishes.

like image 23
Hoylen Avatar answered Nov 15 '22 11:11

Hoylen