如何查询特定对象的realm swift

时间:2017-04-20 20:39:21

标签: ios swift3 realm

编辑以简化我的问题...

我是Realm的新手,到目前为止,它非常酷,但我很难找到如何查询我的Realm DB以检查是否存在特定项目它

这是我的王国模式:

import Foundation
import RealmSwift

class ChartCount: Object{

    dynamic var date: Date = Date()
    dynamic var count: Int = Int(0)
}

在我的主ViewController中,我使用以下函数存储当前7周的一系列ChartCount对象:

// function to check if this weeks days have been created in Realm DB yet and creates them if not
    let realm = try! Realm()
    lazy var visitors: Results<VisitorCount> = { self.realm.objects(VisitorCount.self)}()
    let startOfWeekDate = Date().startOfWeek(weekday: 1)
    let nextDay = 24 * 60 * 60

    var startOfWeek = try! Realm().objects(VisitorCount.self)

func setThisWeeksDays(){
            if charts.count == 0 {
                try! realm.write() {


                    let defaultVisitorDates = [startOfWeekDate, startOfWeekDate + TimeInterval(nextDay), startOfWeekDate + TimeInterval(nextDay*2), startOfWeekDate + TimeInterval(nextDay*3), startOfWeekDate + TimeInterval(nextDay*4), startOfWeekDate + TimeInterval(nextDay*5), startOfWeekDate + TimeInterval(nextDay*6)]

                    for visitors in defaultChartrDates {
                        let newChartDate = ChartCount()
                        newChartDate.date = visitors
                        self.realm.add(newChartrDate)
                    }
                }

                visitors = realm.objects(ChartCount.self)
            }
        }

这就是创建StartOfWeekDate

// Finds the start/end of the current week ----------------------------------------------- //
extension Date {
    func startOfWeek(weekday: Int?) -> Date {
        var cal = Calendar.current
        var component = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
        component.to12am()
        cal.firstWeekday = weekday ?? 1
        return cal.date(from: component)!
    }

    func endOfWeek(weekday: Int) -> Date {
        let cal = Calendar.current
        var component = DateComponents()
        component.weekOfYear = 1
        component.day = -1
        component.to12pm()
        return cal.date(byAdding: component, to: startOfWeek(weekday: weekday))!
    }

    func monthDay() -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd"
        return dateFormatter.string(from: self)
    }
}
internal extension DateComponents {
    mutating func to12am() {
        self.hour = 0 + 24
        self.minute = 0
        self.second = 0
    }

    mutating func to12pm(){
        self.hour = 0
        self.minute = 0
        self.second = 0
    }
}// </end> Finds the start/end of the current week ------------------------------------------ //

我想做的就是查看“约会”日期&#39;我的ChartDate模型的列,以查看其中是否有包含本周第一天的对象(例如startOfWeekDate)。

3 个答案:

答案 0 :(得分:2)

您无法在初始化程序中访问Realm,但您已在代码中获得答案。像对访问者一样使周延迟开始,直到它被使用,并且在你的init完成时它将不会被初始化。这是大多数领域示例的完成方式。

lazy var startOfWeek: Result<ChartCount> = {
    return realm.objects(ChartCount.self).filter("date = 'startOfWeekDate'")
}()

或者,您可以将周开始作为隐式展开的可选项并在viewDidLoad中初始化它或者只是使其成为常规可选

var startOfWeek: Result<ChartCount>!
...
//ViewDidLoad
realm.objects(ChartCount.self).filter("date = 'startOfWeekDate'")

答案 1 :(得分:0)

好的,我想我已经开始工作了。这就是我所做的:

要检查Realm DB是否具有startOfWeekDate记录,我创建了此函数:

func searchForStartOfWeek(findDate: Date) -> ChartCount?{
        let predicate = NSPredicate(format: "date = %@", findDate as CVarArg)
        let dateObject = self.realm.objects(ChartCount.self).filter(predicate).first

        if dateObject?.date == findDate{
            return dateObject
        }
        return nil
    }

然后我用它来检查它是否存在:

func setThisWeeksDays(){
        if searchForStartOfWeek(findDate: startOfWeekDate) == nil {
            try! realm.write() {


                let defaultChartDates = [startOfWeekDate, startOfWeekDate + TimeInterval(nextDay), startOfWeekDate + TimeInterval(nextDay*2), startOfWeekDate + TimeInterval(nextDay*3), startOfWeekDate + TimeInterval(nextDay*4), startOfWeekDate + TimeInterval(nextDay*5), startOfWeekDate + TimeInterval(nextDay*6)] // 3

                for charts in defaultChartDates {
                    let newChartDate = ChartCount()
                    newChartDate.date = charts
                    self.realm.add(defaultChartDates)
                }
            }

            visitors = realm.objects(ChartCount.self)
        }
    }

感谢大家的帮助!

答案 2 :(得分:0)

对于希望通过主键访问Realm对象的人(就像我以前一样),下面是代码:

let specificPerson = realm.object(ofType: Person.self, forPrimaryKey: myPrimaryKey)