Search code examples
objective-cloopsmessage-passingclass-method

Passing an identical message to multiple ObjC classes


I have multiple classes, all of which I want to send an identical message to. To be clearer:

I want to send doX:withClass: with the same parameters to a number of classes. Perhaps code would make it clearer:

+ (void)doX:(NSString *)blah {
     [Utility doX:blah withClass:[Foo class]];
     [Utility doX:blah withClass:[Bar class]];
     [Utility doX:blah withClass:[Baz class]];
     [Utility doX:blah withClass:[Garply class]];
}

I have three methods which do something similar on classes which implement a particular protocol (the doX:withClass: method performs a number of steps that assume that the classes given to it implements such a protocol).

My question is, how can I loop through the classes more programmatically, so I can simply add to a list (in code - not interested in being able to add at runtime) to add it to the loop?


Solution

  • My suggestion would be to pass an NSArray of Class objects:

     [Utility doX:blah withClasses:[NSArray arrayWithObjects:[Foo class], [Bar class], [Baz class], [Garply class], nil]];
    
     -(void) doX:(Blah) blah withClasses:(NSArray *) classes {
          //[classes makeObjectsPerformSelector:@selector(doX:) withObject:blah]
          for(Class *someClass in classes) {
             [Utility doX:blah withClass:someClass]; 
          }
    }