首页 > 解决方案 > CoreStore 分段列表监控如何在运行时指定 .where 子句

问题描述

我的 init 方法中有这段代码:

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包含一对一的关系Muscleexercise.muscle)。

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

我有一组肌肉标识符,我想将其用作过滤器来显示分段列表中的对象。

如何循环通过此标识符将 then to .where 子句添加到CoreStore.monitorSectionedList

我可能期待这样的事情,但不是 100% 肯定只是假设:

让谓词 = 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

我想这是我在这里找到的谓词,但不确定在我的情况下如何正确使用它

编辑 MartinM 评论:

我有带有属性肌肉的运动实体。

如果我想只使用一个肌肉 id 进行所有锻炼,这很简单:

.where(format:"%K = %@", #keyPath(ExerciseEntity.muscle.id), "id_12345")

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

标签: iosswiftcore-datanspredicatecorestore

解决方案


如果你想获取所有的 ExerciseEntity,其中他们的肌肉.id 包含在一个肌肉 ID 列表中,你只需使用:

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 一次支持 2 个谓词的简写,使用逻辑运算符,例如:

Where<ExerciseEntity>(yourWhereClause) && Where<ExerciseEntity(otherWhereClause)

这相当于像这样使用 NSCompoundPredicate:

NSCompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate])

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


推荐阅读