從核心數據提取,我可以通過使用NSPredicate來過濾我所得到的結果,但只能使用持久屬性,而不能使用瞬態屬性(as per this article from Apple)。可以使用什麼方法使用瞬態屬性或某種計算屬性來進一步過濾數據?如何過濾從核心數據中獲取的數據?
(這個問題的an earlier question細化,這是過於寬泛的。)
從核心數據提取,我可以通過使用NSPredicate來過濾我所得到的結果,但只能使用持久屬性,而不能使用瞬態屬性(as per this article from Apple)。可以使用什麼方法使用瞬態屬性或某種計算屬性來進一步過濾數據?如何過濾從核心數據中獲取的數據?
(這個問題的an earlier question細化,這是過於寬泛的。)
與感謝@shallowThought,答案相當簡單:
已經建立了我的謂詞,過濾使用以下行代碼:
filteredLines = theLines.filter {myPredicate.evaluate(with: ($0))}
在這種情況下,theLines就是從CoreData檢索,並比如說myPredicate是什麼我想過濾的,如
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)
在這種情況下,如果謂詞包含瞬態屬性,則過濾按預期工作(即,瞬態屬性被正確評估);從核心數據獲取時,具有瞬態屬性的過濾器不會拋出錯誤,但它也不會返回任何結果。
資源,幫助我到達這個答案:"Higher Order Functions: Map, Filter, Reduce, and More
堆棧溢出文章:
從We-Heart-Swift.com filteredArrayUsingPredicate does not exist in swift Array(前兩個答案)
希望這對我有同樣問題的其他人有幫助。
簡單地遍歷你提取的結果,並採用適合你的過濾標準的對象,使用'for'循環,'.filer'等常用技術。 – shallowThought
@shallowThought - 非常感謝 - 這是我需要的提示。我的結果轉載如下,其他人可能在我所在的地方,並會發現這有用,但這是您的答案,讓我朝着正確的方向前進。 – ConfusionTowers