2011-05-31 73 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,并且需要“不是以字母开头的项目”的“其他”部分。

相关问题