timpone
timpone

Reputation: 19979

how to make array of different objects work well with NSPredicate

I have an array of different objects. One object is CTVMenuItem which has a menuHeaderID. I'd like to get all the items which have a menuHeaderID of 12 AND are of Class CTVMenuItem. How would I do this?

I have:

  // lets test this
  NSMutableArray *testArray=[[NSMutableArray alloc] init];
  // lets add an item
  CTVMenuHeader *mh1=[[CTVMenuHeader alloc] init];
  mh1.name=@"menu-header 1";
  [testArray addObject:mh1];

  CTVMenuItem *mi1=[[CTVMenuItem alloc] init];
  mi1.name=@"sub1 - menu item name #1";
  mi1.menuHeaderID=@11;
  [testArray addObject:mi1];

  CTVMenuItem *mi2=[[CTVMenuItem alloc] init];
  mi2.name=@"sub1 - menu item name #2";
  mi2.menuHeaderID=@12;
  [testArray addObject:mi2];

  NSLog(@"here is array %@", testArray);
  // ?????
  NSArray *selected=[testArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"menuHeaderID == %i", 12]];
  NSLog(@"here is selected %@", selected);

Upvotes: 0

Views: 20

Answers (1)

sam-w
sam-w

Reputation: 7687

For the example above, you want:

[testArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:
  @"(class == %@) AND (menuHeaderID == %i)",
  [CTVMenuItem class],
  12]];

Note that you must test the object type first, before checking menuHeaderID. Swap the two around to see why.

Upvotes: 1

Related Questions