前言:Category分类在项目中随处可见,那您系统地知道Category的使用场景和各种注意事项吗?本文先介绍Category的概念,然后介绍Category三种使用场景:系统类的扩展、第三方库类的扩展和自定义类的扩展;最后介绍了Category使用属性的问题,与Extension的区别,顺便介绍了Load和Initialize方法,并说明使用Category还是继承的关键。
一、Category概念与使用:
1、概念:利用Objective-C动态运行机制,可以为现有类(系统类、第三方库类、自定义类)添加新方法,这种为现有的类添加新方法的方式称为Category(也叫分类)。
Category编译之后的底层结构是struct category_t(如何查看底层结构,可以查看我的博客-OC对象的本质),里面存储着分类的对象方法、类方法、属性、协议信息等,在程序运行的时候,runtime会将Category数据合并到类信息中(类对象、元类对象中)。
2、使用场景:
a)、系统类的扩展:有时候我们需要给系统的类添加自己的属性或者方法,比如常见的UIView的扩展
// 只写一部分代码,抛砖引玉
// .h文件
@interface UIView (KMExtension)
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y; //类似
@end
// .m文件
@implementation UIView (KMExtension)
- (void)setX:(CGFloat)x {
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)x {
return self.frame.origin.x;
}
@end
比如图片缓存框架SDWebImage,其中UIImageView的扩展
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder;
b)、第三方库类的扩展:有时候我们需要改变第三方库方法的一些设置等,比如MJRefresh的上拉加载修改默认的方法设置,但不覆盖原来的方法
#import "MJRefreshAutoNormalFooter.h"
// .h文件
@interface MJRefreshAutoNormalFooter (KMExtension)
+ (instancetype)km_footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock;
@end
// .m文件
@implementation MJRefreshAutoNormalFooter (KMExtension)
+ (instancetype)km_footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock
{
MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
if (refreshingBlock) {
refreshingBlock();
}
}];
// 设置我们需要的字体颜色等
[footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
[footer.stateLabel setFont:[UIFont systemFontOfSize:14]];
[footer.stateLabel setTextColor:kDefaultFontColor3];
return footer;
}
@end
如果我们需要覆盖原来的方法,比如某个库有bug,那么我们可以使用Category重写原来的方法进行替换,在.m文件实现我们自己的代码;
c)、自定义类的扩展:反正是自定义的类,写一个扩展还不如在原来基础上进行修改方便,所以一般这种情况不适用扩展;
3、具体使用方法:
比如我们需要给UITextView添加分类,添加三个属性,一个测试方法,代码如下:
// .h文件
// 以下代码就是展示作用,实际操作更复杂
@interface UITextView (PlaceHolder)
@property (nonatomic, copy) NSString *placeholder;
@property (nonatomic, strong) UIColor *placeholderColor;
@property (nonatomic, assign) NSInteger wordsCount;
- (void)doRightThings;
@end
.m文件实现代码如下:
#import "UITextView+PlaceHolder.h"
#import <objc/runtime.h>
// 常见三种关联对象的key
static const char kPlaceHolder_Key; // 第一种方式
#define kPlaceHolderColor_Key @"kPlaceHolderColor_Key" //第二种方式
// @selector(xxx) 或者_cmd // 第三种方式
@implementation UITextView (PlaceHolder)
- (void)setPlaceholder:(NSString *)placeholder {
objc_setAssociatedObject(self, &kPlaceHolder_Key, placeholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)placeholder {
return objc_getAssociatedObject(self, &kPlaceHolder_Key);
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
objc_setAssociatedObject(self, kPlaceHolderColor_Key, placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIColor *)placeholderColor {
return objc_getAssociatedObject(self, kPlaceHolderColor_Key);
}
- (void)setWordsCount:(NSInteger)wordsCount {
objc_setAssociatedObject(self, @selector(wordsCount), [NSNumber numberWithInteger:wordsCount], OBJC_ASSOCIATION_ASSIGN);
}
- (NSInteger)wordsCount {
return [objc_getAssociatedObject(self, @selector(wordsCount)) integerValue];
}
- (void)doRightThings {
NSLog(@"doRightThings");
}
@end
运行代码:
- (void)viewDidLoad {
[super viewDidLoad];
UITextView *tv = [[UITextView alloc] init];
tv.placeholder = @"请输入账号";
CGFloat ratio = 0.3;
tv.placeholderColor = [UIColor colorWithRed:ratio green:ratio blue:ratio alpha:1.0];
tv.wordsCount = 10;
NSLog(@"placeholder = %@", tv.placeholder);
NSLog(@"placeholderColor = %@", tv.placeholderColor);
NSLog(@"wordsCount = %ld", tv.wordsCount);
[tv doRightThings];
}
结果:
placeholder = 请输入账号
placeholderColor = UIExtendedSRGBColorSpace 0.3 0.3 0.3 1
wordsCount = 10
doRightThings
这样,一个分类就完成了(当然,这个是简化的代码);
二、Category注意事项:
1、属性Property:
正常声明属性的时候,编译器会自动添加下划线成员变量、生成set和get的声明方法与实现方法,但是属性Property在Category中,只是在.h文件生成set和get声明方法,没有下划线成员变量和实现方法,所以如果需要在Category中添加属性,那么需要在.m文件实现set和get方法,可以使用runtime的关联对象来实现。
注意:在分类中直接声明成员变量,Xcode编译器会报错
@interface UITextView (PlaceHolder)
{
NSInteger _test; // Instance variables may not be placed in categories
}
@end
2、与Class Extension的区别:
在OC中,Class Extension 类扩展(也叫匿名分类),一般是在.m文件私有化属性和成员变量,在编译的时候,它的数据就已经包含在类信息中,而Category是在运行的时候,才会将数据合并到类信息中。
3、Category方法:
Category方法(类方法和实例方法)会覆盖原来类的方法,但是load方法不会覆盖,因为load方法没走objc_msgSend消息发送机制。
4、Load方法:
Load方法会在runtime加载类、分类时调用,且只会调用一次;运行顺序,先调用原来类的+load,再调用分类的+load方法,所以一般如果需要交换方法,都是在Category中load方法进行方法替换,比如友盟统计页面时长:
// .h文件
#import <UIKit/UIKit.h>
/// 友盟统计分类
@interface UIViewController (KMUMStatics)
@end
// .m文件
#import "UIViewController+KMUMStatics.h"
#import <UMAnalytics/MobClick.h>
@implementation UIViewController (KMUMStatics)
+ (void)load {
Method m1;
Method m2;
// 运行时替换方法,替换系统的viewWillAppear和viewWillDisappear
m1 = class_getInstanceMethod(self, @selector(statisticsViewWillAppear:));
m2 = class_getInstanceMethod(self, @selector(viewWillAppear:));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, @selector(statisticsViewWillDisappear:));
m2 = class_getInstanceMethod(self, @selector(viewWillDisappear:));
method_exchangeImplementations(m1, m2);
}
- (void)statisticsViewWillAppear:(BOOL)animated {
[self statisticsViewWillAppear:animated];
[MobClick beginLogPageView:NSStringFromClass([self class])];
}
-(void)statisticsViewWillDisappear:(BOOL)animated {
[self statisticsViewWillDisappear:animated];
[MobClick endLogPageView:NSStringFromClass([self class])];
}
@end
5、Initialize方法:
Initialize方法会在类第一次接受消息时调用,走objc_msgSend消息机制,会被Category方法覆盖。
6、选择Category还是继承:
关键是:是否需要一个新的子类,如果需要,那么使用继承,如果不需要,那么使用Category更好。这个需要在项目实践中好好体会。
觉得写的不错,有些启发或帮助,点个赞哦!