IOS开发中的协议,扩展和类别有什么区别?以及如何恰当地使用它们? [英] What is the difference between protocol, extension and category in IOS development? And how to use them appropriately?

查看:308
本文介绍了IOS开发中的协议,扩展和类别有什么区别?以及如何恰当地使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另外,Swift和Objective-C语言之间的这3件事有什么不同吗?谢谢。

Also, is there any difference for these 3 things between Swift and Objective-C languages? Thanks.

推荐答案

协议



协议声明任何类可以选择实现的编程接口。

Protocols

A protocol declares a programmatic interface that any class may choose to implement.

协议定义了适合特定任务或部分的方法,属性和其他要求的蓝图功能。协议就像接口一样,它提供了符合类的方法必须实现的一些方法。

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols are like Interfaces, that provide some methods that the class conforming must implement.

使用:


  • 一个常见的用例是让你改变某些类的行为,而不需要对它们进行子类化。

  • 例如: UITableViewDelegate UITableViewDataSource

  • A common use case is to let you alter the behavior of certain classes without the need to subclass them.
  • Eg: UITableViewDelegate, UITableViewDataSource

另见协议

扩展为现有的类,结构,枚举或协议类型添加新功能。这包括扩展您无法访问原始源代码的类型的能力(称为追溯建模)。

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

扩展类似于Objective-C中的类别。 (与Objective-C类别不同,Swift扩展名没有名称。)

Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

使用:


  • 类别是一种通过将实现扩展到许多文件来模块化类的方法。扩展提供了类似的功能。

  • Categories are a way to modularize a class by spreading its implementation over many files. Extensions provide similar functionality.

类别最常见的用途之一是向内置数据类型添加方法,如 NSString NSArray 。这样做的好处是您不必更新现有代码以使用新的子类

One of the most common uses of categories is to add methods to built-in data types like NSString or NSArray. The advantage of this is that you don’t have to update existing code to use a new subclass

扩展程序和类别在 Objective-C

中有一些区别注意:以下情况仅适用于Objective-C

类别允许您在主界面文件之外添加方法。而扩展必须在主接口文件中实现。这意味着我们可以安全地断定您不能使用扩展来扩展您没有源代码的内置类或类,您应该使用类别。要使用扩展,您需要访问要扩展的类的源。

Categories allow you to add methods outside of the main interface file. Whereas Extensions must be implemented in main Interface file. Which means we can safely conclude you cannot use extensions for extending Builtin classes or Classes for which you don't have the source code, there you should use Categories. And to use extensions you need access to the source of the class you are extending.

这篇关于IOS开发中的协议,扩展和类别有什么区别?以及如何恰当地使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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