Padin215
Padin215

Reputation: 7484

NSPredicate with a NSArray of NSNumbers (Core Data)

I have Core Data entity Field with an attribute of ID. I want to search all Field entities for ID == 1, 2, or 3.

How can I add an array to a NSPredicate w/out creating a long appended string something like:

NSArray *IDArray = @[@1, @2, @3];

NSMutableString *predicateString = [NSMutableString string];

for (NSNumber *ID in IDArray) {
    [predicateString appendString:[NSString stringWithFormat:@"ID == %@, ID]];
}

Upvotes: 0

Views: 965

Answers (1)

Martin R
Martin R

Reputation: 540105

This should work:

NSArray *IDArray = @[@1, @2, @3];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ID IN %@", IDArray];

Remark: You should never use string formatting functions to combine predicates. Use

 [NSCompoundPredicate orPredicateWithSubpredicates:...]

and similar methods. The reason is that strings and predicates have different rules how format specifiers are expanded.

Upvotes: 2

Related Questions