views:

78

answers:

2

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?

+4  A: 

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]; 
      }
}
Jacob Relkin
You could change the body to `[classes makeObjectsPerformSelector:@selector(doX:) withObject:blah]`.
mipadi
Well, I don't want the classes to perform a selector; I want the Utility class to run a method with the Class as an argument. This is because the objects it's operating on need to remain simple and abstracted from the behavior I want the Utility class to perform on classes that implement that particular interface. Thanks, though -- I didn't realize classes could be directly added to an array; I thought they'd have to be encapsulated somehow instead.
Andrew Toulouse
@Andrew, I updated my answer.
Jacob Relkin
+1  A: 

Not sure you really want to loop here.

If it were me I'd probably try to have Foo, Bar, Baz and Garply to extend some base class that defines doX. Then you could have your base class observe blah and call doX when it changes. But maybe I'm not understanding what you're trying to do.

mariachi