Category 分类,动态为已经存在的某个类动态添加方法,为以前的类扩展方法,但是不能添加成员变量,实现了类的相关方法的模块化,把不同的类的方法分配到不同的分类文件中,就像在Java开发中的struts或者spring配置文件模块化一样,便于分模块开发,并且可以扩展OC基础类库中的类。
#import
<Foundation/Foundation.h> @interface Student : NSObject @property (nonatomic,assign)int age; +(id)student; +(id)studentWithAge:(int)age; @end //创建一个名为Min分类 @interface Student (Min) -(void)min; @end |
#import
"Student.h" @implementation Student +(id)student{ return [[[Student alloc]init]autorelease]; } +(id)studentWithAge:(int)age{ //Student *stu=[Student student]; Student *stu=[self student]; //self指向当前类 stu.age=age; return stu; } @end //分类实现 @implementation Student(Min) -(void)min{ NSLog(@"调用了min方法"); } @end |
Student+Sum.h & Student+Sum.m
#import
"Student.h" @interface Student (Sum) //代表分类 Sum是分类的名称 -(void)sum; @end |
#import
"Student+Sum.h" @implementation Student (Sum) -(void)sum{ NSLog(@"sum执行"); } @end |
对NSString扩展
#import
<Foundation/Foundation.h> @interface NSString (Xml) +(void)createXml; @end |
#import
"NSString+Xml.h" @implementation NSString (Xml) +(void)createXml{ NSLog(@"创建了XmL文件"); } @end |
main
#import
<Foundation/Foundation.h> #import "Student.h" #import "Student+Sum.h" //导入分类所在的头文件 #import "NSString+Xml.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu=[Student student]; [stu min]; [NSString createXml]; } return 0; } |