类扩展 (Class Extension也有人称为匿名分类)
- 作用
能为某个类附加额外的属性,成员变量,方法声明
一般的类扩展写到.m文件中
一般的私有属性写到类扩展
- 使用格式:
@interface Mitchell()
//属性
//方法
@end
- 分类的区别
分类的小括号中必须有名字
@interface 类名(分类名字)
/*方法声明*/
@end
@implementation类名(分类名字)
/*方法实现*/
@end
分类只能扩充方法,不能扩展属性和成员变量(如果包含成员变量会直接报错)。
如果分类中声明了一个属性,那么分类只会生成这个属性的set、get方法声明,也就是不会有实现。
举例说明:如果我们分别在,类扩展与分类中添加了两个属性,
分类:
@interface UIButton (DelayControl)
/**
* 需要延迟的时间
*/
@property(nonatomic, assign) NSTimeInterval delayTimeInterval;
@end
类拓展
@interface UIButton ()
/**
* 需要延迟的时间
*/
@property(nonatomic, assign) NSTimeInterval delayTimeInterval;
@end
注意:
虽然我们再类别中声明属性不会报错,但是@property并没有自动为我们设置的属性生成set、get方法。
如果想要实现则需要使用到运行时中属性的动态挂载
本文转自:iOS - 类扩展与分类的区别