您的位置:首页 > 编程语言 > C语言/C++

黑马程序员13——OC语言之Category

2014-03-31 22:43 218 查看
1.Category概念 

OC提供了一种与众不同的方式—Category,可以动态的为已经存在的类添加新的行为(方法,不能添加成员变量)。 

这样可以保证类的原始设计规模最小,功能增加在逐步扩展。 

使用Category对类进行扩展时,不需要创建子类。 

Category使用简单的方式,实现了类的相关方法模块化,把不同的类方法分配到不同的分类文件中。 

2.Catogory的使用方法 

Student+test.h文件 

[plain] view
plaincopy

#import "Student.h"   

// ()代表一个分类,()中的test代表分类的名称   

@interface Student (test)   

   

//只能扩展方法,不能添加成员   

-(void)test2;   

   

@end   

Student+test.m文件 

[plain] view
plaincopy

#import "Student+test.h"   

   

-(void)test2   

{   

    NSLog(@"调用了test2方法");   

}   

@end <span style="font-size: 13.333333969116211px; font-family: 'Calibri Light', sans-serif;"> </span>  

main.m文件: 

[plain] view
plaincopy

#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]   

    }   

}   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: