views:

1462

answers:

5

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.

Regards, Jochen

+6  A: 

It isn't really meaningful to do so since a protocol can't actually implement the method. A protocol is a way of declaring that you support some methods. Adding a method to this list outside the protocol means that all "conforming" classes accidentally declare the new method even though they don't implement it. If some class implemented the NSObject protocol but did not descend from NSObject, and then you added a method to the protocol, that would break the class's conformance.

You can, however, create a new protocol that includes the old one with a declaration like @protocol SpecialObject <NSObject>.

Chuck
A: 

I think you may be mixing up terms here and there. Extensions, Categories, Protocols, Interfaces and Classes are all different things in Objective-C. In The Objective-C 2.0 Language Apple describes the differences very well, including the benefits and drawbacks to using categories and extensions.

If you think about it, what is a "Category" or "Extension" in the conceptual sense? It's a way of adding functionality to a Class. In Objective-C, protocols are designed to have no implementation. Therefore, how would you add or extend the implementation of something that doesn't have implementation to begin with?

slf
+3  A: 

Short answer: No.

Long answer: how would this work? Imagine you could add methods to existing protocols? How would this work? Imagine we wanted to add another method to NSCoding, say -(NSArray *) codingKeys; This method is a required method that returns an array of the keys used to encoding the object.

The problem is that there are existing classes (like, say NSString) that already implement NSCoding, but don't implement our codingKeys method. What should happen? How would the pre-compiled framework know what to do when this required message gets sent to a class that does not implement it?

You could say "we can add the definition of this method via a category" or "we could say that any methods added via these protocol categories are explicitly optional". Yes, you could do this and theoretically get around the problem I've described above. But if you're going to do that, you might as well just make it a category in the first place, and then check to make sure the class respondsToSelector: before invoking the method.

Dave DeLong
I think in theory this could work. Since Objective-C allows adding methods to existing classes with class_addMethod, I could get all defined classes, check if they implement a specific protocol and then add my method to the class (since it only uses the protocol's methods, it does not depend on the class). The question came up because we wanted to define an "extended protocol method" once, and not for every class, and have the compiler know about this, so it doesn't have to throw warnings. So even if we can do this with the runtime, the compiler warnings still are there.
Jochen
I think that in reality it can work too. C# 3.0 allows to extend interfaces via static classes. It is different mechanism than categories, because it is only syntatic sugar. In Objective-C category really adds methods to class.
Filip Kunc
Here's why it would be useful to add methods to existing protocols:Let's say you have a category on `NSObject` defining `-foo`, and a category on `UIApplication` defining `-bar`.In `-bar`, you want to call `[self.delegate foo]`. `UIApplicationDelegate` conforms to `NSObject`. How do you convince the compiler that calling `-foo` on `self.delegate` is fine?
hatfinch
@hatfinch red herring. You wouldn't put the method on `<NSObject>` (the protocol), you'd put it on `NSObject` (the class). However, I think the entire premise is wrong. Generally, if you find you have to access the application instance to achieve proper functionality, then you probably need to rethink your app's architecture.
Dave DeLong
@hatfinch the `<NSObject>` protocol exists so that you can declare variables as `id<SomeProtocol> someVar;` and not get a warning when you try to `[someVar retain];`. `<SomeProtocol>` would be declared as `@protocol SomeProtocol <NSObject>`, thereby giving any `<SomeObject>` the standard `retain`, `release`, `respondsToSelector:`, etc methods.
Dave DeLong
I just used `UIApplicationDelegate` as an example; the point stands for any delegate. I understand the purpose of `<NSObject>`, I just think it would be useful to be able to extend it (in particular, or any protocol in general). For instance, it would be really useful if `-performSelectorOnMainThread:...` etc. were in `<NSObject>`.
hatfinch
Here's a place where this feature would be useful: I have a field in a class of type `id<MyProtocol>`, where `MyProtocol` includes `<NSObject>`. I've used a category to add a method to `NSObject`, and want to call that method on this field, but the compiler produces a warning. I wish my category method could be added to `<NSObject>`.
executor21
@Executor21 so instead of declaring it as `id<MyProtocol> foo`, declare it as `NSObject<MyProtocol> *foo`.
Dave DeLong
NSObject<MyProtocol> only works if it's an NSObject. What if it's e.g. a NSProxy. I added a sample for this.
Jochen
@Jochen it's possible that there are extreme edge cases where this might be useful, but in the years that I've been doing Cocoa development, I've *never* come across a situation where I needed this and couldn't work around it.
Dave DeLong
A: 

if you're already writing a category, why not just add in the protocol definition in the header right after the category definition?

i.e.

@interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
@end

@protocol MyExtendedProtocolName <NSString>
//Method declarations go here
@end

this way any class that imports the category header will also get the protocol definition, and you can add it into your class..

@interface MyClass <OriginalProtocol,MyExtendedProtocolName>

also, be careful when subclassing NSString, it's a cluster and you may not always get the behaviour you're expecting.

pxl
A: 

While it's true that you can't define categories for protocols (and wouldn't want to, because you don't know anything about the existing object), you can define categories in such a way that the code only applies to an object of the given type that has the desired protocol (sort of like C++'s partial template specialization).

The main use for something like this is when you wish to define a category that depends on a customized version of a class. (Imagine that I have UIViewController subclasses that conform to the Foo protocol, meaning they have the foo property, my category code may have need of the foo property, but I can't apply it to the Foo protocol, and if I simply apply it to UIViewController, the code won't compile by default, and forcing it to compile means someone doing introspection, or just screwing up, might call your code which depends on the protocol. A hybrid approach could work like this:

@protocol Foo
- (void)fooMethod

@property (retain) NSString *foo;
@end

@implementation UIViewController (FooCategory)

- (void)fooMethod {
    if (![self conformsToProtocol:@protocol(Foo)]) {
        return;
    }

    UIViewController<Foo> *me = (UIViewController<Foo>*) self;
    // For the rest of the method, use "me" instead of "self"
    NSLog(@"My foo property is \"%@\"", me.foo);
}
@end

With the hybrid approach, you can write the code only once (per class that is supposed to implement the protocol) and be sure that it won't affect instances of the class that don't conform to the protocol.

The downside is that property synthesis/definition still has to happen in the individual subclasses.

Douglas Mayle