2017-04-16 47 views
0

我試圖通過傳遞一個字符串數組,並只拉對象具有與數組中的內容匹配的對象,從而將對象從我的核心數據存儲中取出。使用數組Swift的核心數據過濾器Predicate

我已經能夠獲得此代碼的工作,除了它只使用數組中的第一個項目,並且不會遍歷數組並匹配其餘項目。

這是適用於此的代碼。我正在使用接受和數組的NSPredicate重載。

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

我已經翻閱了關於謂詞和所有那些Apple文檔,並且似乎無法弄清楚它。我花了幾個小時搜索谷歌以及。我不確定我是否不正確地理解某些東西,或者如果我只是完全錯誤地做,我不確定。任何幫助將不勝感激。

由於

回答

1

參數argumentArray爲值數組來替換佔位符等在格式字符串%@

您正在尋找IN操作:

IN

相當於SQL IN操作時,左側必須出現在右邊指定的集合中 。例如,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) 
+0

是的,我讀了,並試圖更早,但它仍然無法正常工作。 argumentArray:標籤也存在於這個問題中。 – bshock84

1

好了,我終於跌跌撞撞到,所提到過載去除argumentArray標籤這個問題Swift Core Data Predicate IN Clause。我試過了,然後改變了我的謂詞格式。所以現在它看起來像這樣

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

    } 

它現在似乎工作。不知道這是否是一個錯誤,因爲Xcode中的自動完成功能會將該標籤放在那裏,這很奇怪。

無論如何,希望這可以幫助有人在同一個問題上掙扎。

謝謝。

0

這個工作對我來說:

`

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)") 
    } 

     } 

`