分类能够做到的事情主要是:即使在你不知道一个类的源码情况下,向这个类添加扩展的方法。此外,分类能够保证你的实现类和其他的文件区分开。
(1) Category的方法不一定非要在@implementation中实现,也可以在其他位置实现,但是当调用Category的方法时,依据继承树没有找到该方法的实现,程序则会崩溃。
(2) Category理论上不能添加变量,但是可以使用@dynamic来弥补这种不足。 (即运行时Runtime)
普通类的头文件是这样的
.h
@interface ViewController : UIViewController
@end
.m
@interface ViewController ()
@end
分类(匿名类别)
.h
@interface UIView (classView)
@end
.m
@implementation UIView (classView)
@end
类扩展(Class Extension也有人称为匿名分类)

网友评论