问题描述:

I have array of strings which I save in Core Data as Transformable. From json I am gettings needed strings like this:

if let mealTimes = dictionary["mealTimes"] as? [String]{

self.mealTimes = mealTimes

}

Now I would like to filter fetch results by strings in mealTime property. I have tried this way:

let predicate = NSPredicate(format: "mealTimes LIKE[cd] '*%@*'", "breakfast")

var breakfastContents = StaticContent.fetchStaticContentsWithPredicate(predicate, inManagedObjectContext: self.coreDataStack.context)

if (breakfastContents.count > 0) {

breakfast = breakfastContents.first!

}

The problem is that result array is empty but I know I have breakfast string in some content. So how can I fix it? I was reading something about saving transformable as NSData so it would need some great trick. I was trying to use LIKE (with and without *) command and CONTAINS.

Extension for StaticContent:

class func fetchStaticContentsWithPredicate(predicate: NSPredicate, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> [StaticContent] {

// Define fetch request/predicate

var fetchRequest = NSFetchRequest(entityName: "StaticContent")

// Assign fetch request properties

fetchRequest.predicate = predicate

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]

// Handle results

let fetchedResults = managedObjectContext.executeFetchRequest(fetchRequest, error: nil) as! [StaticContent]

return fetchedResults

}

网友答案:

You should refactor your data model to get rid of the "array of strings". This is not a very sound way to store this type of values.

Instead, consider a relationship with a new entity that captures those strings. Alternatively, device a scheme where you store a string and have a unique character that separates the records (e.g ; or something similar). Then any simple string predicate would work, like this:

NSPredicate(format: "mealtimes contains[cd] %@", "breakfast")
相关阅读:
Top