14

I have a NSArrayController and a NSTableView. They show tracks from iTunes. I can sort the list by clicking in the header.

Is there a way to set up a default sort descriptor for the table view so it sorts for albums every time the user launches the app?

I tried to set the sortDescriptor on the array controller and the table view but that changes nothing.

Thank you

Edit: The answer is right. But it needs a NSArray:

- (NSArray *)mainSortDescriptor {

    return [NSArray arrayWithObjects:
            [NSSortDescriptor sortDescriptorWithKey:@"album" ascending:YES], 
            [NSSortDescriptor sortDescriptorWithKey:@"trackNumber" ascending:YES], 
            nil];

}

david
  • 3,553
  • 4
  • 28
  • 39

2 Answers2

13

If you want to bind the array controller's sort descriptor, you have to bind it to something. You can put this in your application delegate, for example:

- (NSArray *)tracksSortDescriptors {
    return [NSArray arrayWithObject:
             [NSSortDescriptor sortDescriptorWithKey:@"albumName"
                                           ascending:YES]];
}

Then you can set up the binding in IB as

Bind to: MyAppDelegate  
Model Key Path: tracksSortDescriptors

EDITED. I forgot, when translating this from PyObjC, that I was returning a list. Oops.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Thats right. I tried something similar but it didn't work. Now it works. Thanks – david Apr 07 '11 at 14:10
  • 1
    @Josh Caswell I get the following error: [ valueForUndefinedKey:]: this class is not key value coding-compliant for the key tracksSortDescriptors. Any ideas? – Dom Vinyard Oct 23 '12 at 16:36
  • @DomVinyard You've bound to the view controller instead of app delegate. No problem, simply implement the method `tracksSortDescriptors ` in your view controller instead. – Lars Blumberg Mar 10 '16 at 09:49
5

I tried this, didn't quite work - resorted on each app start, but not while the app was running.

Eventually, I noticed that in my NSArrayController object, the following box was unticked (argh!):

"Auto rearrange content"

...so, FYI to anyone who has the same problem: make sure that box is ON :)

Adam
  • 32,900
  • 16
  • 126
  • 153