CoreData by Tutorial v3: Chapter 2: results is empty

I’m at page 52 of the Swift 3 version of the book and when executing the fetch, results is empty.

    // insert sample data
    let request = NSFetchRequest<Bowtie>(entityName: "Bowtie")
    let firstTitle = segmentedControl.titleForSegment(at: 0)!
    print("searchKey is: \(firstTitle)")
    request.predicate = NSPredicate(format: "searchKey == %@", firstTitle)
    do {
      let results = try managedContext.fetch(request)
      if results.count > 0 {
        populate(bowtie: results.first!)
      } else {
        print("ERROR: fetch results is empty")
    } catch let error as NSError {
      print("Could not fetch: \(error), \(error.userInfo)")

The console print ERROR: fetch results is empty. I checked that the sample data was inserted into the context and that the save did not result in an error:

  func insertSampleData() {
    let fetch = NSFetchRequest<Bowtie>(entityName: "Bowtie")
    fetch.predicate = NSPredicate(format: "searchKey != nil")
    let count = try! managedContext.count(for: fetch)
    if count > 0 {
      // sample data is already loaded
    let path = Bundle.main.path(forResource: "SampleData", ofType: "plist")
    let dataArray = NSArray(contentsOfFile: path!)!
    for dict in dataArray {
      let entity = NSEntityDescription.entity(forEntityName: "Bowtie", in: managedContext)!
      let bowtie = Bowtie(entity: entity, insertInto: managedContext)
      let btDict = dict as! [String:AnyObject]
    = btDict["name"] as? String
      print("\( is being inserted")
      bowtie.searchKey = btDict["seachKey"] as? String
      bowtie.rating = btDict["rating"] as! Double
      let colorDict = btDict["tintColor"] as! [String:AnyObject]
      bowtie.tintColor = UIColor.color(dict: colorDict)

      let imageName = btDict["imageName"] as? String
      let image = UIImage(named: imageName!)
      let photoData = UIImagePNGRepresentation(image!)!
      bowtie.photoData = NSData(data: photoData)
      bowtie.lastWorn = btDict["lastWorn"] as? NSDate
      let timesNumber = btDict["timesWorn"] as! NSNumber
      bowtie.timesWorn = timesNumber.int32Value
      bowtie.isFavorite = btDict["isFavorite"] as! Bool

    do {
      print("context saved successfully")
    } catch let error as NSError {
      print("Could not save data: \(error), \(error.userInfo)")

And each sample tie is inserted and I get the context saved successfully report in the console. I’m not sure what I’m missing here so any help would be appreciated!


Found my error with a little Kaleidoscope magic. Typo (visible in the above code) in btDict["searcKey"] .