Swift NSPredicate throwing EXC_BAD_ACCESS(Code=1, address=0x1) when compounding statements
4738 просмотра
2 ответа
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"
}
}
Автор: Cesarg219
Источник
Размещён: 12.11.2019 09:40
Ответы (2)
51 плюса
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)
Автор: Martin R
Размещён: 20.02.2015 06:01
-1 плюса
Instead of fussing around with format conversions and AND
subpredicates, you could use the PredicatePal framework:
fetchRequest.predicate = *(Key("level") == level && Key("section") == section)
Note that you'll need to use ==
instead of =
for equality comparison.
Вопросы из категории :
- swift Как я могу программным образом определить, работает ли мое приложение в симуляторе iphone?
- swift iOS: Convert UTC NSDate to local Timezone
- swift Как установить цель и действие для UIBarButtonItem во время выполнения
- swift Жирный и не жирный текст в одном UILabel?
- swift Найти касательную точки на кубической кривой безье
- swift Как я могу рассчитать разницу между двумя датами?
- core-data Каждое ли базовое отношение данных должно иметь обратную сторону?
- core-data Удалить / Сбросить все записи в Базовых данных?
- core-data Базовые данные: самый быстрый способ удалить все экземпляры объекта
- core-data NSPredicate: filtering objects by day of NSDate property
- core-data Добавление основных данных в существующий проект iPhone
- core-data Есть ли полезные видео о Core Data?
- nspredicate NSPredicate для длины строкового атрибута NSManagedObject
- nspredicate Проверка основных данных NSP предиката для значения BOOL
- nspredicate Как ограничить счетчик результатов NSFetchRequest?
- nspredicate Базовые данные: предикат, который возвращает объекты другого объекта
- nspredicate Проверьте, содержит ли NSArray какой-либо int