Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

core data - Swift NSPredicate throwing EXC_BAD_ACCESS(Code=1, address=0x1) when compounding statements

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?

Here is the file where the error happens

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"
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

or use ld instead to format a (long) integer:

fetchRequest.predicate = NSPredicate(format: "level = %ld", level)

Note also that

fetchRequest.predicate = NSPredicate(format: ...)
fetchRequest.predicate = NSPredicate(format: ...)

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])

or simply combine the predicates with "AND":

fetchRequest.predicate = NSPredicate(format: "level = %ld AND section = %ld", level, section)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...