-1

I have set up an NSPredicate to check if the object category_id is IN in an NSArray of numbers.

The code:

 ///This is working

NSArray *arr2 = [[NSArray alloc]initWithObjects:@[@3,@2,@3],nil];

[NSPredicate predicateWithFormat:@"category_id IN %@", arr2]

//This is not working

NSArray *arr = [[NSArray alloc]initWithArray:category_array]; //Array with NSNumbers

[NSPredicate predicateWithFormat:@"category_id IN %@", arr]

This was working fine but after I changed my category_array to contains NSNumber the predicate stopped working. How I use NSPredicate for NSNumber?

Update: Arrays:

enter image description here

Entity for Category:

enter image description here

BlackM
  • 3,927
  • 8
  • 39
  • 69
  • how does new category array look like ? its also NSNumber ( the first line of the code ) – ogres Nov 12 '15 at 10:38
  • I update the answer how it looks in the debugger. – BlackM Nov 12 '15 at 10:42
  • How are you using this predicate? What is `category_id`? Is it the property of some object? – Avi Nov 12 '15 at 10:44
  • Yes. I update the answer – BlackM Nov 12 '15 at 10:56
  • Why are you creating an array with the objects on an array that you just created?! `@[]` is EXACTLY the same as `[[NSArray alloc] initWithArray:]` so you are creating an array and use it to create an array with its contents. What for? – Julian F. Weinert Nov 12 '15 at 11:05
  • Also, can you please ensure you code is right? It seems you have written it in the question insert of c&p. You are searching an array of arrays. But if you'd do so in you'r real code, I think it would never work. – Julian F. Weinert Nov 12 '15 at 11:16
  • OK I updated the answer. The `arr2` is just for testing. I need to use `arr` – BlackM Nov 12 '15 at 12:11

2 Answers2

0

You are making minor but blatant mistake here. You are adding an array @[@1,@2,@4] as an object in the array category_array.

Try:

NSArray *category_array = [[NSArray alloc] initWithArray:@[@1,@2,@4]];

or simply

NSArray *category_array = @[@1,@2,@4];
Nishant
  • 12,529
  • 9
  • 59
  • 94
  • Sorry that was typo. Using that way is working fine. the problem is when I am adding NSNumber with `[array addObject:num]` – BlackM Nov 12 '15 at 10:48
  • @BlackM - Also, your `category_id` is String and not a Number. That could be an issue. – Nishant Nov 12 '15 at 10:50
  • Yes I know I just add it as String for simplicity. Anyway it was working with the first approach. I will try changing that and let you know – BlackM Nov 12 '15 at 10:51
  • Please add that working code as well to the question. – Nishant Nov 12 '15 at 10:59
  • The first block of code does not make any sense at all. Why should he allocate an array from an array? The `@[]` shortcut was created to replace the whole alloc-init-stuff. This just creates unnecessary overhead. – Julian F. Weinert Nov 12 '15 at 11:06
0

You are making a little mistake

try out this code

NSArray *category_array = @[@1,@2,@4];
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38