【语法】category

本文深入探讨了Objective-C中的Category机制,一种在不改变类文件的前提下,为已有类动态添加新方法的独特技术。它允许在类设计保持稳定的同时,逐渐扩展功能,无需创建子类,实现类方法的模块化管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

category

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

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

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

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

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

 

category的使用场景

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

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

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

 

 

【例子】

Student.h
//
//  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
Student.m

 

//
//  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

【1.创建category】

【2.填写添加方法的内容】


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



Student+test.h
//
//  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
Student+test.m
//
//  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
main.m
//
//  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;
}

 

转载于:https://www.cnblogs.com/madeininfi/p/3534708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值