分类(category)和类扩展(extension) 详解

什么时候使用分类(category)呢?

比如:


eg.1,我们已经写了很多的页面了,然后要所有类都要添加一个方法,用来收集一些信息,并且这些页面都继承自UIViewController中,我们就可以把代码添加到UIViewController就可以了。

eg.2,我们想要在原来类里边重写方法,或者添加自定义方法的时候,可以使用category来实现。


分类(category)中只能添加方法,不能添加成员变量;

分类(category)只能访问原来类的@protect@public成员变量,不能访问私有成员变量,如果非要访问的话,不能直接访问,但是可以写方法来访问;

分类(category)其实里边是可以添加成员变量的,category添加成员变量传送门

分类的添加过程如下:





然后生成的类JWTest1ViewController+unlock.h我们可以看到,.h文件如下


#import "JWTest1ViewController.h"


@interface JWTest1ViewController (unlock) // JWTest1ViewController 是原来的类 unlock是分类


- (void)userUnlock; // 这个是我们添加的方法


@end


.m文件如下


#import "JWTest1ViewController+unlock.h"


@implementation JWTest1ViewController (unlock)


- (void)userUnlock{

    NSLog(@"userUnlock");

}


@end


如何不用每个类里边都要添加头文件才能引用?还有分类的优先级是怎么样的呢?

下面我们来看一下类扩展(extension

其实类扩展我们经常见到,项目中也经常用到;先来看一下JWTest1ViewController.m中的代码


#import "JWTest1ViewController.h"


@interface JWTest1ViewController () // 这里就是类扩展(extension


@end


@implementation JWTest1ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


类扩展是category的一个特例,也叫匿名分类,为该类添加一些属性和方法。

并且写在.m中的变量和方法都是私有的,写在.h中的变量和方法就是公共的。


猜你喜欢

转载自blog.csdn.net/jwheat/article/details/79965682
今日推荐