In Objective-C, I can add methods to existing classes with a category, e.g.
@interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
@end
Is it also possible to do this with protocols, i.e. if there was a NSString protocol, something like:
@interface <NSString> (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
@end
I want to do this since I have several extensions to NSObject (the class), using only public NSObject methods, and I want those extensions also to work with objects implementing the protocol .
To give a further example, what if I want to write a method logDescription that prints an object's description to the log:
- (void) logDescription {
NSLog(@"%@", [self description]);
}
I can of course add this method to NSObject, but there are other classes that do not inherit from NSObject, where I'd also like to have this method, e.g. NSProxy. Since the method only uses public members of protocol , it would be best to add it to the protocol.
Edit: Java 8 now has this with "virtual extension methods" in interfaces: http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf. This is exactly what I would like to do in Objective-C. I did not see this question earning this much attention...
Regards,
Jochen
question from:
https://stackoverflow.com/questions/1521267/defining-categories-for-protocols-in-objective-c 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…