1

i have this code in swift:

lists = sharedAppCore.getRealm().objects(Event).filter("status = 1 OR status = 2").sorted("end_date", ascending: false)

now i want to filter with start_date NSDate() but this not work:

lists = sharedAppCore.getRealm().objects(Event).filter("status = 1 OR status = 2 OR start_date >= \(NSDate())").sorted("end_date", ascending: false)

any ideas?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Luca Becchetti
  • 1,210
  • 1
  • 12
  • 28
  • Maybe related: http://stackoverflow.com/questions/29095950/swift-filter-by-nsdate-object-property – Larme Feb 05 '16 at 15:13

2 Answers2

1
lists = sharedAppCore.getRealm()
    .objects(Event)
    .filter("status = 1 OR status = 2 OR start_date >= \(NSDate())")
    .sorted("end_date", ascending: false)

Strictly speaking, Above code is not the same as your final code.

filter("status = 1 OR status = 2").filter(predicate).sorted("end_date", ascending: false)

^ Because this predicate same as the following:

filter("(status = 1 OR status = 2) AND end_date >= %@", NSDate())

If you create predicate as all OR, you can just do the following:

filter("status = 1 OR status = 2 OR end_date >= %@", NSDate())

Additionally, if you compare without hours, you should truncate hours from the date first. Then compare with the truncated date.

Like the following:

let now = NSDate()

let calendar = NSCalendar.currentCalendar()
let component = calendar.components([.Year, .Month, .Day], fromDate: now)

let today = calendar.dateFromComponents(component)! // truncated time

Then use truncated date to compare in the predicate.

let now = NSDate()

let calendar = NSCalendar.currentCalendar()
let component = calendar.components([.Year, .Month, .Day], fromDate: now)

let today = calendar.dateFromComponents(component)! // truncated time

let lists = realm
    .objects(Event)
    .filter("status = 1 OR status = 2 OR end_date >= %@", today)
    .sorted("end_date", ascending: false)
kishikawa katsumi
  • 10,418
  • 1
  • 41
  • 53
0

solved with this code:

let predicate = NSPredicate(format: "end_date >= %@", NSDate())
lists = sharedAppCore.getRealm().objects(Event).filter("status = 1 OR status = 2").filter(predicate).sorted("end_date", ascending: false)
Luca Becchetti
  • 1,210
  • 1
  • 12
  • 28