BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

Conditional saving of NSManagedObjectContext

Paul Hudson    @twostraws   

We’ve been using the save() method of NSManagedObjectContext to flush out all unsaved changes to permanent storage, but what we haven’t done is check whether any changes actually need to be saved. This is often OK, because it’s common to place save() calls only after we specifically made a change such as inserting or deleting data.

However, it’s also common to bulk your saves together so that you save everything at once, which has a lower performance impact. In fact, Apple specifically states that we should always check for uncommitted changes before calling save(), to avoid making Core Data do work that isn’t required.

Fortunately, we can check for changes in two ways. First, every managed object is given a hasChanges property, that is true when the object has unsaved changes. And, the entire context also contains a hasChanges property that checks whether any object owned by the context has changes.

So, rather than call save() directly you should always wrap it in a check first, like this:

if moc.hasChanges {
    try? moc.save()
}

It’s a small change to make, but it matters – there’s no point doing work that isn’t needed, no matter how small, particularly because if you do enough small work you realize you’ve stacked up some big work.

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.