OC Category 分类

1、Category

  • 1)分类/类别(category):

    • 允许以模块的方式向现有类定义添加新的方法(默认不能添加实例变量)。用以扩展自己或他人以前实现的类,使它适合自己的需要。

    • 分类的名称括在类名之后的一对圆括号 “( )” 中。

      1
      2
      3
      4
      5
      @interface QCStudent (Print)
      @end

      @implementation QCStudent (Print)
      @end
    • 分类文件名使用符号“+”来分隔类和分类的名字(Xcode 会自动生成)。

      1
      2
      QCStudent+Print.m
      QCStudent+Print.h
    • 分类用它可以将类的定义模块化到相关方法的组或分类中。它还提供了扩展现有类定义的简便方式,并且不必访问类的源代码,也无需创建子类。

    • 分类可以覆写该类中的另一个方法,但是通常认为这种做法是拙劣的设计习惯。一个类可以拥有多个分类。使用分类添加新方法来扩展类不仅会影响这个类,同时也会影响它的所有子类。分类为现有类添加新方法可能对你有用,但它们可能和该类的原始设计或意图不一致。对象/分类命名对必须是唯一的。

  • 2)分类中添加属性(实例变量):

    • iOS 开发中,分类默认不允许添加属性。

    • 但是如果在自己开发的框架中,希望在分类中动态添加属性,可以通过 OC 运行时的关联对象功能添加。在分类中,定义一个属性时,需要自己实现 getter & setter 方法,而且没有 _成员变量

    • 运行时非常重要的一个应用:给分类动态添加属性,结果能够让框架包装的更好,让使用者做出最小的修改。

2、向分类中添加方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// NSString+Path.h

@interface NSString (Path)

// 声明方法
- (NSString *)appendDocumentPath;

@end

// NSString+Path.m

@implementation NSString (Path)

// 实现方法
- (NSString *)appendDocumentPath {

NSString *dir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
return [dir stringByAppendingPathComponent:self.lastPathComponent];
}

@end

// ViewController.m

// 调用自定义方法
NSString *documentPath = [@"hello.png" appendDocumentPath];

3、向分类中添加属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// NSString+Path.h

@interface NSString (Path)

// 声明属性
@property (nonatomic, retain) NSURL *url;

@end

// NSString+Path.m

// 包含运行时头文件
#import <objc/runtime.h>

@implementation NSString (Path)

/**
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, const void *key)

参数:
object :属性的持有者
key :属性的键值
value :属性的数值
policy :属性的引用类型
*/

// 设置属性的键值
const void *UrlKey = @"UrlKey";

// 属性的 setter 方法
- (void)setUrl:(NSURL *)url {

// 用运行时方法设置属性的值
objc_setAssociatedObject(self, UrlKey, url, OBJC_ASSOCIATION_RETAIN);
}

// 属性的 getter 方法
- (NSURL *)url {

// 用运行时方法获取属性的值
return objc_getAssociatedObject(self, UrlKey);
}

@end

// ViewController.m

NSString *myStr = [[NSString alloc] init];

// 设置自定义变量的值
myStr.url = [NSURL URLWithString:@"http://123.com"];

// 获取自定义变量的值
NSURL *strUrl = myStr.url;
文章目录
  1. 1. 1、Category
  2. 2. 2、向分类中添加方法
  3. 3. 3、向分类中添加属性
隐藏目录