Search code examples
swiftcore-datanspredicate

Swift predicate that returns matches on a Core Data transformable string array


I have a Core Data entity which has an attribute called likedMovies which is a String array [String]. This is configured as a Transformable attribute.

I populate a list of IDs inside this attribute, so for example:

User entity:
name = Duncan | likedMovies = [524, 558, 721]
name = Saskia | likedMovies = [143, 558, 653]
name = Marek | likedMovies = [655, 323, 112]

I would like to write a predicate which returns all User entities where the likedMovies array contains a given value. I have tried the predicate below but it doesn't work - for the id 558, instead of returning [Duncan, Saskia] I get no entities returned.

fetchRequest.predicate = NSPredicate(format: "%@ IN %@", "558", "likedMovies")

Thank you in advance for your help.

enter image description here


Solution

  • There are two issues: first, your predicate format is wrong. You cannot use %@ as placeholder for attribute names; you must instead use %K:

    fetchRequest.predicate = NSPredicate(format: "%@ IN %K", "558", "likedMovies")
    

    But the second problem is that transformable attributes cannot be used in predicates as part of a fetch request (for a SQLite store). One option is to use the predicate to filter the User objects in memory (after fetching them). Another option is to represent the array of IDs as a string (with suitable separator), rather than an array of strings. You can then use the CONTAINS string operator to create the predicate. But adding and removing IDs to the likedMovies will become a rather unwieldy process of string manipulation. Another option is to replace the transformable attribute with a to-many relationship. I recommend the last of these.