【语法】category

category

category(分类)就是在不改变类文件的前提下,然后动态添加类的方法                             

  1.oc提供了一种与众不同的方式--catagory,可以动态的为已经存在的类添加新的行为(方法)

  2.这样可以保证类的原始设计规模比较小,功能增加时间在逐步扩展

  3.使用category对类惊醒扩展时间,不需要创建子类

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

 

category的使用场景

  1.在定义类时的某些情况下(例如需求变更),你可能想要位其中的某个或几个类中添加新的方法

  2.一个类中包含了许多不同种类的方法需要实现,而浙西方法需要不同团队的成员实现

  3.在使用基础类库中的类时,有可能希望这些类实现一些自己需要的方法,比如写一个NSString+JSON.h为NSString着个类拓展一些解析JSON的方法。

 

 

【例子】

Student.h
【语法】category
//
//  Student.h
//  category
//
//  Created by 裴烨烽 on 14-1-27.
//  Copyright (c) 2014年 裴烨烽. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Student : NSObject

-(void)test;



@end
【语法】category
Student.m

 

【语法】category
//
//  Student.m
//  category
//
//  Created by 裴烨烽 on 14-1-27.
//  Copyright (c) 2014年 裴烨烽. All rights reserved.
//

#import "Student.h"

@implementation Student

-(void)test{
    NSLog(@"调用了text方法");
}
@end
【语法】category

【1.创建category】
【语法】category
【2.填写添加方法的内容】

【语法】category
【3.项目栏多出两个category文件】

【语法】category



Student+test.h
【语法】category
//
//  Student+test.h
//  category
//
//  Created by 裴烨烽 on 14-1-27.
//  Copyright (c) 2014年 裴烨烽. All rights reserved.
//

#import "Student.h"//告诉文件要给哪个文件添加类。

@interface Student (test)//()括号代表的是分类,()中的test代表分类的名称
-(void)test2;
//方法只能拓展方法。
@end
【语法】category
Student+test.m
【语法】category
//
//  Student+test.m
//  category
//
//  Created by 裴烨烽 on 14-1-27.
//  Copyright (c) 2014年 裴烨烽. All rights reserved.
//

#import "Student+test.h"

@implementation Student (test)

-(void)test2{

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



@end
【语法】category
main.m
【语法】category
//
//  main.m
//  category
//
//  Created by 裴烨烽 on 14-1-27.
//  Copyright (c) 2014年 裴烨烽. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Student+test.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        Student *stu=[[Student alloc] init];
        [stu test];
        [stu test2];
        
    }
    return 0;
}
【语法】category

【语法】category

上一篇:WAMP自己DIY添加apache、php、mysql版本


下一篇:SQL Server 2005中的分区表(六):将已分区表转换成普通表(转)