Swift 核心数据 NSPredicate 静态字符串问题
Swift Core Data NSPredicate static string issue
我想让谓词更灵活地进行更改。我在源代码中有很多这样的字符串:
let predicate = NSPredicate(format: "bodyPart.name = %@", name)
let filteredExercises = ExerciseEntity.mr_findAll(with: predicate)
但是如你所见,如果有一天我将 BodyPart 名称更改为 MuscleGroup,它会导致如下问题:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath bodyPart.name not found in entity <NSSQLEntity ExerciseEntity id=5>'
我正在寻找关键路径如
的解决方案
let predicate = NSPredicate(format: "%@ = %@", \BodyPart.name, name)
使用 %K 替换密钥路径
let predicate = NSPredicate(format: "%K = %@", #keyPath(BodyPart.name), name)
我想让谓词更灵活地进行更改。我在源代码中有很多这样的字符串:
let predicate = NSPredicate(format: "bodyPart.name = %@", name)
let filteredExercises = ExerciseEntity.mr_findAll(with: predicate)
但是如你所见,如果有一天我将 BodyPart 名称更改为 MuscleGroup,它会导致如下问题:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath bodyPart.name not found in entity <NSSQLEntity ExerciseEntity id=5>'
我正在寻找关键路径如
的解决方案let predicate = NSPredicate(format: "%@ = %@", \BodyPart.name, name)
使用 %K 替换密钥路径
let predicate = NSPredicate(format: "%K = %@", #keyPath(BodyPart.name), name)