ios - 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
包含一对一的关系Muscle
(exercise.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"
解决方案
如果你想获取所有的 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 子句。然后,您还可以将该复合谓词存储在某处并附加另一个适合您需要的复合谓词。
推荐阅读
- reactjs - npm update 什么都不做
- string - Powershell - 在多次反斜杠后提取字符串最后一部分的最佳方法
- javascript - Owl Carousel 按项目而不是总是显示导航
- visual-studio-code - 在哪里可以找到 VS Code 自动完成列表中的图标
- javascript - 用javascript中的正则表达式替换文本
- c# - asp.net core web api无法从客户端发送对象
- javascript - 如何解决通过id查找商品的问题?
- angular - 如何在 Angular 6+ 上基于 --project 导入脚本?
- css - 如何修改此 Bootstrap 列堆叠行为
- yii2 - 更新 Yii2 项目到 php 7.2