类别(Category)的作用(三)---添加非正式协议

在上一篇文章 类别(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.csdn.net/jiajiayouba/article/details/21105873
2、http://www.cnblogs.com/stevenwuzheng/p/5457487.html
3、http://blog.csdn.net/wzzvictory/article/details/9295317

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值