2011-04-14 82 views
4

我有一个整数字段的表。我想选择该字段包含任何几个不同值的所有行。使用NSPredicate与整数列表匹配

我使用这个:

[NSPredicate predicateWithFormat:@"myIntValue IN {1,2,3,4}"] 

但这只能返回行,其中myIntValue为1

我在做什么错?

回答

10

这工作:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 

NSArray *idList = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], 
              [NSNumber numberWithInt:2], 
              [NSNumber numberWithInt:3], 
              [NSNumber numberWithInt:4], 
              nil]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idealForId IN $IDLIST"]; 
request.predicate = [predicate predicateWithSubstitutionVariables: 
    [NSDictionary dictionaryWithObject:idList forKey:@"IDLIST"]]; 
+1

核心数据只存储对象,因此当您创建谓词时,您总是必须将标量转换为对象。 – TechZen 2011-04-14 18:59:47

2

你试过吗?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myIntValue IN %@", 
[NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil]]; 

documentation可能在这里有用。

+0

我认为这可能适用于字符串,但它似乎不适用于整数。我试过[NSNumber numberWithInt:1]而不是@“1”,但那也不管用。 – teedyay 2011-04-14 13:28:33

+0

@“1”是一个NSString,@ 1是一个NSNumber – trapper 2017-07-26 04:20:58

0

我不知道这种情况已经改变,因为这个问题最初发布,但我得到所有这三个完全相同的断言。

[NSPredicate predicateWithFormat:@"myIntValue IN {1, 2, 3, 4}"]; 

[NSPredicate predicateWithFormat:@"myIntValue IN {%d, %d, %d, %d}", 1, 2, 3, 4]; 

[NSPredicate predicateWithFormat:@"myIntValue IN %@", @[@1, @2, @3, @4]]; 

所以不需要将所有东西都包裹在对象中。