Objective-C基础笔记(4)Category
来源:互联网 发布:软件项目计划书 编辑:程序博客网 时间:2024/05/18 02:43
OC中提供了一种与众不同的方式--Category,可以动态的为已经存在的类添加新的行为(方法),这样可以保证类的原始设计规模较小,功能增加时再逐步扩展。
在使用Category对类进行扩展时,不需要创建子类,Category使用简单的方式,实现了类的相关方法的模块化,把不同的类方法分配到不同的分类文件中。
下面我们通过三个分类例子来看一下如何使用分类:
接着我们上一篇的代码,下面我们创建一个Student的Test分类,创建过程如下:
注意上面的Student+Test.h和Student+Test.m这两个文件就是我们为Student类创建的分类文件
Student+Test.h文件
#import "Student.h"@interface Student (Test)- (void)test;@endStudent+Test.m文件
#import "Student+Test.h"@implementation Student (Test)- (void) test { NSLog(@"调用了Student的Test分类的test方法");}@endmain.m文件
#import <Foundation/Foundation.h>#import "Student.h"#import "Student+Test.h"int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu = [[[Student alloc] initStudent:23] autorelease]; [stu test]; } return 0;}运行结果:
2014-11-16 11:32:00.861 内存管理[582:33690] 年龄为23的学生被创建了
2014-11-16 11:32:00.862 内存管理[582:33690] 调用了Student的Test分类的test方法
2014-11-16 11:32:00.862 内存管理[582:33690] 年龄为23的学生被释放了
分类除了这种写法其实可以直接写到Student.h和Student.m中,而不用单独创建文件。我们也可以给系统的类(NSString)进行分类,比如我们给NSString添加一个处理json的方法。#import <Foundation/Foundation.h>@interface NSString (JSON)+ (void)json;@end
#import "NSString+JSON.h"@implementation NSString (JSON)+ (void) json{ NSLog(@"{'nam':'CodeingSnal', 'age',24");}@end
分类的使用场景:
1、在定义类的某些情况下(例如需求变更),你可能需要给其中的某个或某几个类添加新的方法。
2、一个类中包含了许多不同种类的方法需要实现,而这些方法需要不同的团队的成员实现。
3、在使用基础类库的类时,有可能希望这些类实现一些自己需要的方法,比如写个NSString+JSON.h,为NSString这个类拓展一些解析JSON的方法。
4 0
- Objective-C基础笔记(4)Category
- 【Objective-C基础】类别Category
- Objective-C - category学习笔记
- Objective C基础(四)---Category、Extension、Protocol
- Objective-C学习笔记(二)–Category和Extension
- Objective-c Category(类别)
- 学习笔记(objective-c)-类别(category)
- Objective-C基础笔记
- Objective-C 入门(六)category 分类
- objective-c类别(Category)详细解说
- 【深入浅出Objective-C】4.5分类(category)
- Objective-C中的类别(Category)
- Objective-C使用Category
- Category 类别 -Objective-C
- Category 类别 -Objective-C
- Objective-C分类 (category)
- Category 类别 -Objective-C
- Objective-C相关Category
- 第十二周上机项目三
- HDU 5095 Linearization of the kernel functions in SVM(模拟)
- POJ 2406--Power Strings(kmp算法)
- 实验四
- hdu 5104 Primes Problem(数学)
- Objective-C基础笔记(4)Category
- JAVA的反射机制与动态代理
- LeetCode - Text Justification 题解
- ASP.NET动态网站开发培训-24.论文管理系统(四、制作Login页面和后台论文管理主页)
- 2014.11.15
- 学习资料(一)
- U3d学习第一天---界面布局更改及基本操作
- iOS 笔试题
- 3 - IOS之cocos3d - 2 - 把blender导出的3D文件加载到cocos3d