-1

I am extracting data from the past week using CoreData. It all works fine for days when some data is stored. However, when no data is stored, the program crashes. How can I handle this error?

    for i in 0...6 { // Get every day in the past week
        let appDel = (UIApplication.sharedApplication().delegate as! AppDelegate)
        let context: NSManagedObjectContext = appDel.managedObjectContext
        let request = NSFetchRequest(entityName: "Pulser")
        request.returnsObjectsAsFaults = false

        let calendar = NSCalendar.currentCalendar()
        let now = NSDate()
        let beginningOfToday = calendar.startOfDayForDate(now)
        let previousDay = calendar.startOfDayForDate(calendar.dateByAddingUnit(.Day, value: -i, toDate: beginningOfToday, options: [])!)
        let previousPreiviousDay = calendar.startOfDayForDate(calendar.dateByAddingUnit(.Day, value: -i - 1 , toDate: beginningOfToday, options: [])!)

         request.predicate = NSPredicate(format:"(date >= %@) AND (date < %@)", previousPreiviousDay, previousDay)

        do {
            let results = try context.executeFetchRequest(request)  as! [Pulser]
            pulseArray.append(meanValue(results)) // if more than one value stored for each day, take the mean value of it

        }
        catch let error as NSError {
            print(error)
        }
    }
Nils
  • 313
  • 1
  • 2
  • 14
  • 2
    Check if `results` is not empty ...? (An empty result set is not an error.) – Martin R Feb 17 '16 at 15:17
  • 2
    Check if `results` is empty. And it's not very efficient to retrieve the same context, the calendar and `now` 6 times in the repeat loop. – vadian Feb 17 '16 at 15:17
  • Use `NSCompoundPredicate` to avoid the 6 fetches in order to do only one as suggested by @vadian – Larme Feb 17 '16 at 15:25

1 Answers1

0

It works like a charm now, thanks.

 if results.count > 0 {
            pulseArray.append(meanValue(results)) 

  }
Nils
  • 313
  • 1
  • 2
  • 14