Aiden
Aiden

Reputation: 103

CoreData conditionally fetching on NSDate using NSPredicate (swift)

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

Upvotes: 3

Views: 3414

Answers (2)

Adrian
Adrian

Reputation: 16735

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])

Upvotes: 5

V-Xtreme
V-Xtreme

Reputation: 7333

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

Upvotes: 0

Related Questions