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 <span style="font-size: 13.333333969116211px; font-family: 'Calibri Light', sans-serif;"> </span>
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]
- }
- }