3

Basically I have an entity called TimeLoc that has three attributes: time, latitude and longitude. And their types are Date, Double and Double respectively. I got stuck when I was trying to make a request with filter on attribute time.

Here is my code:

...
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) 
var context: NSManagedObjectContext = self.managedObjectContext!
var request = NSFetchRequest(entityName: "TimeLoc")
var endTime = NSDate()
var startTime = NSDate(timeIntervalSinceNow: -65)
let predicate = NSPredicate(format: "time>= \(startTime) AND time<= \(endTime)")
request.predicate = predicate
var results: NSArray = context.executeFetchRequest(request, error: nil)!
...

And I got the following error: 'Unable to parse the format string "time>= 2015-07-14 03:24:03 +0000 AND time<= 2015-07-14 03:25:08 +0000"'

How should I fix this? I have googled a bit but all the solutions I found were in Objective-C. It would be great if someone can answer me in Swift.

Edit: As V-Xtreme suggested, an answer to this problem can be find in Glauco Neves's answer to this question

Community
  • 1
  • 1
Aiden
  • 93
  • 1
  • 2
  • 8

2 Answers2

5

The accepted solution did not work for me, though it made intuitive sense. As an alternative, I created a predicate so search a range, like so:

"%K BETWEEN {%@, %@}" where %K is my key path, and the two %@s are my start and end dates.

let datePredicate = NSPredicate(format: "%K BETWEEN {%@, %@}", argumentArray: [#keyPath(Activity.startTime), startDate!.startOfDay, endDate!.endOfDay])
Adrian
  • 16,233
  • 18
  • 112
  • 180
0

I guess you are sending parameters to the predicate in NSDate format :

let predicate = NSPredicate(format: "time>= \(startTime) AND time<= \(endTime)")

Here your startTime and endTime is of type NSDate . Try to convert it in String format and pass it to the predicate . It should work .

Reference : NSPredicate: filtering objects by day of NSDate property

Community
  • 1
  • 1
V-Xtreme
  • 7,230
  • 9
  • 39
  • 79
  • Thank you@V-Xtreme. I tried `let predicate = NSPredicate(format: "time>= '\(startTime)' AND time<= '\(endTime)'")`. But I got a new error, '-[__NSCFString timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x7fb889fd6dc0'. – Aiden Jul 14 '15 at 04:32
  • It solved the 'Unable to parse the format string' error. But got a more confusing error. please see the first comment, I edited it. @V-Xtreme. – Aiden Jul 14 '15 at 04:40