Core Data: Beyond the Basics

Jul 26 2022 · Swift 5.5, iOS 15, Xcode 13.3.1

Part 1: Fetching & Displaying Launches

05. Dynamically Adjust Sort Descriptors

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Filtering Using Predicates Next episode: 06. Modeling Relationships

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

While sort descriptors can be handy to initially sort data coming out of the persistent store, you might want to provide your user the chance to sort the data in real time as they use your app. Luckily some improvements to Core Data in recent years has made that possible. Both sort descriptors and predicates for fetch requests are accessible outside of the initial fetch request declaration and can be changed on the fly. Let’s add a sort button to the Launches view.

let sortTypes = [
    (name: "Name", descriptors: [SortDescriptor(\RocketLaunch.name, order: .forward)]),
    (name: "LaunchDate", descriptors: [SortDescriptor(\RocketLaunch.launchDate, order: .forward)])
  ]
@State var activeSortIndex = 0
.onChange(of: activeSortIndex) { _ in
      launches.sortDescriptors = sortTypes[activeSortIndex].descriptors
}
.toolbar {
  Menu(content: {
    Picker(
      selection: $activeSortIndex,
      content: {
        ForEach(0..<sortTypes.count, id: \.self) { index in
          let sortType = sortTypes[index]
          Text(sortType.name)
        }
      },
      label: {}
    )
  }, label: {
    Image(systemName: "line.3.horizontal.decrease.circle.fill")
  })
}