Ces*_*219 16 core-data nspredicate swift
我试图在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"
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*n R 51
%@谓词格式字符串中的占位符用于Objective-C对象,因此您必须将整数包装到NSNumber:
fetchRequest.predicate = NSPredicate(format: "level = %@", NSNumber(integer: level))
Run Code Online (Sandbox Code Playgroud)
或者ld用来格式化(长整数):
fetchRequest.predicate = NSPredicate(format: "level = %ld", level)
Run Code Online (Sandbox Code Playgroud)
另请注意
fetchRequest.predicate = NSPredicate(format: ...)
fetchRequest.predicate = NSPredicate(format: ...)
Run Code Online (Sandbox Code Playgroud)
如果不创建复合谓词,则秒赋值只会覆盖第一个.你可以使用NSCompoundPredicate:
let p1 = NSPredicate(format: "level = %ld", level)!
let p2 = NSPredicate(format: "section = %ld", section)!
fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates([p1, p2])
Run Code Online (Sandbox Code Playgroud)
或者简单地将谓词与"AND"组合:
fetchRequest.predicate = NSPredicate(format: "level = %ld AND section = %ld", level, section)
Run Code Online (Sandbox Code Playgroud)