How can I access specific subsets of a large NSDictionary in Cocoa?

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

How can I at different times in my program get an NSDictionary (or NSArray) that contains different groups of these objects? In one case, I will need all B, but next time I will need all C objects, as well as B objects that satisfy (kindOfCIsh == true).

Is there an easy way to access these subsets? Perhaps using filter predicates? Of course, I can skip the entire dictionary and collect the necessary subset manually, but I have a feeling that there is a better way.

Any help is appreciated.

+3
source share
2 answers

[[myDictionary allValues] filterArrayUsingPredicate: pred];

+8
source

You can use categories

the code looks 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
+1
source

All Articles