Search code examples
iosswiftcore-datanspredicatereduce

Comparing strings with NSPredicate before saving to Core Data


I am trying to perform a string comparison before saving to Core Data.

The string that gets saved to Core Data will contain a list of physical exercises. The string of exercises must only get saved once regardless of order.

Example:

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.

My progress:

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)")
    }
}

In my code, I am trying to compare the fetched result (string) in Core Data, with the new string I am attempting to save.

My problem is I keep getting 0 - which is causing the save attempt to fail every time.

How can I compare a string that I am trying to save, with a string that occurs in Core Data?


Solution

  • Assuming your sortedComponents is of type String, perhaps you can try this:

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

    But, if your sortedComponents is of type [String] the code in the question should already work, just make sure that you save to core data the exerciseGroup that is already sorted.