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.
objective-c protocols
PruitIgoe Jul 20 '12 at 15:44 2012-07-20 15:44
source share