使用NSDate()进行域查询时出错

时间:2016-02-05 15:08:39

标签: swift realm

我在swift中有这个代码:

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

现在我想用start_date NSDate()进行过滤,但这不起作用:

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

任何想法?

2 个答案:

答案 0 :(得分:1)

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

严格来说,上面的代码与最终代码不同。

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

^因为这个谓词与以下内容相同:

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

如果您将谓词创建为全部OR,则可以执行以下操作:

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

此外,如果您在没有小时数的情况下进行比较,则应从截止日期开始截断小时数。然后与截断日期进行比较。

如下所示:

let now = NSDate()

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

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

然后使用截断日期在谓词中进行比较。

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)

答案 1 :(得分:0)

用这段代码解决了:

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)