1.Category概念
OC提供了一种与众不同的方式—Category,可以动态的为已经存在的类添加新的行为(方法,不能添加成员变量)。
这样可以保证类的原始设计规模最小,功能增加在逐步扩展。
使用Category对类进行扩展时,不需要创建子类。
Category使用简单的方式,实现了类的相关方法模块化,把不同的类方法分配到不同的分类文件中。
2.Catogory的使用方法
Student+test.h文件
#import "Student.h"
// ()代表一个分类,()中的test代表分类的名称
@interface Student (test)
//只能扩展方法,不能添加成员
-(void)test2;
@end
Student+test.m文件
#import "Student+test.h"
-(void)test2
{
NSLog(@"调用了test2方法");
}
@end
main.m文件:
#import<Foundation/Foundation.h>
#import "Student.h"
//导入分类
#import "Student+Test.h"
int main(int argc,const char *argv[])
{
@autoreleasepool
{
Student *stu = [[Student alloc]init]autorelease];
//调入分类方法
[stu test2]
}
}
3.Category的使用场景
定义某些类的情况下(例如需求变更),你可能想要为其中的某个或者几个类添加新的方法。
一个类中包含了许多不同类的方法需要实现,而这些方法需要不同的团队的成员实现。
使用基础类库的类时,又可能希望这些实现一些自己需要的方法。比如写个NSString+JSON.h,为NSString这个类拓展一些解析JSON的方法。