4

I have successfully added Core Data to my SwiftUI project. I need to filter the results by type. When I add a predicate to the fetch request the app crashes at the point where the view containing the fetch request tries to load.

The error is Thread 1: EXC_BAD_ACCESS (code=1, address=0x1)

 @Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Task.entity(),
    sortDescriptors:[
        NSSortDescriptor(keyPath: \Task.type, ascending: true),
        NSSortDescriptor(keyPath: \Task.totalScore, ascending: false),
    ],
        predicate: NSPredicate(format: "type == %@", Int16(1))) //this is the line that crashes the app
 var tasks: FetchedResults<Task>

If I change the Int16(1) to Int16(0), the app does not crash but no data appears in the list.

This is the first app I have witten using core data so I need help.

1
  • I suspect your problem is your predicate format. %@ expects a String or a value that Swift can implicitly convert to a String, so what placeholder would you use for an Int? Commented Sep 1, 2019 at 18:55

2 Answers 2

4

Thanks to andrewbuilder. He got me looking in the right direction. The correct way to use a predicate that expects an Int is:

predicate: NSPredicate(format: "type == %i", Int16(1)))

I was using %@ when I should have used %i.

Sign up to request clarification or add additional context in comments.

Comments

1

You can also make the int an NSNumber object:

NSPredicate(format: "type == %@", @(1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.