如何过滤从Core Data获取的数据? [英] How to filter data that has been fetched from Core Data?

查看:110
本文介绍了如何过滤从Core Data获取的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Core Data获取,我可以使用NSPredicate过滤我获得的内容,但只能使用持久属性,而不能使用临时属性(根据苹果的这篇文章)。什么方法可以用于使用瞬态属性或某种计算属性进一步过滤数据?



(这个问题是先前的问题,其过于宽泛。 )

解决方案

感谢@shallowThought,答案很简单:



设置了我的谓词后,过滤使用以下代码行:

  filteredLines = theLines.filter {myPredicate。在这种情况下,theLines是从CoreData中检索的,因为它是一个非常简单的方法,和myPredicate是我想要过滤的任何内容,例如

  let p1 = NSPredicate(format:lineNumber> 4) 
let p2 = NSPredicate(format:lineNumber <7)
// let minLineNumberStr =4
// let p3 = NSPredicate(format:lineNumber> =%@ ,minLineNumberStr)//与p1一样,但更灵活

var predArray:[NSPredicate] = []

//注释掉我们没有实际使用的谓词:
predArray.append(p1)
predArray.append(p2)
// predArray.append(p3)

let myPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:predArray)

在这种情况下,如果谓词包含一个transient属性,瞬时属性被正确地计算);当从核心数据获取时,具有瞬态属性的过滤器不会引发错误,但是它也不会返回任何结果。



帮助我得到这个答案的资源: / p>



希望这对我有同样问题的其他人有帮助。 / p>

Fetching from Core Data, I can filter what I get by using NSPredicate, but only by using persistent attributes, but not transient attributes (as per this article from Apple). What method(s) can be used to further filter the data using Transient Attributes or some sort of computed property?

(This question is a refinement of an earlier question, which was overly broad.)

解决方案

With thanks to @shallowThought, the answer is fairly straightforward:

Having set up my predicates, the filtering uses the following line of code:

filteredLines = theLines.filter {myPredicate.evaluate(with: ($0))}

In this case, theLines is what was retrieved from CoreData, and myPredicate is whatever I want to filter on, such as

    let p1 = NSPredicate(format: "lineNumber > 4")  
    let p2 = NSPredicate(format: "lineNumber < 7")  
//        let minLineNumberStr = "4"
//        let p3 = NSPredicate(format: "lineNumber >= %@", minLineNumberStr) // same as p1, but more flexible

    var predArray : [NSPredicate] = []

// Comment out the predicates we DON'T actually use:
        predArray.append(p1)
        predArray.append(p2)
//        predArray.append(p3)

    let myPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predArray)

In this case, if the predicate contains a transient attribute, the filtering works as expected (i.e. the transient attribute is evaluated correctly); when fetching from core data, the filter with a transient property does NOT throw an error, but it also returns no results.

Resources that helped my arrive at this answer:

Hope this is helpful to others with the same question I had.

这篇关于如何过滤从Core Data获取的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆