UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: CoreData, Dates, and DatePicker

Forums > SwiftUI

Dear all,

I wonder if there is a nicer/shorter option to use a SwiftUI DatePicker with Dates of a NSManagedObject than this one?

DatePicker("MyString", selection: Binding<Date>(get: {myObject.date ?? Date()}, set: {myObject.date = $0}), displayedComponents: .date)

or is this the intended way of doing it? The same goes for the other SwiftUI components which require a Binding. Of course, the date on the NSManagedObject is not a Binding and any other solution I searched for had more boilerplate around it to make it work. I haven't found any news on this in the WWDC 2021 videos, either.

Do you have any suggestions?

3      

Thats seems like a good solution if you don't want to add unwrapped properties to an extension on your NSManagedObject, like this:

extension MyObject {
  var wrappedDate: Date {
    date ?? Date()
  }
}

I would, however, extract the Binding to a computed property like this:

var dateSelection: Binding<Date> {
  Binding {
    myObject.date ?? Date()
  } set {
    myObject.date = newValue
  }
}

You could create a property in the view that binds to the DatePicker, and on view initailisation and dismissal, connect that back to the NSManagedObject property. For example:

@State private var dateSelection: Date
...
init() {
  _dateSelection = State(wrappedValue: myObject.date ?? Date())
}
...
.onDisappear {
  myObject.date = dateSelection // do wherever suits you
}

Personally, I do a combination of the first and third, but it's up to you how you do it.

3      

Thank you for your suggestions. The second option for my NSManagedObject seems neat. Makes the call side in the DatePicker cleaner as well. I'll give it a try.

3      

thanks my issue has been fixed.

3      

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.