2011-05-31 71 views
21

我試圖從不在給定集合中的核心數據中獲取對象,但是我一直無法讓它工作。從核心數據中獲取對象不在集合中

例如,假設我們有一個名爲User的核心數據實體,它具有幾個屬性,如userName,familyName,givenName和active。鑑於表示一組用戶名的字符串數組,我們可以很容易地獲取所有對應的用戶名是列表中的用戶:

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init]; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" 
              inManagedObjectContext:moc]; 
[request setEntity:entity]; 

NSArray *userNames = [NSArray arrayWithObjects:@"user1", @"user2", @"user3", nil]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName IN %@", userNames]; 
[request setPredicate:predicate]; 
NSArray *users = [moc executeFetchRequest:request error:nil]; 

不過,我想獲取該集合的補,即,我希望所有的核心數據中的用戶沒有在userNames數組中指定的用戶名。有沒有人有一個想法如何解決這個問題?我認爲在謂詞(i.e., "userName NOT IN %@")中添加一個"NOT"會很簡單,但是Xcode會拋出一個異常,說明不能分析謂詞格式。我也嘗試使用可用於提取請求的謂詞構建器,但沒有運氣。文檔也不是特別有用。建議?註釋?感謝您的幫助:)

回答

52

爲了尋找不屬於你的數組中的對象,所有你需要做的就是這樣的事情:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (userName IN %@)", userNames]; 

應該返回的所有請求沒有你指定的對象的對象

+0

夠簡單......謝謝,slev。 – tomas 2011-05-31 14:31:34

+0

太棒了。我認爲這是行不通的。但是那是因爲我的數組中的數據來自另一個字段。謝謝。簡單而有效。 – 2013-01-01 03:42:01

+0

注意:這不適用於NSNumber變量,這可能是有道理的,但如果您將一個枚舉包裝在NSNumber中,這是一種遺憾。在這種情況下,使用'[NSPredicate predicateWithFormat:@「NOT(enumWrapper IN {%d,%d})」,enum1,enum2]'。 – 2013-03-18 00:43:18

1

我在覈心數據/目標-c上不夠強大,但謂詞應該像下面的語句;

[predicateFormat appendFormat:@"not (some_field_name in {'A','B','B','C'})"]; 

一個例子:

NSMutableString * mutableStr = [[NSMutableString alloc] init]; 

//prepare filter statement 
for (SomeEntity * e in self.someArray) { 
    [mutableStr appendFormat:@"'%@',", e.key]; 
} 

//excluded objects exist 
if (![mutableStr isEqual:@""]) 
{ 
    //remove last comma from mutable string 
    mutableStr = [[mutableStr substringToIndex:mutableStr.length-1] copy]; 

    [predicateFormat appendFormat:@"not (key in {%@})", mutableStr]; 
} 

//... 
//use this predicate in NSFetchRequest 
//fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateFormat]; 
//... 
0

下面是另一個有用的例子,說明如何把字符串列表,並篩選出任何不以字母開始AZ:

NSArray* listOfCompanies = [NSArray arrayWithObjects:@"123 Hello", @"-30'c in Norway", @"ABC Ltd", @"British Rail", @"Daily Mail" @"Zylophones Inc.", nil]; 

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF MATCHES[c] '^[A-Za-z].*')"]; 

NSArray *filteredList = [listOfCompanies filteredArrayUsingPredicate:bPredicate]; 

for (NSString* oneCompany in filteredList) 
    NSLog(@"%@", oneCompany); 

當我使用AZ索引填充UITableView時,我使用這種NSPredicate,並且需要「不是以字母開頭的項目」的「其他」部分。

相關問題