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

UserDefaults in a CoreData class, refresh issue.

Forums > SwiftUI

Hi,

I have a CoreData class where I load a static var from UserDefaults. When the value of it changes, the display doesn't get refreshed except if I kill the app and reload. I understand why but I don't know how to solve this issue. Any idea?

Thanks Alessandro

3      

hi Alessandro,

  • don't know who @Amina3432 is or why he or his bot is spamming all these posts with suspicious links ...

if you have a display (View) that wants to be sensitive to changes in your user defaults (an entity in Core Data), just be sure you have a @FetchRequest tied to that entity, something like

@FetchRequest(entity: YourUserDefaultEntity.entity(), sortDescriptors: []) 
private var userDefaults: FetchedResults<YourUserDefaultEntity>

then you retrieve the values of the defaults from it (i am guessing there's only one such object)

let userFavoriteBookTitle = userDefaults[0].userFavoriteBookTitle ?? "Hacking With Swift"

any change to the user defaults entity such as

userDefaults[0].userFavoriteBookTitle = "Beyond Code" 

should trigger an update of the display.

hope that helps,

DMG

3      

Thanks DMG,

I retrieved the UserDefaults data directly in the class method and it works as expected now. I wanted to do it at the class level directly because it's a value shared by all the objects but I could not find any better solution. When I mentioned UserDefaults, I meant this one: https://developer.apple.com/documentation/foundation/userdefaults, not a CoreData class named userDefaults :-)

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.