Passing an identical message to multiple ObjC classes
-
29-09-2019 - |
Question
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];
}
}
OTHER TIPS
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.