Objective-C: class versus protocol

I read the protocols (and I think I can rewrite some code using them), but I seem to be fixated on what exactly makes it different from the class?

For example, if I have a ColorController class:

#import <Foundation/Foundation.h> @interface ColorController : NSObject { UIColor* colorToReturn; } - (UIColor* ) setColor : (float) red : (float) green : (float) blue; @end 

and .m

 #import "ColorController.h" @implementation ColorController - (UIColor* ) setColor : (float) red : (float) green : (float) blue { float newRed = red/255; float newGreen = green/255; float newBlue = blue/255; colorToReturn = [UIColor colorWithRed:newRed green:newGreen blue:newBlue alpha:1.0]; return colorToReturn; } @end 

and then import it into another class:

 ColorController* colorManager = [ColorController new]; UIColor* newColor = [colorManager setColor:66.0:66.0:66.0]; 

it seems like it makes sense to convert to a protocol, as many other classes can use the setColor method. But I'm not sure my understanding of protocols is disabled. I thought that as soon as the protocol is announced, it will be available for other classes, but since you should include it in the .h files anyway, the only noticeable difference for me was that using the protocol, the setColor method can be called directly in any class, in which I imported the protocol, while importing the class I would have to call the class and method back [colorManager setColor: 66.0: 66.0: 66.0]; What exactly would happen here?

Now my opinion is probably due to the fact that I am new / inexperienced with the protocols and have a limited look at them and their use, so if someone can give me a brief (besides "go read docs": D) answer the benefits of the protocols and perhaps an example of use, I would really appreciate it.

+1
objective-c protocols
Jul 20 '12 at 15:44
source share
2 answers

The protocol does not provide implementation, but only a declaration of some functionality. You still have to perform functions manually for any class that conforms to this protocol. (A common example of this is the delegate template). Protocols are similar to interfaces in java if you are familiar with them.

edit deleted dead link

+2
Jul 20 2018-12-15T00:
source share

And the ObjC protocol is much like the Java interface: - you do not need to execute your protocol - a class can implement more than one protocol, but only subclasses from one class

So, if you expect your protocol class to be used by only one class, a subclass that inherits most of your behavior, then create a class. But if you expect more than one class to use your protocol class, then create a protocol.

+1
Jul 20 '12 at 15:53
source share



All Articles