向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\ ...
随机推荐
- 利用mongodb开发lbs应用实践【转】
近期作为突击队员,与同事一起突击构建了一个简单的lbs系统.当前比较主流的做法是使用mongodb,因为其已经封装了常用的lbs基本操作(如查找附近的人),功能非常强大,对于开发周期只有一周的项目,m ...
- JDK的帧--java.util包装工具库
题词 JDK,Java Development Kit. 首先,我们必须认识到,,JDK但,但设置Java只有基础类库.它是Sun通过基础类库开发,这是唯一的.JDK书写总结的类库.从技术含量来说,还 ...
- 特殊的forward_list操作
为了理解forward_list为什么有特殊版本的添加和删除操作,考虑当我们从一个单向链表中删除一个元素时会发生什么.当添加或删除一个元素时,删除或添加的元素之前的那个元素的后继会发生变化.为了添加或 ...
- Q_INIT_RESOURCE宏
QT应用程序,无论是exe,staticlib,还是dll程序,都可以通过qrc文件来导入各种资源. qrc会将这些资源文件转换为相应代码,参与应用程序的编译. 这样做的好处就是:简化了应用程序发 ...
- Sample Ant Build File - WAR--reference
I am using the Spring SimpleFormController example to illustrate the build process. The figure below ...
- mysq优化参数详解:innodb_buffer_pool_size,innodb_file_per_table
Mysql配置参数: thread_pool:如果支持的话,使用线程池 innodb_buffer_pool_size:物理内存50%-70%最高80%独立实例,多实例:60% innodb_flus ...
- 【转载】NIO客户端序列图
步骤一:打开SocketChannel,绑定客户端本地地址(可选,默认系统会随机分配一个可用的本地地址),示例代码如下: SocketChannel clientChannel = SocketCha ...
- 使用POI操作Excel使用小总结
1. Workbook维护一个调色板,可以自定义设置56种颜色,下标从8到63. 用到颜色的地方,可以输入下标获取颜色,如CellStyle的setFillForegroundColor(); 2.C ...
- css3绘制中国结
<!doctype html> <html> <head> <title></title> <meta charset='utf-8' ...
- java ssm框架入门(一)面向接口编程
因为工作上用到spring + strtus2 + mybatis ,所以开始学习下这个框架. 这里用到的是MySQL数据库 首先从web.xml 开始 <?xml version=" ...