How can I remove all NSTableColumns from an NSTableView?
Asked Answered
E

4

5

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];
}
Erse answered 22/12, 2011 at 18:54 Comment(1)
does the crash come with a message in the console ?Kisor
H
16

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]];
    }
}
Hutch answered 18/4, 2012 at 12:57 Comment(0)
H
4

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.

Hudgins answered 17/6, 2014 at 3:7 Comment(0)
T
0
[[[_tableView tableColumns] copy] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [_tableView removeTableColumn:obj];
}];
Troytroyer answered 19/4, 2014 at 9:34 Comment(0)
N
0

Here is a Swift implementation:

tableView.tableColumns.forEach({tableView.removeTableColumn($0)})
Nonfiction answered 28/5, 2019 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.