Tapas Pal Tapas Pal - 1 year ago 110
Swift Question

NSPredicate: Unable to parse the format string for relationship

I have two entity named "

" and "
". "
" entity has an one-to-one relationship with "
" named "

CIUser :
-> userId(Int)
-> isLive(bool)
-> name(String)

-> castId(Int)
-> lastUpdate(Date)

Now my requirement is to fetch all the users who are currently live and there lastUpdate is less than a calculated date. So I had prepared my fetch request like

let time = //an calculated NSDate object

let fetchRequest = NSFetchRequest(entityName: "CIUser")
fetchRequest.predicate = NSPredicate(format: "isLive == %@ AND cast.lastUpdate <= %@", NSNumber(bool: true), time)

But it crash the application throwing
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "isLive == %@ AND cast.lastUpdate <= %@"'

Can anyone help me where I am doing wrong, or what approach should I take. Suggestion will be appreciated.

Answer Source

The problem is that "CAST" is a reserved word in the predicate format syntax, and the reserved words are case-insensitive. So this conflicts with your relationship named "cast".

As a workaround, use the %K key path substitution:

fetchRequest.predicate = NSPredicate(format: "isLive == %@ AND %K <= %@",
                            NSNumber(bool: true), "cast.lastUpdate", time)

or rename the relationship. You may want to use the %K expansion generally to avoid such problems:

fetchRequest.predicate = NSPredicate(format: "%K == %@ AND %K <= %@",
                           "isLive", NSNumber(bool: true),
                           "cast.lastUpdate", time)

For more information, see Predicate Format String Syntax in the "Predicate Programming Guide".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download