复合语句时,Swift NSPredicate抛出EXC_BAD_ACCESS(Code = 1,address = 0x1)

时间:2015-02-20 02:37:51

标签: swift core-data nspredicate

我试图在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"
  }
}

2 个答案:

答案 0 :(得分:49)

谓词格式字符串中的%@占位符用于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)

答案 1 :(得分:-1)

您可以使用PredicatePal框架,而不是乱搞格式转换和AND次预测:

fetchRequest.predicate = *(Key("level") == level && Key("section") == section)

请注意,您需要使用==代替=进行相等比较。