开发者

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]];
     [Utili开发者_如何学运维ty 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?


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]; 
      }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜