【问题标题】:NSPredicate to use with Transformable propertyNSPredicate 与 Transformable 属性一起使用
【发布时间】:2015-07-07 09:01:10
【问题描述】:

我有一个字符串数组,我在 Core Data 中保存为可转换的。从 json 我得到需要的字符串是这样的:

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

现在我想通过 mealTime 属性中的字符串过滤获取结果。我试过这种方式:

let predicate = NSPredicate(format: "mealTimes LIKE[cd] '*%@*'", "breakfast")
var breakfastContents = StaticContent.fetchStaticContentsWithPredicate(predicate, inManagedObjectContext: self.coreDataStack.context)
if (breakfastContents.count > 0) {
    breakfast = breakfastContents.first!
}

问题是结果数组是空的,但我知道我在某些内容中有早餐字符串。那么我该如何解决呢?我正在阅读一些关于将可转换保存为 NSData 的内容,因此它需要一些很棒的技巧。我试图使用LIKE(带和不带*)命令和CONTAINS

静态内容的扩展:

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
}

【问题讨论】:

标签: ios swift core-data nspredicate nsfetchrequest


【解决方案1】:

您应该重构您的数据模型以摆脱“字符串数组”。这不是存储此类值的一种非常可靠的方式。

相反,考虑与捕获这些字符串的新实体的关系。或者,设置一个存储字符串并具有分隔记录的唯一字符的方案(例如; 或类似的东西)。然后任何简单的字符串谓词都可以工作,如下所示:

NSPredicate(format: "mealtimes contains[cd] %@", "breakfast")

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多