类别和类扩展之间的区别? [英] Difference between Category and Class Extension?

查看:117
本文介绍了类别和类扩展之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类别和类扩展之间有什么区别.我相信两者都用于在现有类中添加自定义方法.有人可以对此进行解释吗?带有代码的示例将不胜感激.

What is the difference between a Category and a Class Extension. I believe both are used to add custom methods in existing classes. Can someone throw light on this? Examplification with code will be really appreciated.

推荐答案

类别是一种向现有类添加方法的方法.它们通常驻留在名为"Class + CategoryName.h"的文件中,例如"NSView + CustomAdditions.h"(当然还有.m).

A category is a way to add methods to existing classes. They usually reside in files called "Class+CategoryName.h", like "NSView+CustomAdditions.h" (and .m, of course).

一个类扩展是一个类别,除了两个主要区别之外:

A class extension is a category, except for 2 main differences:

  1. 类别没有名称.声明如下:

  1. The category has no name. It is declared like this:

@interface SomeClass ()

- (void) anAdditionalMethod;

@end

  • 扩展名的实现必须在文件的主@implementation块中.

  • The implementation of the extension must be in the main @implementation block of the file.

    在.m文件的顶部看到一个类扩展声明该类上的更多方法是很常见的,然后在该类的主要@implementation部分中实现这些方法.这是一种声明"pseudo-private"方法的方法(pseudo-private方法不是真正的私有方法,只是不对外公开).

    It's quite common to see a class extension at the top of a .m file declaring more methods on the class, that are then implemented below in the main @implementation section of the class. This is a way to declare "pseudo-private" methods (pseudo-private in that they're not really private, just not externally exposed).

    这篇关于类别和类扩展之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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