NSPredicate 抛出 EXC_BAD_ACCESS
NSPredicate throwing EXC_BAD_ACCESS
我正在尝试删除用户选择的书籍,我在 NSPredicate 行收到 EXC_BAD_ACCESS。谁能告诉我哪里做错了?
func deleteSelectedBook() {
// Create Fetch Request
let fetchRequest = NSFetchRequest(entityName: "BookEntity")
// Create array string for predicate
var titleCollection:[String] = []
var formatString:String = ""
if let selectedCellCollection = self.tableView.indexPathsForSelectedRows {
for index in selectedCellCollection{
if (!formatString.isEmpty) {
formatString += " OR "
}
var temp = (self.tableView.cellForRowAtIndexPath(index)?.textLabel?.text)!
titleCollection.append(temp)
formatString += " title = %@ "
}
}
// Configure Fetch Request
fetchRequest.predicate = NSPredicate(format: formatString, titleCollection)
......
对于两个(例如)选定的项目,formatString
将是
"title = %@ OR title = %@"
需要两个参数,但在
NSPredicate(format: formatString, titleCollection)
只给出了一个参数。你可以用
解决这个问题
NSPredicate(format: formatString, argumentArray: titleCollection)
titleCollection
现在为
谓词创建。但更好更简单的解决方案是
NSPredicate(format: "title IN %@", titleCollection)
使用固定的谓词格式字符串。
通常应该避免使用字符串操作来创建
谓词格式字符串。在这种情况下,一个简单的谓词服务
同样的目的。在更复杂的情况下,NSCompoundPredicate
可用于动态构建谓词。
我正在尝试删除用户选择的书籍,我在 NSPredicate 行收到 EXC_BAD_ACCESS。谁能告诉我哪里做错了?
func deleteSelectedBook() {
// Create Fetch Request
let fetchRequest = NSFetchRequest(entityName: "BookEntity")
// Create array string for predicate
var titleCollection:[String] = []
var formatString:String = ""
if let selectedCellCollection = self.tableView.indexPathsForSelectedRows {
for index in selectedCellCollection{
if (!formatString.isEmpty) {
formatString += " OR "
}
var temp = (self.tableView.cellForRowAtIndexPath(index)?.textLabel?.text)!
titleCollection.append(temp)
formatString += " title = %@ "
}
}
// Configure Fetch Request
fetchRequest.predicate = NSPredicate(format: formatString, titleCollection)
......
对于两个(例如)选定的项目,formatString
将是
"title = %@ OR title = %@"
需要两个参数,但在
NSPredicate(format: formatString, titleCollection)
只给出了一个参数。你可以用
解决这个问题NSPredicate(format: formatString, argumentArray: titleCollection)
titleCollection
现在为
谓词创建。但更好更简单的解决方案是
NSPredicate(format: "title IN %@", titleCollection)
使用固定的谓词格式字符串。
通常应该避免使用字符串操作来创建
谓词格式字符串。在这种情况下,一个简单的谓词服务
同样的目的。在更复杂的情况下,NSCompoundPredicate
可用于动态构建谓词。