I have a series of \"policy\" objects which I thought would be convenient to implement as class methods on a set of policy classes. I have specified a protocol for this, and
A class in Objective-C does work like an instance -- the main underlying difference is that retain counting does nothing on them. However, what you're storing in the -availableCounters array aren't instances (the id
type) but classes, which have a type of Class
. Therefore, with the -availableCounters definition you specified above, what you need is this:
Class counterClass = [[MyModel availableCounters] objectAtIndex: self.index];
return ( [counterClass countFor: self] );
However, it would probably be semantically better if you used instances rather than classes. In that case, you could do something like the following:
@protocol Counter
- (NSUInteger) countFor: (Model *) model;
@end
@interface CurrentListCounter : NSObject
@end
@interface SomeOtherCounter : NSObject
@end
Then your model class could implement the following:
static NSArray * globalCounterList = nil;
+ (void) initialize
{
if ( self != [Model class] )
return;
globalCounterList = [[NSArray alloc] initWithObjects: [[[CurrentListCounter alloc] init] autorelease], [[[SomeOtherCounter alloc] init] autorelease], nil];
}
+ (NSArray *) availableCounters
{
return ( globalCounterList );
}
Then your use of that would be exactly as you specified above:
id counter = [[Model availableCounters] objectAtIndex: self.index];
return ( [counter countFor: self] );