TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Sharing a background NSManagedObjectContext across a task group’s tasks?

Forums > Swift

I have to do a series of network operations to fetch some records and then update them in Core Data. First I make a network call that fetches 0 or more items, then I do a series of network calls for each of those items. I want to create (or update) Core Data entities for all the items in the first request, and then kick off the additional requests to fill out their details, but do those concurrently.

Can I share one background MOC for all of that, or does each task needs its own? Something like this:

try await withThrowingTaskGroup(of: Void.self)
{ inGroup in
    let moc = PersistenceController.shared.container.newBackgroundContext()
    let items = try await self.api.getItems()

    for item in items
    {
        //  Create or update the basic record…

        let mocItem = fetchOrCreateItem(withID: item.id, inMOC: moc)
        mocItem.update(from: item)
        try moc.save()

        //  Get details…

        inGroup.addTask
        {
            let details = try await self.api.getItemDetails(itemID: item.id)
            mocItem.udpateDetails(from: details)
            try moc.save()
        }
    }
}

My instincts tell me this is unsafe, but the compiler doesn’t warn me, and I actually can’t reliably test it (the service is one for which I only get a single item back).

3      

Hi! I think you might want to use perform func in moc. According to the documentation -> “Core Data has a function to help guarantee Core Data tasks always happen one after another in a serial queue…no matter where that task is added from. This function is called perform.” So this might help to avoid any unwanted behaviour with Core Data.

As for debugging, don't know if you already set it or not. But unfortunately, concurrency problems don’t always throw errors, yet they can cause problems in your app. To help with this, Xcode has a setting you can activate to have it alert you of concurrency problems.

  • Go to Edit Scheme
  • Add a new Environment Variable
  • Name: com.apple.CoreData.ConcurrencyDebug Value: 1”

So this should help you catch any possible bugs.

4      

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!

Reply to this topic…

You need to create an account or log in to reply.

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.