Why do I need a countForFetchRequest once the data is loaded?

Hey,

Regarding Chapter 2, Section “Propogating a managed context”. My question is to do with why I can’t comment out insertSampleData after running the app once. The data is inserted into CoreDate, but I still need to run the func InsertSampleData. Presumably because something in the first bit of code, which just counts the number of objects in the request, is needed.

func insertSampleData()
{
// check CData for entries (and end here if there are)
let fetchRequest = NSFetchRequest(entityName: “Bowtie”)
fetchRequest.predicate = NSPredicate(format: “searchKey != nil”)
let count = managedContext.countForFetchRequest(fetchRequest, error: nil)
if count > 0 { return }
…}

Could you please clarify why it appears that I need to run this code before I can successfully executeFetchRequest from CoreData?

Thanks!

The reason why you insert sample data is because when an app is new, there is no data in your dB. You insert dummy data so that your search won’t come up empty. Alas you only need to do this once. You could do it everytime but it would be rather silly.

Indeed, I get that you insert sample data. Never mind.