In this SO question from 2010, the OP asks how to go about formatting a stored fetch request created in the Xcode GUI to allow for variable substitution when the stored request is called at runtime using NSFetchRequest:fetchRequestFromTemplateWithName:substitutionVariables.
Apple has some archived documentation that talks about how to do this in Obj-C, but Swift handles variables differently and I haven't found the syntax documented anywhere.
In my application, I'm looking to find an audio track that belongs to a certain category. The track has an attribute called trackCategory
which is defined as an Int64
In my template Fetch Request, I've set up a Custom Predicate with the statement trackCategory == $TRACKCATEGORY
. As I understand it, I'm setting up a condition where the object will only be returned if the object's trackCategory
value matches a variable value named $TRACKCATEGORY
that will be substituted at runtime.
And then, in my code, I'm trying to call this stored fetch request as follows:
fetchRequest = model.fetchRequestFromTemplate(withName:
"getUnplayedTracks", substitutionVariables: ["TRACKCATEGORY" : forCategory])!
Two things:
model
is declared at the top of the ViewController (this document) as:
let model = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.managedObjectModel
.
forCategory
is an Int64 declared elsewhere.
When I build and run this, I get a SIGABRT with the error message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unable to resolve variable expression: $TRACKCATEGORY'
I'm sure I'm missing something with how the Custom predicate statement is formatted, but I just can't figure out what it is.