How to remove all NSTableColumns from an NSTableView?

I am trying to implement an NSTableView cleanup method for all AND columns and columns. But I get a crash when trying 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]; } 
+4
source share
3 answers

Well, if that helps, you can remove all columns like this:

 - (void)removeAllColumns { while([[tableView tableColumns] count] > 0) { [tableView removeTableColumn:[[tableView tableColumns] lastObject]]; } } 
+14
source

The NSArray returned by tableColumns changes to removeTableColumn . Do not assume that he has not changed.

Although it returns as a non-mutable NSArray, the underlying implementation is changing, and it is unsafe to use NSEnumerator with modified collections. In the while loop, you send the nextObject message to the enumerator whose current object was just deleted — 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 in an empty array returns nil, col sets nil, the condition false, and the while loop ends.

+3
source
 [[[_tableView tableColumns] copy] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [_tableView removeTableColumn:obj]; }]; 
0
source

Source: https://habr.com/ru/post/1387621/


All Articles