'How can i apply filters on fetch request with transformable type atributes

i'm trying to do a dictionary app with a data set of words which contain 2 arrays of string, i created my data model with 2 transformable attributes [String]

https://i.stack.imgur.com/vHzFJ.png

I can do fetchRequests, get all my words and write it on my view like this :

struct ContentView: View
{
    @FetchRequest(sortDescriptors: []) var mots: FetchedResults<Mot>
    @Environment(\.managedObjectContext) var moc
    
    let possibleKanjis:[String] = ["猫", "犬"]
    let possibleKanas:[String] = ["ねこ", "いぬ"]
        
    var body: some View
    {
        VStack
        {
            HStack
            {
                Button("Add")
                {
                    let motExemple = Mot(context: moc)
                    motExemple.kanjis = [possibleKanjis.randomElement()!]
                    motExemple.kanas = [possibleKanas.randomElement()!]
                    
                    try! moc.save()
                }
            }
            
            
            List(mots) { (mot: Mot) in
                
                HStack
                {
                    Text(mot.kanjis?[0] ?? "No Kanji")
                    Text(mot.kanas?[0] ?? "No Kana")
                    
                    Button("Delete")
                    {
                        moc.delete(mot)
                        try! moc.save()
                    }
                }
            }
            
            Spacer()
        }
    }
}

but how can i apply filter on my fechrequest for doing a reserch

Something like :

@FetchRequest(sortDescriptors: [], predicate: NSPredicate(format: "kanji CONTAIN %@", "猫")) var mots: FetchedResults<Mot>

Thanks you



Solution 1:[1]

A transformable attribute is not searchable because it can be anything and it is archived raw data.

For a simple type like a string array consider to transform the object into a JSON string.

Declare the attribute as String

@NSManaged public var jsonKanjis: String

And add a computed property

var kanjis : [String] {
    get { (try? JSONDecoder().decode([String].self, from: Data(cdKanji.utf8))) ?? [] }
    set {
        if let data = try? JSONEncoder().encode(newValue),
           let string = String(data: data, encoding: .utf8) {
               jsonKanjis = string
           } else {
               jsonKanjis = ""
           }
        
    }
}

A String attribute is searchable

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vadian