小编典典

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

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"
  }
}

阅读 336

收藏
2020-07-07

共1个答案

小编典典

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