iOS --- Objective-C中的Category
来源:互联网 发布:微信淘宝优惠群机器人 编辑:程序博客网 时间:2024/05/16 19:45
Objective-C中的Category类似于Swift中的extension. 常用于给Int, NSString, NSArray等基本数据类型的对象进行一些方法的扩展.
主要有两种用途: 基本类型扩展和函数前向定义.
基本类型的扩展
如下例子, 可以给NSString添加reverse方法.
新建NSString+ReverseString的扩展类, 在.h中
// NSString+ReverseString.h@interface NSString (ReverseString)- (id)reverseString;@end
在.m文件中, 实现reverseString方法:
// NSString+ReverseString.m@implementation NSString (ReverseString)- (id) reverseString { NSUInteger len = [self length]; NSMutableString *returnStr = [NSMutableString stringWithCapacity:len]; while (len) { unichar c = [self characterAtIndex:--len]; // 两个字节 [returnStr appendString:[NSString stringWithFormat:@“%C”, c]]; } return returnStr;}@end
使用的时候非常简单:
#import “NSString+ReverseString.h"NSString *str = @“hello world”;NSString *reverseStr = [str reverseString];
注意: category中只能扩展方法, 而不能扩展属性.
函数前向定义
看这个应用场景: 在.m文件中, test1方法中调用test2, 但test2是在test1后边定义, 这是会带来一个函数前向定义的警告. 我们可以将test2放在.h文件中定义即可消除该警告, 那如果不想这样做呢, 可以使用category来实现.
在.m文件中使用category来定义test2, 即将test2私有化(外部不能访问), 同时不会带来函数前向定义的问题.
@interface Foo (Private)- (void)test2;@end@implementation xxx@end
具体代码就不贴上来了.
1 0
- iOS --- Objective-C中的Category
- objective-c中的category
- Objective-C中的Category(分类)
- 【iOS】Objective-C之Category的使用
- ios学习路线—Objective-C(Category)
- Objective-C中的Category的用法
- Objective-c 中的Category和Extension
- Objective-C中的类别(Category)
- 黑马程序员——Objective-C中的Category(类别)——黑马 IOS 技术博客
- Objective-C使用Category
- Category 类别 -Objective-C
- Category 类别 -Objective-C
- Objective-C分类 (category)
- Category 类别 -Objective-C
- Objective-C相关Category
- Objective-C之category
- Category 类别 -Objective-C
- Objective-C 分类Category
- Delphi的DataSource事件
- Activity生命周期的分析
- nginx详解
- SecureCRT连接linux,vim颜色显示问题
- hive grouping sets 和 cube 用法
- iOS --- Objective-C中的Category
- 网页字体参考
- linux配置虚拟IP地址方法
- [转载]tcp粘包分析
- 人丑就要多读书(9)
- Tuning NGINX for Performance nginx性能调优
- vim自动设置 textwidth 的问题
- OKHttp源码解析-ConnectionPool对Connection重用机制&Http/Https/SPDY协议选择
- 关于 被hao123 首页劫持问题!治标不治本的解决