Bird
0
0

Identify the error in this Core Data setup code: let container = NSPersistentContainer(name: "Model") container.loadPersistentStores { storeDescription, error in if error != nil { print("Failed to load store") } } let context = container.viewContext context.perform { let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) newItem.setValue("Sample", forKey: "title") } context.save()

medium📝 Debug Q6 of 15
iOS Swift - Local Data Persistence
Identify the error in this Core Data setup code: let container = NSPersistentContainer(name: "Model") container.loadPersistentStores { storeDescription, error in if error != nil { print("Failed to load store") } } let context = container.viewContext context.perform { let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) newItem.setValue("Sample", forKey: "title") } context.save()
ANSPersistentContainer name is incorrect
Bcontext.save() is called outside perform block causing threading issue
CMissing error handling in loadPersistentStores
DEntity name "Item" does not exist
Step-by-Step Solution
Solution:
  1. Step 1: Analyze threading with context.perform

    Changes inside perform block run asynchronously; save() outside may run before changes applied.
  2. Step 2: Identify correct save usage

    Save should be called inside perform block to ensure changes are committed properly.
  3. Final Answer:

    context.save() is called outside perform block causing threading issue -> Option B
  4. Quick Check:

    Save must be inside perform block [OK]
Quick Trick: Call save() inside perform block to avoid threading bugs [OK]
Common Mistakes:
  • Calling save() outside perform block
  • Ignoring asynchronous context execution
  • Assuming loadPersistentStores error handling is missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes