检查是否在特定日期添加了领域数据 [英] Check if Realm data has been added on a specific date

查看:81
本文介绍了检查是否在特定日期添加了领域数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在特定日期注册了任何锻炼,我正在尝试创建一个查找.

I am trying create a lookup if there is any workout registered on a specific date.

Object类如下:

The Object class looks like this:

class Workout: Object {

    @objc dynamic var date: Date?
    // List of exercises (to-many relationship)
    var exercises = List<Exercise>()

}

还有

class Exercise: Object {

    @objc dynamic var name: String?
    // List of sets (to-many relationship)
    var sets = List<Set>()
    var parentWorkout = LinkingObjects(fromType: Workout.self, property: "exercises")
}

在Realm中,我看到有一个注册的日期为2019-12-07 19:48:35 +0000;.因此,我要像这样在viewDidLoad中添加支票:

In Realm, I can see that there is one registered with the date 2019-12-07 19:48:35 +0000;. So I am adding a check in my viewDidLoad like this:

let nowDate = Date()
func checkIfWorkoutHasBeenRegistered() {// Check if there already exist a workout today
        let realm = try! Realm()

        let todaysWorkouts = realm.objects(Workout.self).filter("date = %@", nowDate)
        if todaysWorkouts.isEmpty {
            print("No workout found")
        } else {
            print("Workout has been created")
        }
    }

但是它给了我输出No workout found,甚至以为我今天已经注册了锻炼.有提示吗?

But it gives me output No workout found, even thought I have registered a workout today. Any tips?

推荐答案

使用当前谓词,您正在将保存日期和时间与当前日期和时间进行比较,这肯定会有所不同,因为即使相差不到一秒将使他们不平等.相反,您可能想查看保存的日期是否在某个范围内.例如,如果您想查看所有具有今天"出现的date的对象,则可以创建一个谓词,例如:

With your current predicate you're comparing the save date and time to current date and time which are certainly going to be different because even a fraction of a second difference is going to make them unequal. Instead you likely want to see if the saved date falls within a some range. For example, if you wanted to see all objects that have a date that occurred "today," you could create a predicate like:

let startOfDay = Calendar.current.startOfDay(for: Date())
let endOfDay = Calendar.current.date(byAdding: .day, value: 1, to: startOfDay) ?? Date()

let predicate = NSPredicate(format: "date >= %@ && date < %@", startOfDay as NSDate, endOfDay as NSDate)
let todaysWorkouts =  realm.objects(Workout.self).filter(predicate)

这篇关于检查是否在特定日期添加了领域数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆