Objective-c - 类别和协议的目的 [英] Objective-c - Purpose of categories and protocols
问题描述
我一直在阅读Objective-c Protocols and Categories,这对我来说似乎毫无意义。它们都用于以一些有趣的方式向程序中添加内容,而不仅仅是手动添加它。
I've been reading up on Objective-c Protocols and Categories and both seem rather pointless to me. They're both used for adding things to the program in some funny way instead of just manually adding it.
我可能会确信协议的目的是这样的你可以检查id的类型,但那真的是关于它的。我认为没有其他真正的用途。
I might be convinced to see the purpose of the protocol being so that you can check the type of id's, but that's really about it. I see no other real use for them.
至于类别,我真的不明白为什么你不会只是将它们添加到代码中。为什么你需要手动指定一个类别中的方法,而不是正常执行?您是否想要制作一个子类但稍作修改?为什么不做一个子类?
As for categories, I really don't see why you wouldn't just add them to the code. Why do you need to manually specify methods in a category that you're then gonna implement as opposed to just doing it normally? Is it that you might wanna make a "subclass" but with slight modifications? Why not just make a subclass?
我真的没有看到其中任何一个的目的,我希望有人可以告诉我他们真正的用途= /
I really don't see the purpose of either of these, I hope someone can tell me their real use =/
提前致谢,
Christian
Thanks in advance, Christian
推荐答案
类别是添加方法到你的源不可用的类,例如所有Apple类(以NS,CG,CA等开头的类),而不需要对它们进行子类化。
Categories are to add methods to classes whose source is unavailable to you, such as all the Apple classes (those starting with NS, CG, CA, etc.), without needing to subclass them.
协议的目的是定义遵循该协议的类必须实现的方法。在Java中,那些被称为接口。目的是编纂不是兄弟姐妹的类(同一超类的子类)之间的相似性。假设您有一个类主席
和一个类 Petrol
。这些没有很多共同之处,只是它们都遵循易燃
协议,这要求它们具有某些方法,例如 specificEnergy
和 flamingPoint
。
The purpose of protocols is to define methods that classes adhering to that protocol have to implement. In Java, those are called interfaces. The purpose is to codify similarities between classes that are not siblings (subclasses of the same superclass). Suppose you have a class Chair
and a class Petrol
. These don't have a lot in common, except that they both adhere to the flammable
protocol, which requires them to have certain methods, such as specificEnergy
and flamingPoint
.
现在你的 Fire
class可以有一个方法 addFlammableMaterial:(id< flammable>)material
。
Now your Fire
class can have a method addFlammableMaterial:(id <flammable>)material
.
协议是通常用于声明某些类的实例可以是某些其他实例的委托。您可以声明视图控制器作为 UITableView
的数据源,声明它符合 UITableViewDataSource
协议,这意味着你的viewController保证它实现了该协议所需的方法,并且tableView可以安全地休息,因为它可以信任VC作为它的数据源。
Protocols are often used to declare that instances of certain classes can be delegates for certain other instances. You can declare your view controller to act as the data source to a UITableView
by declaring it to conform to the UITableViewDataSource
protocol, which means your viewController guarantees that it implements the required methods of that protocol, and the tableView can rest safely because it can trust the VC to be its data source.
这篇关于Objective-c - 类别和协议的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!