【问题标题】:Core Data Filter Predicate With An Array Swift使用数组 Swift 的核心数据过滤谓词
【发布时间】:2017-09-12 03:11:36
【问题描述】:

我试图通过传入一个字符串数组来从我的核心数据存储中提取对象,并且只提取类别与数组中的内容匹配的对象。

我已经能够让这段代码工作,除了它只使用数组中的第一项,并且不会遍历数组并匹配其余的项。

这是适用于此的代码。我正在使用接受和数组的 NSPredicate 重载。

    func filterTopicCategories() {
        fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory == %@", argumentArray: selectedCategories)
        topicsToSelectFrom = fetchController.fetchTopics()
        }

我已经翻阅了有关谓词和所有这些的 Apple 文档,但似乎无法完全弄清楚。我也花了几个小时在谷歌上搜索。我不确定我是否只是没有正确理解某些事情,或者我只是做错了,我不确定。任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: ios arrays swift core-data nspredicate


    【解决方案1】:

    这对我有用:

    `

        let isWatchLaterPredicate = NSPredicate(format: "isWatchLater == YES")    
    

    let managedContext = appDelegate.managedObjectContext

        let fetchRequestWatchLater = NSFetchRequest<NSManagedObject>(entityName: "WatchList")
    
        fetchRequestWatchLater.predicate = isWatchLaterPredicate
        print(fetchRequestWatchLater)
    
        do {
    
            watchList = try managedContext.fetch(fetchRequestWatchLater)
    
    
            print("watch List Items \(isWatchLaterPredicate)")
        } catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }
    
            }
    

    `

    【讨论】:

      【解决方案2】:

      好的,所以我终于偶然发现了这个问题Swift Core Data Predicate IN Clause,其中提到了删除重载中的 argumentArray 标签。我试过了,然后也改变了我的 predicateFormat 。所以现在看起来是这样的

          func filterTopicCategories() {
              fetchController.topicFetchRequest.predicate = NSPredicate(format: "ANY topicCategory IN %@", selectedCategories)
              topicsToSelectFrom = fetchController.fetchTopics()
      
          }
      

      它现在似乎可以工作了。不确定这是否是一个错误,因为 Xcode 中的自动完成功能会将标签放在那里,所以很奇怪。

      无论如何,希望这可以帮助那些在同样问题上苦苦挣扎的人。

      谢谢。

      【讨论】:

        【解决方案3】:

        参数argumentArray 用于替换格式字符串中%@ 等占位符的值数组。

        您正在寻找IN 运算符:

        输入

        相当于一个SQLIN操作,左边必须出现 在右侧指定的集合中。例如,name IN { 'Ben', 'Melissa', 'Nick' }。集合可以是一个数组,一个 集合或字典——在字典的情况下,使用它的值。 在 Objective-C 中,您可以创建一个 IN 谓词,如 下面的例子:

        NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection]; 
        

        其中aCollection 可能是NSArrayNSSet 的实例, NSDictionary,或任何相应的可变类。

        所以如果topicCategory是一个字符串写

        fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory IN %@", selectedCategories)
        

        【讨论】:

        • 是的,我之前读过并尝试过,但它仍然无法正常工作。 argumentArray: label 也有问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-21
        • 2017-07-27
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多