在保存到核心数据之前将字符串与 NSPredicate 进行比较
Comparing strings with NSPredicate before saving to Core Data
我正在尝试在保存到 Core Data 之前执行字符串比较。
保存到 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 中出现的字符串?
假设你的 sortedComponents
是 String
类型,也许你可以试试这个:
let sortedExerciseGroup = exerciseGroup.components(separatedBy: " ").sorted().joined(separator: " ")
let predicate = NSPredicate(format: "upperBody.sortedComponents == %@", sortedExerciseGroup)
但是,如果您的 sortedComponents
是 [String]
类型,则问题中的代码应该已经可以工作,只需确保将已排序的 exerciseGroup
保存到核心数据.
我正在尝试在保存到 Core Data 之前执行字符串比较。
保存到 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 中出现的字符串?
假设你的 sortedComponents
是 String
类型,也许你可以试试这个:
let sortedExerciseGroup = exerciseGroup.components(separatedBy: " ").sorted().joined(separator: " ")
let predicate = NSPredicate(format: "upperBody.sortedComponents == %@", sortedExerciseGroup)
但是,如果您的 sortedComponents
是 [String]
类型,则问题中的代码应该已经可以工作,只需确保将已排序的 exerciseGroup
保存到核心数据.