我正在使用 Core Data 来存储由多个实体组成的对象模型,但相关的是这样的:
实体: 拉伸(stretch)
相关属性:
设备用过,
肌肉群
我在 Storyboard中有一个带有 UISegmentedControl
的场景,我用来选择 equipmentUsed
。
// Creates a variable which changes the selectedEquipment type based on which
// selectedSegmentIndex is clicked
var stretches: [Stretch] = [] // List of stretches
var selectedEquipment : NSString? // Equipment selected from UISegmentedControl
@IBAction func selectEquipment(sender: UISegmentedControl) {
if equipmentSelector.selectedSegmentIndex == 0 {
self.selectedEquipment = "roller"
}
if equipmentSelector.selectedSegmentIndex == 1 {
self.selectedEquipment = "none"
}
}
在 UISegmentedControl
下方,我有用于切换各种肌肉群的静态单元格。使用谓词进行过滤的每个示例都会将所有数据转储到 TableView 上,然后再进行过滤。我正在尝试为谓词选择关键路径并将它们放入数组中。
我正在尝试创建谓词来选择特定的设备(例如:无或泡沫轴)和特定的肌肉群。我将前面的 selectedEquipment
字符串用作以下谓词中的变量:
var shoulderPredicate = NSPredicate(format: "stretch.equipmentUsed contains[c] $selectedEquipment AND (stretch.muscleGroup contains[c] %@", "shoulders")
我在从 shoulderPredicate 创建数组时遇到了问题。这是我创建数组的代码:
@IBAction func testSearchStretches(sender: AnyObject) {
println("testSearchStretches clicked")
var stretchList = (stretches as NSArray).filteredArrayUsingPredicate(shouldersPredicate)
for stretch in stretchList {
println(stretch)
}
}
我可以看到 testSearchStretches IBAction 在控制台中打印“testStretches clicked”,但它不打印 stretchList,但我知道有一个 Stretch 与谓词匹配。我相信我设置的谓词不区分大小写,所以我认为这不是问题所在。
一旦我弄清楚了数组,我将在另一个屏幕上显示结果。现在,我只是想让谓词工作以创建 stretchList 数组。我是编程新手,我正在尝试超越教程以自己创建一些东西。如果你来到这里,感谢阅读,非常感谢你的帮助。
最佳答案
你的谓词有两个问题:
- 您不得在键路径中包含实体名称。 谓词格式字符串中的
$selectedEquipment
不插入或插值selectedEquipment
变量的值。可以使用谓词中的$VAR
使用predicateWithSubstitutionVariables()
函数,但我认为这是 这不是你想要的。
你的谓词可能应该是
NSPredicate(format: "equipmentUsed contains[c] %@ AND muscleGroup contains[c] %@",
selectedEquipment, "shoulders")
假设“equipmentUsed”和“muscleGroup”是String 属性。
关于ios - 使用变量创建 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27930174/