Chapter 4: Intermediate Fetching Confusing moment

Hi everyone! In the stater pack application appdelegate.swift file author using that function

func importJSONSeedDataIfNeeded() {
let fetchRequest = NSFetchRequest(entityName: “Venue”)
let count = try! coreDataStack.managedContext.count(for: fetchRequest)

guard count == 0 else { return }

do {
  let results = try coreDataStack.managedContext.fetch(fetchRequest)
  results.forEach({ coreDataStack.managedContext.delete($0) })
  
  coreDataStack.saveContext()
  importJSONSeedData()
} catch let error as NSError {
  print("Error fetching: \(error), \(error.userInfo)")
}

} PLEASE answer to me anyone why author employing those lines???
let results = try coreDataStack.managedContext.fetch(fetchRequest)
results.forEach({ coreDataStack.managedContext.delete($0) })
Aren’t they extra? Thanks for everyone who responds =))

@simons1994 Thanks very much for your question! I honestly don’t think the lines you’ve pointed out are redundant or “extra”. Outside of the do/catch block, you’re declaring WHAT the fetchRequest is, and then inside the do/catch block, you actually PERFORM the fetchRequest, and do whatever work you want to do with the results that are returned. I hope this makes sense :slight_smile:

All the best!

Thanks for your answer! Im really appreciated time you’ve spent to read and answer my question)
But my question is not about what is it goin’ during the method, my question is about why do we delete results fetched from context WHEN count == 0? isn’t there’s already nothing to delete? why author doing it when count == 0 ???

please i really can’t get why for several days(((

You are correct.

Before importing the seed data, what needs to delete are records of other entities (Category, Location, PriceInfo, and Stats) other than Venue.

thank you! you gave me some food for thought:+1:

This topic was automatically closed after 166 days. New replies are no longer allowed.