Tapas Pal Tapas Pal - 4 months ago 11
Swift Question

NSPredicate: Unable to parse the format string for relationship

I have two entity named "

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

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

CICast:
-> 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

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".

Comments