Feb 16, 2025 iOS

Core Data Intrview question

Here are some commonly asked Core Data interview questions, categorized for different levels of expertise.


Basic Questions

  1. 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.
  2. 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.
  3. 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.
  4. How do you add Core Data to a new/existing iOS project?
    • Select “Use Core Data” when creating a new project.
    • For existing projects:
      1. Add CoreData.framework.
      2. Create a .xcdatamodeld file.
      3. Set up NSPersistentContainer in AppDelegate or SceneDelegate.

Intermediate Questions

  1. 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()
  2. What is NSFetchedResultsController?
    • A controller that efficiently fetches and monitors changes in data, typically used with UITableView or UICollectionView for automatic updates.
  3. 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
  4. 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

  1. What is the difference between privateQueueConcurrencyType and mainQueueConcurrencyType?
    • mainQueueConcurrencyType: Used for UI-related tasks.
    • privateQueueConcurrencyType: Used for background operations.
  2. How to handle Core Data concurrency?
    • Use background contexts with perform or performAndWait:
    backgroundContext.perform { let newUser = User(context: backgroundContext) newUser.name = "Async User" try? backgroundContext.save() }
  3. 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.
  4. 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

  1. 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.
  2. 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.
  3. What happens if two different contexts modify the same object?
    • Core Data resolves conflicts using merge policies: context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
Index