OC之category的用法

本文介绍如何在Objective-C中通过Category扩展现有类的功能,包括代码示例、应用场景以及总结最佳实践。

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

  • 简介
  • 实例
  • 好处

一、category简介

动态的为某个已经存在的类增加方法,不可以增加成员变量

二、实例

//
//  Student+CatetoryStudent.h
//  Category
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Student.h"

@interface Student (CatetoryStudent)

-(void) test;

@end
//
//  Student+CatetoryStudent.m
//  Category
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Student+CatetoryStudent.h"

@implementation Student (CatetoryStudent)

-(void)test
{
    NSLog(@"test");
}

@end
//
//  main.m
//  Category
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

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

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

    @autoreleasepool {
        
        Student *stu = [[[Student alloc] init] autorelease];
        
        [stu test];
        
    }
    return 0;
}

三、总结

在什么时候用category比较好?

1⃣️需求改变

2⃣️土堆合作

3⃣️对系统类扩展,比如给NSString类增加一个处理Json的方法

转载于:https://www.cnblogs.com/letougaozao/p/3625871.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值