我正在尝试在Swift中使用NSPredicate来查询核心数据,但是在尝试运行它时抛出EXC_BAD_ACCESS(Code = 1,address = 0x1)错误,我在做什么错?
这是发生错误的文件
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
:
fetchRequest.predicate = NSPredicate(format: "level = %@", NSNumber(integer: level))
或改用ld
格式化(长)整数:
fetchRequest.predicate = NSPredicate(format: "level = %ld", level)
另请注意
fetchRequest.predicate = NSPredicate(format: ...)
fetchRequest.predicate = NSPredicate(format: ...)
并没有创建复合谓词,使秒针分配简单地覆盖第一。您可以使用NSCompoundPredicate
:
let p1 = NSPredicate(format: "level = %ld", level)!
let p2 = NSPredicate(format: "section = %ld", section)!
fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates([p1, p2])
或简单地将谓词与“ AND”组合:
fetchRequest.predicate = NSPredicate(format: "level = %ld AND section = %ld", level, section)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句