LAST CHANCE: Save 50% on all my Swift books and bundles! >>

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 Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot 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.