NSPredicate parse error

I'm trying to create a predicate with the below line, but it keeps telling me it's unable to parse the format string.


var request = NSFetchRequest(entityName: "Player")
request.predicate = NSPredicate(format: "ANY matches.bracket == %@", self)


On Player's entity 'matches' is an optional to-many relationship to a Match entity. The Match entity has a to-one required attribute 'bracket' that points to a Bracket entity. I'm inside of the Bracket class with the above code, so thus the 'self' property.


I want to get all Player entities where at least one of the matches pointed to belongs to the current bracket.


What am I doing wrong here?

Answered by MartinR in 41794022

The problem is that "MATCHES" is a predicate keyword (used for regular expression matches), and predicate keywords are case-insensitive. Using the "%K" keypath expansion should solve the problem:


let request = NSFetchRequest(entityName: "Player")
request.predicate = NSPredicate(format: "ANY %K == %@", "matches.bracket", self)


This is generally a good idea to avoid name conflicts. For more information, see Predicate Format String Syntax in the "Predicate Programming Guide".

Accepted Answer

The problem is that "MATCHES" is a predicate keyword (used for regular expression matches), and predicate keywords are case-insensitive. Using the "%K" keypath expansion should solve the problem:


let request = NSFetchRequest(entityName: "Player")
request.predicate = NSPredicate(format: "ANY %K == %@", "matches.bracket", self)


This is generally a good idea to avoid name conflicts. For more information, see Predicate Format String Syntax in the "Predicate Programming Guide".

Thanks, Martin. I looked at that so many times and the 'matches' never even occurred to me!

NSPredicate parse error
 
 
Q