views:

432

answers:

2

I have a single NSDictionary object which contains a large number of custom objects. The objects will either be of class B or of class C, both of which inherit from class A. If the objects are of type B, they will have an internal flag (kindOfCIsh) which will be used for future grouping.

How can I, at different times in my program, get an NSDictionary (or NSArray) that contains different groupings of those objects? In one case, I will want all of B, but another time I will want all of the C objects, plus the B objects that satisfy (kindOfCIsh == true).

Is there a simple way to get access to these subsets? Perhaps using filter predicates? I can, of course, loop through the entire dictionary and build the required subset manually, but I have a feeling that there is a better way.

Any help is appreciated.

+1  A: 

You can use categories

the code is something like this

@interface NSDictionary (dictionaryForClass)

  -(NSMutableDictionary *) dictionaryWithObjectsKindOfClass:(Class)myClass;

@end

@implementation NSDictionary (dictionaryForClass)

-(NSMutableDictionary *) dictionaryWithObjectsKindOfClass:(Class)myClass;
{
  NSMutableDictionary *ret = [[[NSMutableDictionary alloc] init] autorelease];

  for (id object in self) {
    if ([object isKindOfClass:myClass]) {
       [ret addObject:object];
    }  
  }  
  return ret;

}

@end
Igor
Thank you for the answer, hellra1ser. It is still, essentially a loop through all of the elements, but I like that it is tucked away in a category.
e.James
+3  A: 

[[myDictionary allValues] filteredArrayUsingPredicate: pred];

Graham Lee
It looks like predicates will be the way to go. Thank you.
e.James