Objective-C: Class versus Protocol [duplicate]

≯℡__Kan透↙ 提交于 2020-01-05 07:16:15

问题


I'm reading up on protocols (and thinking I might be able to rewrite some code using them) but I seem to be getting stuck on what exactly makes it different than a class?

For example, if I have a class ColorController:

#import <Foundation/Foundation.h>

@interface ColorController : NSObject { 

UIColor* colorToReturn;

}


- (UIColor* ) setColor : (float) red : (float) green : (float) blue; 

@end

and the .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];

this seems to make perfect sense to convert into a protocol, since a lot of other classes could use the setColor method. But I am not sure if my understanding of protocols is off, I thought that once a protocol was declared it would be available to other classes, but since you have to still include it in the .h files, the only discernible difference to me was that with a protocol the setColor method could be called directly in whatever class I have imported the protocol to, whereas with importing a class I would have to call back to the class and method [colorManager setColor:66.0:66.0:66.0]; What exactly would be the gain here?

Now my view is probably because I'm a newbie/inexperienced with protocols and have a limited view on them and their usage so if someone could give me a brief (other than "go read the docs" : D ) reply on the benefits of protocols and maybe an example of use I'd really appreciate it.


回答1:


A protocol does not give an implementation, only a declaration of some functionality. You would still have to implement the function(s) manually for any class that conforms to that protocol. (A common example of this is the delegate pattern). Protocols are similar to interfaces in java, if you are familiar to those.

edit removed dead link




回答2:


And ObjC protocol is a lot like a Java interface: - you don't have to implement your protocol - a class can implement more than one protocol, but only be subclassed from one class

So if you expect your class-or-protocol will only be used by one class, a subclass which inherits much of your behavior, then make a class. But if you expect more than one class to use your class-or-protocol, then make a protocol.



来源:https://stackoverflow.com/questions/11582685/objective-c-class-versus-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!