2017-03-20 21 views
-1

我需要根據存儲在CoreDate中的實際值設置我的NSPredicate。有沒有一種方法可以根據存儲在CoreData中的實際值來設置NSPredicate?

假設我們有一個CoreData實體:「畢業生」。如果他/她的畢業日期不爲零,我們想要取得畢業日期早於Date1的畢業生。否則,我想檢查他/她的生日是否早於Date2。

謂詞是這樣的:

"if graduationDate != null graduationDate < %@ else birthday < %@" 

所以我實際上有兩個謂語。如果第一個謂詞想要檢查的字段爲空,則第二個字符只應該生效。

我的想法:

  1. 我可以在我的應用程序,而不是CoreData處理此,只是不知道是否有隻使用一個NSPredicate梳理出來的一種方式。

  2. 有些帖子提到NSPredicate與SQL Where子句等價,這對我很有意義。我認爲我在這裏需要的是超出條款能夠達到的水平。

我的問題不是關於如何使用NSPredicate過濾提取結果。這是關於如何使用流量控制來設置NSpredicate,如果其他子句爲

+1

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html向下滾動到 「**濾波結果**」。在提交新文章之前,您也可以多次搜索這個問題。您也可以根據需要爲多個謂詞添加NSCompoundPredicate https://developer.apple.com/reference/foundation/nscompoundpredicate。 –

+0

如果NSPredicate和NSCompoundPredicate是「基本用法」,那麼能否請您解釋一下核心數據提取的高級用法以及您要求的內容,對於我們受教育程度較低的基本用戶? –

+0

[iOS CoreData NSPredicate可能一次查詢多個屬性]的可能重複(http://stackoverflow.com/questions/10611362/ios-coredata-nspredicate-to-query-multiple-properties-at-once) –

回答

1

您可以使用NSCompoundPredicate來組合較小的謂詞。

let graduates = NSPredicate.init(format: "graduationDate != NULL AND graduationDate < %@ ", graduationDate); 
    let oldPeople = NSPredicate.init(format: "graduationDate == NULL AND birthday > %@ ", cutOffBirthday); 
    let predicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [graduates, oldPeople]); 
相關問題