Swift NSPredicate 在复合语句时抛出 EXC_BAD_ACCESS(Code=1, address=0x1) [英] Swift NSPredicate throwing EXC_BAD_ACCESS(Code=1, address=0x1) when compounding statements
问题描述
我试图在 Swift 中使用 NSPredicate 来查询核心数据,但在尝试运行它时抛出 EXC_BAD_ACCESS(Code=1, address=0x1) 错误,我做错了什么?
I am trying to use NSPredicate in Swift to query Core Data but it throws an EXC_BAD_ACCESS(Code=1, address=0x1) error when trying to run it, what am I doing wrong?
这是发生错误的文件
class LevelsScreenModel : UIViewController {
func getWord(level: Int, section: Int) -> String
{
let fetchRequest = NSFetchRequest(entityName: "Words")
//This is the line where the error happens
fetchRequest.predicate = NSPredicate(format: "level = %@", level)
fetchRequest.predicate = NSPredicate(format: "section = %@", section)
let word = AppDelegate().managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as [Words]
if(word.count > 1)
{
for words in word
{
println(words.word)
return words.word
}
}
return "ERROR"
}
}
推荐答案
谓词格式字符串中的 %@
占位符用于 Objective-C对象,所以你必须把整数包装成一个 NSNumber
:
The %@
placeholder in predicate format strings is for Objective-C
objects, so you have to wrap the integer into an NSNumber
:
fetchRequest.predicate = NSPredicate(format: "level = %@", NSNumber(integer: level))
或使用 ld
来格式化(长)整数:
or use ld
instead to format a (long) integer:
fetchRequest.predicate = NSPredicate(format: "level = %ld", level)
还要注意
fetchRequest.predicate = NSPredicate(format: ...)
fetchRequest.predicate = NSPredicate(format: ...)
不创建复合谓词,秒赋值简单覆盖第一个.您可以使用 NSCompoundPredicate
:
does not create a compound predicate, the seconds assignment simply
overwrites the first. You can use an NSCompoundPredicate
:
let p1 = NSPredicate(format: "level = %ld", level)!
let p2 = NSPredicate(format: "section = %ld", section)!
fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates([p1, p2])
或者简单地将谓词与AND"结合起来:
or simply combine the predicates with "AND":
fetchRequest.predicate = NSPredicate(format: "level = %ld AND section = %ld", level, section)
这篇关于Swift NSPredicate 在复合语句时抛出 EXC_BAD_ACCESS(Code=1, address=0x1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!