在上一篇文章 类别(Category)的作用(二)中,详细说明类别的第二个作用,接下来是类别的第三个作用。
类别作用三:向对象添加非正式协议。
一、概念
显然这个名词是相对于正式协议而言的。什么是正式协议,请自行找度娘。
苹果官方文档 Cocoa Core Competencies 一文中是这样介绍非正式协议的:
An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.
大概意思:非正式协议是NSObject类(显而易见,还包括它的子类)的类别,其所有的子类都含蓄地接受了这个协议。(类别是Objective-C的一个语言特点,可以让你在无需子类化的前提下为一个类增加方法。)非正式协议中的方法是否实现都是可选的,因此在调用非正式协议中的方法之前,需要去检查对象类是否实现了它。在Objective-C2.0中引入可选的正式协议方法之前,非正式协议是Foundation和AppKit类实现委托的唯一方式。
从以上可以看出,所谓的非正式协议就是类别,即凡是NSObject或其子类的类别,都是非正式协议。
二、代码说明
//NSObject+Addition.h
#import <Foundation/Foundation.h>
@interface NSObject (Addition)
- (void)testMethod;
@end
//NSObject+Addition.m
#import "NSObject+Addition.h"
@implementation NSObject (Addition)
- (void)testMethod {
NSLog(@"This is a testing Method");
}
@end
这个类别是NSObject的类别,因为几乎所有的OC的类都是NSObject的子类,所以所有的类只要import了这个头文件,就可以调用testMethod,这就是所谓的非正式协议。
文章参考:
1、http://blog.youkuaiyun.com/jiajiayouba/article/details/21105873
2、http://www.cnblogs.com/stevenwuzheng/p/5457487.html
3、http://blog.youkuaiyun.com/wzzvictory/article/details/9295317