向OC类中添加默认的协议实现(ProtocolKit)
以forkingdog的PorotocolKit举例
举例
ProtocolKit Protocol extension for Objective-C Usage Your protocol: @protocol Forkable <NSObject> @optional
- (void)fork; @required
- (NSString *)github; @end
Protocol extension, add default implementation, use @defs magic keyword @defs(Forkable) - (void)fork {
NSLog(@"Forkable protocol extension: I'm forking (%@).", self.github);
} - (NSString *)github {
return @"This is a required method, concrete class must override me.";
} @end
Your concrete class @interface Forkingdog : NSObject <Forkable>
@end @implementation Forkingdog - (NSString *)github {
return @"https://github.com/forkingdog";
} @end
Run test [[Forkingdog new] fork];
Result [Console] Forkable protocol extension: I'm forking (https://github.com/forkingdog).
实现
我们可以看到关键字是@def 查看其定义是
// For a magic reserved keyword color, use @defs(your_protocol_name)
#define defs _pk_extension // Interface
#define _pk_extension($protocol) _pk_extension_imp($protocol, _pk_get_container_class($protocol)) // Implementation
#define _pk_extension_imp($protocol, $container_class) \
protocol $protocol; \
@interface $container_class : NSObject <$protocol> @end \
@implementation $container_class \
+ (void)load { \
_pk_extension_load(@protocol($protocol), $container_class.class); \
} \ // Get container class name by counter
#define _pk_get_container_class($protocol) _pk_get_container_class_imp($protocol, __COUNTER__)
#define _pk_get_container_class_imp($protocol, $counter) _pk_get_container_class_imp_concat(__PKContainer_, $protocol, $counter)
#define _pk_get_container_class_imp_concat($a, $b, $c) $a ## $b ## _ ## $c
转化为oc语言定义就是
@protocol Forkable; \
@interface __PKContainer_Forkable_0 : NSObject <Forkable> @end \
@implementation __PKContainer_Forkable_0 \
@synthesize title = _title; + (void)load { \
//add protocol class method?
_pk_extension_load(@protocol(Forkable), __PKContainer_Forkable_0.class);
} -(NSString *)title
{
if (!_title) {
_title = @"default title!";
}
return _title;
} - (void)fork {
NSLog(@"Forkable protocol extension: I'm forking (%@).", self.github);
} - (NSString *)github {
return @"This is a required method, concrete class must override me.";
}
@end
从这可以看出关键的代码 _pk_extension_load()
可以猜想其定义是
1 在load里注册自己包含那些扩展协议
2 在c方法里遍历所有的类 把有扩展的 方法的实现指过去
现在查看其函数实现 关键代码如下
__attribute__((constructor)) static void _pk_extension_inject_entry(void) { pthread_mutex_lock(&protocolsLoadingLock); unsigned classCount = ;
Class *allClasses = objc_copyClassList(&classCount); @autoreleasepool {
for (unsigned protocolIndex = ; protocolIndex < extendedProtcolCount; ++protocolIndex) {
PKExtendedProtocol extendedProtcol = allExtendedProtocols[protocolIndex];
for (unsigned classIndex = ; classIndex < classCount; ++classIndex) {
Class class = allClasses[classIndex];
if (!class_conformsToProtocol(class, extendedProtcol.protocol)) {
continue;
}
_pk_extension_inject_class(class, extendedProtcol);
}
}
}
pthread_mutex_unlock(&protocolsLoadingLock); free(allClasses);
free(allExtendedProtocols);
extendedProtcolCount = , extendedProtcolCapacity = ;
}
//将协议的方法添加到到类中(如果不存在就不添加了)//包括类方法和实例方法
static void _pk_extension_inject_class(Class targetClass, PKExtendedProtocol extendedProtocol) { for (unsigned methodIndex = 0; methodIndex < extendedProtocol.instanceMethodCount; ++methodIndex) {
Method method = extendedProtocol.instanceMethods[methodIndex];
SEL selector = method_getName(method); if (class_getInstanceMethod(targetClass, selector)) {
continue;
} IMP imp = method_getImplementation(method);
const char *types = method_getTypeEncoding(method);
class_addMethod(targetClass, selector, imp, types);
} Class targetMetaClass = object_getClass(targetClass);
for (unsigned methodIndex = 0; methodIndex < extendedProtocol.classMethodCount; ++methodIndex) {
Method method = extendedProtocol.classMethods[methodIndex];
SEL selector = method_getName(method); if (selector == @selector(load) || selector == @selector(initialize)) {
continue;
}
if (class_getInstanceMethod(targetMetaClass, selector)) {
continue;
}
IMP imp = method_getImplementation(method);
const char *types = method_getTypeEncoding(method);
class_addMethod(targetMetaClass, selector, imp, types);
}
}
由此可知猜想是正确的,方法告诉我们对于某一个含有该协议的类,如果其含有了协议里面的函数,则跳过,如果没有该函数就添加。
这里是下载地址
向OC类中添加默认的协议实现(ProtocolKit)的更多相关文章
- 在SpringMVC中,当Json序列化,反序列化失败的时候,会抛出HttpMessageNotReadableException异常, 当Bean validation失败的时候,会抛出MethodArgumentNotValidException异常,因此,只需要在ExceptionHandler类中添加处理对应异常的方法即可。
在SpringMVC中,当Json序列化,反序列化失败的时候,会抛出HttpMessageNotReadableException异常, 当Bean validation失败的时候,会抛出Method ...
- AE 向已存在的要素类中添加字段
风过无痕 原文向已存在的要素类中添加字段 以前,在用AE写程序的时候,为了方便,一般都是直接新建一个MapControl窗体应用程序.这次需要解决的问题用不到窗口,就突发奇想,直接新建了一个Conso ...
- C++中若类中没有默认构造函数,如何使用对象数组
前言: 如果定义一个类,有其默认的构造函数,则使用new动态实例化一个对象数组,不是件难事,如下代码: #include <memory> #include <iostream> ...
- 类中添加log4j日志
在编写代码的时候需要随时查看工作日志,查看工作日志的好处就是随时能检查出错误.所以我一般就需要在编写代码的前期添加工作日志,以便更好的查看相关错误输出. 以一个springmvc小demo为例子 主 ...
- 【2016.3.30项目技术记录】]VS2010自动生成MFC单文档框架程序的修改:去除属性框,在CViewTree类中添加鼠标单击响应
转自http://blog.csdn.net/yanfeiouc2009/archive/2010/06/07/5653360.aspx 手头上有个东西要用到单文档,由于想省事,直接用VS2010做了 ...
- springboot在工具类中添加service的方法,显示为空的解决方案
@Component// 1.将工具类声明为spring组件,这个必须不能忘 public class TestUtils { //2.自动注入 @Autowired private ItemServ ...
- C++空类中的默认函数
定义一个空的C++类,例如 class Empty { } 一个空的class在C++编译器处理过后就不再为空,编译器会自动地为我们声明一些member function,一般编译过去就相当于 cla ...
- 【c++】类中带默认参数的函数
反思两个问题 1. 带默认参数的函数,为何声明.定义不能同时有参数? 2. 带默认参数的函数, 为何带默认参数的参数靠后站? 上程序 #include <iostream> #includ ...
- 给VS类文件添加默认头注释
找到类文件所在路径:C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplatesCache\CSharp\ ...
随机推荐
- SOAP web service用AFNetWorking实现请求
问: This is my current call to (asmx) SOAP web service: NSString *soapMessage = [NSString stringWithF ...
- android110 jni01
##交叉编译(编译就是编译成汇编指令,使得电脑能够识别,比如windows平台模拟linux平台编译出来得程序可以在linux上运行.) * 在一个平台下,编译出另一个平台能够执行的二进制的代码 * ...
- C# - 系统类 - String类
String类 ns:System String类封装了一系列不能被改变的Unicode字符序列 字符属于引用类型 但它又具有值类型的行为 固定不变意味着 一旦在托管堆中分配了一块内存来存储字符 字符 ...
- 【转】Hibernate映射机制之XXX.hbm.xml
http://blog.csdn.net/a9529lty/article/details/6454924[注意多对一中“多”和“一”各自的java文件.xml文件的书写格式] 另外两篇总结:http ...
- 在MyEclipse中如何去掉JS或jsp语法错误提示!
在MyEclipse中如何去掉JS或jsp语法错误提示! 关于在 MyEclipse 上 WEB 工程里面的 JS/JSP 经常会有语法错误提示,这是由于 MyEclipse 对其语法要求相当严格所造 ...
- (转)OpenVPN下载、安装、配置及使用详解
原文地址:http://www.365mini.com/page/14.htm OpenVPN简介 OpenVPN是一个用于创建虚拟专用网络(Virtual Private Network)加密通道的 ...
- elfiner-servlet 2.x已开源!
通过近一周的努力,elfiner-servlet 2.x基本搞定! 已提交github,开源之!请各位享用~~ 对elfinder不熟悉的请访问:http://elfinder.org 一个很不错的文 ...
- Net预编译 真的好用与否
公司手机网站上千个 ASP.NET开发一套程序只是配置不一样,所有站点呈现的内容就不一样了, 以前的程序是ASP的,现在ASP程序猿少之又少了,所以公司要求转.NET,新开发也用NET.所有现在上千个 ...
- 使用XMl序列化器生成xml文件
生成XML文件 创建几个虚拟的短信对象,存在list中 备份数据通常都是备份至sd卡 使用StringBuffer拼接字符串 把整个xml文件所有节点append到sb对象里 sb.append(&q ...
- poj1308 Is It A Tree?(并查集)详解
poj1308 http://poj.org/problem?id=1308 题目大意:输入若干组测试数据,输入 (-1 -1) 时输入结束.每组测试数据以输入(0 0)为结束标志.然后根据所给的 ...