Fast transfer of NSPredicate EXC_BAD_ACCESS (code = 1, address = 0x1) when compiling applications

I try to use NSPredicate in Swift to query Core Data, but it throws an EXC_BAD_ACCESS error (Code = 1, address = 0x1) when trying to start it, what am I doing wrong?

Here is the file where the error occurred

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" } } 
+7
swift core-data nspredicate
source share
2 answers

The %@ placeholder in formatted format strings for Objective-C objects, so you need to wrap the integer in NSNumber :

 fetchRequest.predicate = NSPredicate(format: "level = %@", NSNumber(integer: level)) 

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

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

We also note that

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

does not create a complex predicate; a simple assignment simply overwrites the first. You can use NSCompoundPredicate :

 let p1 = NSPredicate(format: "level = %ld", level)! let p2 = NSPredicate(format: "section = %ld", section)! fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates([p1, p2]) 

or just combine predicates with AND:

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

Instead of fussing with format conversion and AND sub-presentations, you can use the PredicatePal framework:

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

Note that to compare equality you need to use == instead of = .

0
source share

All Articles