Here are some commonly asked Core Data interview questions, categorized for different levels of expertise.
Basic Questions
-
What is Core Data in iOS?
- Core Data is Apple’s framework for managing an object graph and persisting data in an iOS/macOS app. It helps in storing, retrieving, and managing structured data efficiently.
-
What are the main components of Core Data?
- NSManagedObjectContext: Manages object lifecycle and changes.
- NSPersistentContainer: Manages the Core Data stack (since iOS 10).
- NSManagedObjectModel: Defines data structure (entities, attributes, relationships).
- NSPersistentStoreCoordinator: Handles communication between context and persistent store.
- NSManagedObject: Represents a single record in Core Data.
-
How is Core Data different from SQLite?
- Core Data is an object graph management framework, while SQLite is a database.
- Core Data provides features like caching, relationships, and undo/redo, whereas SQLite requires manual queries.
-
How do you add Core Data to a new/existing iOS project?
- Select “Use Core Data” when creating a new project.
- For existing projects:
- Add
CoreData.framework
. - Create a
.xcdatamodeld
file. - Set up
NSPersistentContainer
inAppDelegate
orSceneDelegate
.
- Add
Intermediate Questions
-
How do you perform CRUD operations in Core Data?
-
Create:
let entity = User(context: context) entity.name = "Mike" try? context.save()
-
Read:
let fetchRequest: NSFetchRequest<User> = User.fetchRequest() let users = try? context.fetch(fetchRequest)
-
Update:
user.name = "Michael" try? context.save()
-
Delete:
context.delete(user) try? context.save()
-
Create:
-
What is
NSFetchedResultsController
?- A controller that efficiently fetches and monitors changes in data, typically used with
UITableView
orUICollectionView
for automatic updates.
- A controller that efficiently fetches and monitors changes in data, typically used with
-
How do you perform batch updates in Core Data?
let batchUpdateRequest = NSBatchUpdateRequest(entityName: "User") batchUpdateRequest.propertiesToUpdate = ["name": "Updated Name"] batchUpdateRequest.resultType = .updatedObjectsCountResultType let result = try? context.execute(batchUpdateRequest) as? NSBatchUpdateResult
-
What is an
NSPersistentContainer
?- Introduced in iOS 10, it simplifies Core Data stack management.
let container = NSPersistentContainer(name: "MyApp") container.loadPersistentStores { _, error in if let error = error { fatalError("Failed to load: \(error)") } }
Advanced Questions
-
What is the difference between
privateQueueConcurrencyType
andmainQueueConcurrencyType
?-
mainQueueConcurrencyType
: Used for UI-related tasks. -
privateQueueConcurrencyType
: Used for background operations.
-
-
How to handle Core Data concurrency?
- Use background contexts with
perform
orperformAndWait
:
backgroundContext.perform { let newUser = User(context: backgroundContext) newUser.name = "Async User" try? backgroundContext.save() }
- Use background contexts with
-
What is Core Data Migration?
- When a data model changes (e.g., adding a new attribute), Core Data migrations ensure smooth transitions without data loss.
-
How do you handle Core Data multi-threading issues?
- Use multiple contexts: One for the main thread, one for background tasks.
-
Never pass managed objects between threads; instead, pass object IDs:
let objectID = user.objectID backgroundContext.perform { let backgroundUser = backgroundContext.object(with: objectID) backgroundUser.name = "Updated in Background" try? backgroundContext.save() }
Scenario-Based Questions
-
How would you optimize Core Data performance?
- Use
NSBatchInsertRequest
for bulk inserts. - Use
NSPersistentContainer
for background operations. - Fetch only required attributes (
fetchRequest.propertiesToFetch
). - Use indexing in the data model.
- Avoid retaining
NSManagedObject
instances for too long.
- Use
-
How do you debug Core Data issues?
- Enable SQL debugging:
UserDefaults.standard.set(true, forKey: "com.apple.CoreData.SQLDebug")
- Use
Faulting
to fetch only necessary data. - Check logs for errors in
NSPersistentStoreCoordinator
.
- Enable SQL debugging:
-
What happens if two different contexts modify the same object?
- Core Data resolves conflicts using merge policies:
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
- Core Data resolves conflicts using merge policies: