Core Data Guide

💿 Core Data — Batch Insertion

Rajai Kumar
Nerd For Tech
Published in
2 min readDec 19, 2022

--

Credits: developer.apple.com

Adding bulk data at once to your database is required for almost all projects. In my case it will mostly be downloading user data when installing in a new device.

I have seen some new developers including me using for-loop for taking objects one by one from the array then add it to the context.

Credits: canva

Okay, let’s get to the code.

Example:

/// Create Batch Insert Request
let insertRequest = NSBatchInsertRequest(entity: BookKeeper.entity(), objects: booksArray)
/// Set the Result Type, in our case we need object IDs
insertRequest.resultType = NSBatchInsertRequestResultType.objectIDs
/// Execute the request using the background context already created.
let result = try? bgContext().execute(insertRequest) as? NSBatchInsertResult
/// Finally we merge using the objectIDs we got from the results.
if let objectIDs = result?.result as? [NSManagedObjectID], !objectIDs.isEmpty {
let save = [NSInsertedObjectsKey: objectIDs]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: save, into: [mainContext])

Steps:

  1. Create a NSBatchInsertRequest with entity description we get from NSManagedObject and objects array converted to dictionary.
  2. Set result type to the NSBatchInsertRequest we created as objectIDs
  3. Execute the request using the background context(Create background context with NSMergeByPropertyObjectTrumpMergePolicy).
  4. Merge changes using NSManagedObject.mergeChanges with changeNotificationData into the main context in an array.

It might be confusing with just this information. Please refer to the sample project given below.

📁 File with batch insertion code

🗄️ Repo

📰 My other articles related to Core Data

  1. Core Data Fetch Index for faster searches.
  2. Core Data Fetch Request template

--

--

Rajai Kumar
Nerd For Tech

I’m a workaholic iOS developer. I focus a lot on UX and product efficiancy.