OC基础知识:分类Category
当我们需要在系统自带的类中添加自定义的方法时,可以对原有的类的方法进行扩展,这就是category。
1.主要用途
打开Xcode,在导航列表中点击右键,选择New File -->Objective-C File ,然后添加要新增的分类名称和选择要扩展的类。分类文件的名称通常格式为:UIView + NewImage.h 和 UIView + NewImage.m
在 .h文件中添加要新增的方法:#import<UIKit /UIKit.h>
@interface UIView (NewImage)
+(UIImageview *) defaultImageView;
@end
在.m文件里实现新增方法
#import“UIView + NewImage.h”
@implementation UIView (NewImage)
+(UIImageview *) defaultImageView{
UIImageView * imageView = [UIImageView alloc] initWithImage:[UIImage imageWithNamed:@"xxx"]];
return imageView;
}
@end
3.分类的使用
#import "ViewController.h"
#import“UIView + NewImage.h”
@interface ViewController ()
@property(nonatomic,strong) UIImageView * imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (_imageView == nil) {
_imageView = [UIImageView defaultImageView];
_imageView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview: _imageView];
}
}
- 不要用分类去重写已经存在的方法;
- 通过使用分类添加的方法,不仅针对该类有效,对于其子类也有效,例如:给UIView添加了分类,UIImageView、UIButton等子类也可以使用;
- 对象+分类必须名称唯一。