NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

UserDefaults in a CoreData class, refresh issue.

Forums > SwiftUI


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


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,



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:, not a CoreData class named userDefaults :-)


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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.