3

I'm trying to figure go to set sort descriptor in binding for NSArrayController but I have not be able to find a example of how to do it.

I have a NSArrayController bind it to core data and I want to sort the data. My question is how I can do this using bindings:

enter image description here I'll really appreciate if

user2924482
  • 8,380
  • 23
  • 89
  • 173

3 Answers3

3

Assuming that you would like to sort the data by artistName ( in descending and not concerned about the case sensitivity), you can do like this

func sortByName() -> [NSSortDescriptor] {
    return [NSSortDescriptor(key: "artistName", ascending: false, selector: #selector(NSString.caseInsensitiveCompare))]
}

Within the "Sort Descriptors" section of the binding, specify this method name as part of the Model Key PathsortDescriptionSection

1

I think you mean you want to enter the sort descriptor directly in the NIB. You can't do that.

Bindings allow you to connect the array controller's sortDescriptors property to a property of some other controller object so that they stay in sync. That is, you would need some object to implement a property which is an indexed collection (like an array) of NSSortDescriptor object. This would likely be the window or view controller. Then, you could bind the array controller's Sort Descriptors binding to that object with the key path naming that property.

That doesn't let you set the sort descriptors themselves in the NIB.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
0

After check @user1751240 answer on Swift5.2 & Xcode12.2 I can offer 2 ways to solve the initial issue:

  1. By code:
   // Directly after arrayController will init
   override func awakeFromNib() {
        super.awakeFromNib()

        let descriptors = [NSSortDescriptor(key: "artistName",
                                            ascending: false,
                                            selector: #selector(NSString.caseInsensitiveCompare))]
        arrayController.sortDescriptors = descriptors
    }
  1. From nib:
    @objc
    var sortByName: [NSSortDescriptor] {
        [NSSortDescriptor(key: "artistName",
                          ascending: false,
                          selector: #selector(NSString.caseInsensitiveCompare))]
    }

Screenshot from IB

WINSergey
  • 1,977
  • 27
  • 39