Objective-C:类与协议 [英] Objective-C: Class versus Protocol

查看:67
本文介绍了Objective-C:类与协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读协议(并认为我可以使用它们重写一些代码),但我似乎一直在思考它与类的不同之处?

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?

例如,如果我有一个类 ColorController:

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

和.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];

这似乎非常适合转换为协议,因为许多其他类可以使用 setColor 方法.但是我不确定我对协议的理解是否已关闭,我认为一旦声明了协议,它就可以用于其他类,但是由于您仍然必须将它包含在 .h 文件中,因此对我来说唯一可辨别的区别是使用协议,可以在我将协议导入到的任何类中直接调用 setColor 方法,而在导入类时,我必须回调类和方法 [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?

现在我的观点可能是因为我是一个新手/对协议缺乏经验并且对它们及其用法的看法有限,所以如果有人能给我一个简短的(除了去阅读文档":D)回复协议的好处,也许是一个使用示例,我真的很感激.

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.

推荐答案

协议不给出实现,只给出一些功能的声明.您仍然必须为符合该协议的任何类手动实现函数.(一个常见的例子是委托模式).协议类似于java中的接口,如果你熟悉的话.

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.

编辑删除死链接

这篇关于Objective-C:类与协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆