Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculating group row at run time of a NSTableView
    text
    copied!<p>I have a <code>NSTableView</code>, filled with song titles.</p> <p>The songs are ordered by artists, so I can display the artist name as a row view.<br /></p> <p><img src="https://i.stack.imgur.com/P9tj4.png" alt="enter image description here"></p> <hr> <h2>Code</h2> <p>Until now, I had to iterate through the table data and manually add the artists to the array.</p> <pre><code>NSMutableArray *songsAndArtists = [NSMutableArray array]; Artist *artist; for (Song *song in self.songs) { if (artist != song.artist) { artist = song.artist; [songsAndArtists addObject:artist]; } [songsAndArtists addObject:song]; } </code></pre> <hr> <p>This can be really slow if you have 1'000 - 5'000 songs.<br /> I haven't really figured out how I could speed up this process.</p> <p>Does anybody have an idea how to calculate this at runtime?</p> <hr> <h2>EDIT</h2> <p>I'll try to clarify what I meant:</p> <p><code>NSTableView</code> supports <strong>group rows</strong>. My table view displays all the songs in CoreData. I'd like to use the group rows to display the artist of the songs, like in the print screen I added above.</p> <p>To do this I have to provide an array with an artist, followed by it's songs, followed by the next artist, and so on.</p> <p>The code above shows how to insert the artists, but it's a pretty time-consuming process.</p> <p>So my question, how can I speed this up?</p> <hr> <h2>HINT</h2> <p>Like <a href="https://stackoverflow.com/users/210171/nielsbot">nielsbot</a> and <a href="https://stackoverflow.com/users/742584/feloneous-cat">Feloneous Cat</a> suggested, iterating through all the artists won't work for me.</p> <p>The user also has the option to search though the library. Therefore, not all the songs should actually appear in the list.</p> <hr> <h2>Solution</h2> <p>I just want you to let you know what the problem was:</p> <p>The problem was, that I actually compared via <code>NSString</code> in the previous version.<br /> Pretty stupid fault...</p> <p>It takes about <strong>0.1 seconds or less</strong> which is great:</p> <pre><code>tableData = [self addGroupRowsToArray:[self allSongs] withKeyPath:@"artist"]; - (NSArray *)addGroupRowsToArray:(NSArray *)array withKeyPath:(NSString *)keyPath { NSMutableArray *mixedArray = [NSMutableArray array]; id groupRowItem; for (id arrayItem in array) { if (groupRowItem != [arrayItem valueForKeyPath:keyPath]) { groupRowItem = [arrayItem valueForKeyPath:keyPath]; [mixedArray addObject:groupRowItem]; } [mixedArray addObject:arrayItem]; } return mixedArray; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload