首页 > 解决方案 > 在保存到核心数据之前将字符串与 NSPredicate 进行比较

问题描述

我正在尝试在保存到核心数据之前执行字符串比较。

保存到 Core Data 的字符串将包含一个体育锻炼列表。不论顺序如何,这一系列练习只能保存一次。

例子:

let str1 = "Burpees Rowing Running"
// This is in Core Data

let str2 = "Running Rowing Burpees"
// This is an attempt to save to Core Data. It should *fail* because there is already an exercise set with these exercises - just not in the same order.

我的进步:

func checkEntityThenSave(exerciseGroup:String){
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "SavedExerciseSets")
    let predicate = NSPredicate(format: "upperBody.sortedComponents == %@", exerciseGroup.components(separatedBy: " ").sorted())
    
    request.predicate = predicate
    request.fetchLimit = 1

    do{
        let count = try context.count(for: request)
        
        print("Count - \(count)") // Always evaluates to 0

        if(count > 0){
            // Save to Core Data
        }
        else{
            // Show Alert
        }
      }
    catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

在我的代码中,我试图将 Core Data 中获取的结果(字符串)与我试图保存的新字符串进行比较。

我的问题是我一直得到 0 - 这导致每次保存尝试都失败。

如何将我尝试保存的字符串与 Core Data 中出现的字符串进行比较?

标签: iosswiftcore-datanspredicatereduce

解决方案


假设你sortedComponents是 type String,也许你可以试试这个:

let sortedExerciseGroup = exerciseGroup.components(separatedBy: " ").sorted().joined(separator: " ")
let predicate = NSPredicate(format: "upperBody.sortedComponents == %@", sortedExerciseGroup)

但是,如果您sortedComponents的类型[String]是问题中的代码应该已经可以工作,只需确保将exerciseGroup已排序的核心数据保存到核心数据中。


推荐阅读