我的初始化方法中有以下代码:

self.monitor = CoreStore.monitorSectionedList(
        From<ListEntityType>()
            .sectionBy(#keyPath(ListEntityType.muscle.name)) { (sectionName) -> String? in
                return "\(String(describing: sectionName)) years old"
            }
            .orderBy(.ascending(#keyPath(ListEntityType.muscle.name)), .ascending(\.name))
    )

我想以某种方式在运行时添加到此监视器.where条件。
ListEntityType是称为Exercise的实体的类型别名。因此,每个Exercise都包含一对一的关系Muscle(exercise.muscle)。

每个实体都有唯一的标识符属性。

我有肌肉识别器数组,我想将其用作过滤器以显示分段列表中的对象。

如何循环遍历这些标识符,然后将其添加到CoreStore.monitorSectionedList的.where子句中

我可能期望这样的事情,但不能百分百确定只是一个假设:

let谓词= NSPredicate(格式:“%K = $ ARGUMENT”)
    var predicates = [NSPredicate]()

    if let muscles : [MuscleGroupEntity] = workout?.muscles.toArray() {
        for muscle in muscles
        {
            let myNewPredicate = predicate.withSubstitutionVariables(["ARGUMENT" : muscle.id])
            predicates.append(myNewPredicate)
        }
    }

    self.monitor = CoreStore.monitorSectionedList(
        From<ListEntityType>()
            .sectionBy(#keyPath(ListEntityType.muscle.name)) { (sectionName) -> String? in
                return "\(String(describing: sectionName)) years old"
            }
            .where(format:"%K = %@", argumentArray: predicates)
            .orderBy(.ascending(#keyPath(ListEntityType.muscle.name)), .ascending(\.name))
    )

此代码因错误而崩溃:
-[NSComparisonPredicate rangeOfString:]: unrecognized selector sent to

我猜这是我发现here的谓词得出的,但不确定如何正确使用它

对于MartinM评论:

我有一个属性为Muscle的ExerciseEntity。

如果我只想用一根肌肉id进行所有锻炼,那很简单:
.where(format:"%K = %@", #keyPath(ExerciseEntity.muscle.id), "id_12345")

但是我想指定更多的肌肉并在运行时定义它们。我以某种方式需要了解什么是格式,什么参数以及如何传递标识符数组,而不只是一个"id_12345"

最佳答案

如果您要获取所有的exerciseId列表中包含其muscle.id的ExerciseEntity,则只需使用:

let muscleIds = workout?.muscles.compactMap({ $0.id }) ?? []
From....
   .where(Where<ExerciseEntity>(#keyPath(ExerciseEntity.muscle.id), isMemberOf: muscleIds))

那相当于具有以下格式的谓词:%K IN%@,ExerciseEntity.muscle.id,muscleIds

这也可以否定-> NOT(%K IN%@),与在CoreStore中使用!Where相同。

复合谓词需要指定如何链接。 CoreStore使用逻辑运算符一次支持两个谓词的简写,例如:
Where<ExerciseEntity>(yourWhereClause) && Where<ExerciseEntity(otherWhereClause)

这等效于像这样使用NSCompoundPredicate:
NSCompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate])

如果需要更复杂的连接,还可以将该复合谓词直接作为参数传递给where子句。然后,您还可以将该复合谓词存储在某个位置,并附加另一个适合您需要的复合谓词。

10-08 06:26