检查核心数据中是否存在记录

时间:2018-08-15 16:29:02

标签: swift core-data

当我从核心数据中获取记录时,我正在寻找abreak是否为空或为零。以前运行我的应用程序时,系统提示我abreak为零。要解决此问题,我想检查它是否为nil以及输出为0。

到目前为止,这是我的代码:

func fetchCards() {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Date")
    let sort = NSSortDescriptor(key: #keyPath(Date.date), ascending: true)
    fetchRequest.sortDescriptors = [sort]

    do {
        cards = try managedContext.fetch(fetchRequest)
        for card in cards as [NSManagedObject] {
            let time1 = card.value(forKey: "startTime") as! String
            let time2 = card.value(forKey: "endTime") as! String
            let abreak = card.value(forKey: "abreak") as! Int
            var hours = ""

            if abreak == nil {
                self.breaks.append(0)
                hours = calcTime(time1: time1, time2: time2)
            } else {
                self.breaks.append(card.value(forKey: "abreak") as! Int)
                let time3 = Int(time2)! - abreak
                hours = calcTime(time1: time1, time2: "\(time3)")
            }


            self.hours.append(hours)
        }
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }

}

我遇到错误“将'Int'类型的非可选值与nil进行比较,总是返回false。”还有另一种解决方法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用guard let or if let来代替time1,time2,abreak。

 for card in cards as [NSManagedObject] {
                guard let time1 = card.value(forKey: "startTime") else {return}
                guard let time2 = card.value(forKey: "endTime") else {return}
                guard let abreak = card.value(forKey: "abreak") else {return}
                var hours = ""

                if abreak == nil {
                    self.breaks.append(0)
                    hours = calcTime(time1: time1, time2: time2)
                } else {
                    self.breaks.append(card.value(forKey: "abreak") as! Int)
                    let time3 = Int(time2)! - abreak
                    hours = calcTime(time1: time1, time2: "\(time3)")
                }


                self.hours.append(hours)

答案 1 :(得分:0)

如果abreak可以是nil,则必须有条件下放到Int

let abreak = card.value(forKey: "abreak") as? Int

或者写起来更方便

    ....
    var hours = ""

    if let abreak = card.value(forKey: "abreak") as? Int {
        self.breaks.append(abreak)
        let time3 = Int(time2)! - abreak
        hours = calcTime(time1: time1, time2: "\(time3)")
    } else {
        self.breaks.append(0)
        hours = calcTime(time1: time1, time2: time2)
    }
    ....

基本上,强烈建议使用NSManagedObject子类和点表示法,而不要使用原始的KVC方法。