How do you decorate a class with some generic implementation of a protocol?
Sorry for what might be an obvious question. I'm new to objective c and so am still treading water just a little bit.
I've got a protocol for which I want a generic implementation:
@protocol SelectableElement <NSObject>
@property BOOL selected;
@end
I've got a couple of objects that I want to be selectable:
@interface Widget : NSObject <SelectableElement>
@end
@interface Duhicky : NSObject <SelectableElement>
@end
What I'd like to do is to write the implementation of the protocol once, and make sure that both objects implement it that way.
I don't think that I can write a generic category and bind it to both, so I guess one way of doing it is to add implement the category on the common class NSObject:
@implementation NSObject (Selectable)
- (BOOL)selectable
{
if (![self conformsToProtocol:@protocol(SelectableElement)]) return;
return YES; // Use associative storage for this?
}
- (void)setSelectable:(BOOL)selectable
{
if (![self conformsToProtocol:@protocol(SelectableElement)]) return;
// set this associatively?
}
@end
Of course, I can't define a property variable to do this, I would need to use the associative object store... which I've not demonstrated here.
Is this the only way of adding selectable behaviour generically to anything that implements the selectable element protocol? Or is there a more obvious way that I'm missing?
I can of course use inheritance to implement this simple example, but that would only work for implementing a single protocol in this way. Is this approach that I've suggested considered a natural fit, or is it a hack?
Joe