top of page

NSManagedObjectContext().refreshAllObjects()

Persist or cache data on a single device or sync data to multiple devices with CloudKit.


Many developers for Apple's platform don't reach this point. You typically arrive here with a mature application that has some customers, ideally. Projects that are merely proofs of concept or MVPs might be far from implementing an offline feature, or perhaps not.


So, what does the refreshAllObjects() method do? When you invoke this method, it resets all managed objects currently registered with the managed object context. This discards any unsaved changes and fetches the latest values from their persistent store.


This method proves beneficial when you have multiple contexts and aim to ensure changes made in one context are mirrored in another. For instance, you might have a background context updating data from a remote server. In such cases, it's essential to ensure that the main context, which displays the data to users, remains current.


However, it's vital to understand that calling refreshAllObjects can impact performance. This is because it prompts all registered objects to be refetched from their persistent store. Hence, you should employ this method judiciously, ensuring your app's data remains updated, but without compromising efficiency.


let contextToUse = newBackgroundContext

await contextToUse.perform {
	// perform work
	try contextToUse.save()
}

viewContext.refreshAllObjects()

bottom of page