iOS 协议分发
Github:AOMultiproxier、HJProtocolDispatcher
协议实现分发器,能够轻易实现将协议事件分发给多个实现者。
一、AOMultiproxier.h
#define AOMultiproxierForProtocol(__protocol__, ...) ((AOMultiproxier <__protocol__> *)[AOMultiproxier multiproxierForProtocol:@protocol(__protocol__) withObjects:((NSArray *)[NSArray arrayWithObjects:__VA_ARGS__,nil])])
调用类方法的宏定义。
@interface AOMultiproxier : NSProxy
@property (nonatomic, strong, readonly) Protocol * protocol; // 协议
@property (nonatomic, strong, readonly) NSArray * attachedObjects; // 协议方法实现者
+ (instancetype)multiproxierForProtocol:(Protocol *)protocol
withObjects:(NSArray*)objects;
@end
AOMultiproxier 继承自 NSProxy 类,声明了两个只读属性和一个初始化方法。
NS_ROOT_CLASS
@interface NSProxy <NSObject>{
Class isa;
}
NSProxy 是一个类似于 NSObject 的根类,实现了 NSObject 协议。
苹果的官方文档描述:
Typically, a message to a proxy is forwarded to the real object or causes the proxy to load (or transform itself into) the real object. Subclasses of NSProxy can be used to implement transparent distributed messaging (for example, NSDistantObject) or for lazy instantiation of objects that are expensive to create.
NSProxy implements the basic methods required of a root class, including those defined in the NSObject protocol. However, as an abstract class it doesn’t provide an initialization method, and it raises an exception upon receiving any message it doesn’t respond to. A concrete subclass must therefore provide an initialization or creation method and override the forwardInvocation: and methodSignatureForSelector: methods to handle messages that it doesn’t implement itself. A subclass’s implementation of forwardInvocation: should do whatever is needed to process the invocation, such as forwarding the invocation over the network or loading the real object and passing it the invocation. methodSignatureForSelector: is required to provide argument type information for a given message; a subclass’s implementation should be able to determine the argument types for the messages it needs to forward and should construct an NSMethodSignature object accordingly. See the NSDistantObject, NSInvocation, and NSMethodSignature class specifications for more information.
NSProxy 仅仅是个转发消息的场所,至于如何转发,取决于派生类到底如何实现。比如可以在内部 hold 住(或创建)一个对象,然后把消息转发给该对象。那我们就可以在转发的过程中做些手脚了,甚至可以不去创建这些对象,去做任何你想做的事情,但是必须要实现他的 forwardInvocation: 和 methodSignatureForSelector: 方法。
二、AOMultiproxier.m
@interface AOMultiproxier()
@property (nonatomic, strong) Protocol * protocol;
@property (nonatomic, strong) NSOrderedSet * objects;
@end
私有 readwrite 属性。
+ (instancetype)multiproxierForProtocol:(Protocol *)protocol withObjects:(NSArray *)objects
{
// 调用实例方法
return [[super alloc] initWithProtocol:protocol objects:objects];;
}
- (instancetype)initWithProtocol:(Protocol*)protocol objects:(NSArray*)objects
{
// 保存协议
_protocol = protocol;
NSMutableArray * validObjects = [NSMutableArray array];
BOOL oneConforms = NO;
for (id object in objects) {
// 判断 object 是否遵守了 protocol 协议
if ([object conformsToProtocol:protocol]) {
oneConforms = YES;
}
// 判断 object 是否遵守了 protocol 协议或者 protocol 的父协议
if ([self _object:object inheritsProtocolOrAncestorOfProtocol:protocol]) {
[validObjects addObject:object];
}
}
// 没有任何对象遵守协议,触发断言
NSAssert(oneConforms, @"You didn't attach any object that declares itself conforming to %@. At least one is needed.", NSStringFromProtocol(protocol));
_objects = [NSOrderedSet orderedSetWithArray:validObjects];
if (_objects.count <= 0 || !oneConforms) return nil;
return self;
}
初始化方法,给属性赋值。判断对象数组 objects 里的对象是否能够遵守了协议。
+ (BOOL)conformsToProtocol:(Protocol*)protocol
{
return YES;
}
- (BOOL)conformsToProtocol:(Protocol *)aProtocol
{
return protocol_conformsToProtocol(self.protocol, aProtocol);
}
重写方法。在此处一直返回 YES,且未调用。
- (NSArray *)attachedObjects
{
return [self.objects array];
}
NSSet -》NSArray。
/**
* 是否能够响应 selector 方法。
*/
- (BOOL)respondsToSelector:(SEL)selector
{
BOOL responds = NO;
// 是否是必须实现的协议方法(required)
BOOL isMandatory = NO;
// 获取方法描述
struct objc_method_description methodDescription = [self _methodDescriptionForSelector:selector
isMandatory:&isMandatory];
if (isMandatory) {
responds = YES;
}
else if (methodDescription.name != NULL) {
// 非必须实现的再检查 object 是否实现了协议方法
responds = [self _checkIfAttachedObjectsRespondToSelector:selector];
}
return responds;
}
/**
* 转发消息
*/
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
SEL selector = [anInvocation selector];
BOOL isMandatory = NO;
struct objc_method_description methodDescription = [self _methodDescriptionForSelector:selector
isMandatory:&isMandatory];
// 方法描述获取失败,调用 super 触发 crash
if (methodDescription.name == NULL) {
[super forwardInvocation:anInvocation];
return;
}
BOOL someoneResponded = NO;
for (id object in self.objects) {
// 可以响应,由 object 调用协议方法
if ([object respondsToSelector:selector]) {
[anInvocation invokeWithTarget:object];
someoneResponded = YES;
}
}
// If a mandatory method has not been implemented by any attached object, this would provoke a crash
// 如果没有 required 方法没有被实现,调用 super 触发 crash
if (isMandatory && !someoneResponded) {
[super forwardInvocation:anInvocation];
}
}
/**
* 获取方法签名,包含参数类型、返回值类型等信息。
*/
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
NSMethodSignature * theMethodSignature;
BOOL isMandatory = NO;
struct objc_method_description methodDescription = [self _methodDescriptionForSelector:selector
isMandatory:&isMandatory];
if (methodDescription.name == NULL) {
return nil;
}
// 方法描述 -> 方法签名
theMethodSignature = [NSMethodSignature signatureWithObjCTypes:methodDescription.types];
return theMethodSignature;
}
消息转发核心方法。检查 selector 对应的方法描述是否正确,并对 required 方法未实现的情况做出处理。
/**
* 返回方法描述
*/
- (struct objc_method_description)_methodDescriptionForSelector:(SEL)selector isMandatory:(BOOL *)isMandatory
{
struct objc_method_description method = {NULL, NULL};
// First check on main protocol. 当前协议查找
method = [self _methodDescriptionInProtocol:self.protocol selector:selector isMandatory:isMandatory];
// If no method is known on main protocol, try on ancestor protocols. 在父协议查找
if (method.name == NULL) {
unsigned int count = 0;
Protocol * __unsafe_unretained * list = protocol_copyProtocolList(self.protocol, &count);
for (NSUInteger i = 0; i < count; i++) {
Protocol * aProtocol = list[i];
// Skip root protocol
if ([NSStringFromProtocol(aProtocol) isEqualToString:@"NSObject"]) continue;
method = [self _methodDescriptionInProtocol:aProtocol selector:selector isMandatory:isMandatory];
// 找到了
if (method.name != NULL) {
break;
}
}
free(list);
}
return method;
}
/**
* 获取方法描述
*/
- (struct objc_method_description)_methodDescriptionInProtocol:(Protocol *)protocol selector:(SEL)selector isMandatory:(BOOL *)isMandatory
{
struct objc_method_description method = {NULL, NULL};
// 使用 runtime 方法获取
method = protocol_getMethodDescription(protocol, selector, YES, YES);
if (method.name != NULL) {
*isMandatory = YES;
return method;
}
method = protocol_getMethodDescription(protocol, selector, NO, YES);
if (method.name != NULL) {
*isMandatory = NO;
}
return method;
}
实际获取方法是 _methodDescriptionInProtocol:selector: isMandatory:,在方法内调用运行时方法 protocol_getMethodDescription,这个方法有四个参数,来看看各代表了什么。
/**
* Returns a method description structure for a specified method of a given protocol.
*
* @param proto A protocol.
* @param aSel A selector.
* @param isRequiredMethod A Boolean value that indicates whether aSel is a required method. 标识是否是必须实现的
* @param isInstanceMethod A Boolean value that indicates whether aSel is an instance method. 标识是否是实例方法
*
* @return An c objc_method_description structure that describes the method specified by e aSel,
* e isRequiredMethod, and e isInstanceMethod for the protocol e p.
* If the protocol does not contain the specified method, returns an c objc_method_description structure
* with the value c {NULL, c NULL}.
*
* @note This function recursively searches any protocols that this protocol conforms to.
*/
OBJC_EXPORT struct objc_method_description
protocol_getMethodDescription(Protocol * _Nonnull proto, SEL _Nonnull aSel,
BOOL isRequiredMethod, BOOL isInstanceMethod)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
注意第三、四个参数即可。
- (BOOL)_checkIfAttachedObjectsRespondToSelector:(SEL)selector
{
for (id object in self.objects) {
if ([object respondsToSelector:selector]) {
return YES;
}
}
return NO;
}
检查 object 对象是否能够响应 selector 方法。
- (BOOL)_object:(id)object inheritsProtocolOrAncestorOfProtocol:(Protocol*)protocol
{
// 在当前协议中查找
if ([object conformsToProtocol:protocol]) {
return YES;
}
BOOL conforms = NO;
unsigned int count = 0;
Protocol * __unsafe_unretained * list = protocol_copyProtocolList(protocol, &count);
// 在查找父协议中查找
for (NSUInteger i = 0; i < count; i++) {
Protocol * aProtocol = list[i];
// Skip root protocol. 如果查找到了 NSObject 协议,结束查找
if ([NSStringFromProtocol(aProtocol) isEqualToString:@"NSObject"]) continue;
// 递归调用
if ([self _object:object inheritsProtocolOrAncestorOfProtocol:aProtocol]) {
conforms = YES;
break;
}
}
free(list);
return conforms;
}
查找 object 是否实现了协议方法。
三、HJProtocolDispatcher.h
#define AOProtocolDispatcher(__protocol__, ...) \
[ProtocolDispatcher dispatcherProtocol:@protocol(__protocol__) \
toImplemertors:\[NSArray arrayWithObjects:__VA_ARGS__, nil]]
同样的宏定义,这里用了 \ 换行,更适合阅读。__VA_ARGS__ 是新的 C99 规范中新增的一个可变参数的宏,目前似乎只有 gcc 支持(VC6.0的编译器不支持),实现思想就是宏定义中参数列表的最后一个参数为 ...。
四、HJProtocolDispatcher.m
/**
* 返回方法描述
*/
struct objc_method_description MethodDescriptionForSELInProtocol(Protocol *protocol, SEL sel) {
// required 方法
struct objc_method_description description = protocol_getMethodDescription(protocol, sel, YES, YES);
if (description.types) {
return description;
}
// optional 方法
description = protocol_getMethodDescription(protocol, sel, NO, YES);
if (description.types) {
return description;
}
// 未找到
return (struct objc_method_description){NULL, NULL};
}
/**
* 判断 protocol 是否包含 sel 方法
*/
BOOL ProtocolContainSel(Protocol *protocol, SEL sel) {
return MethodDescriptionForSELInProtocol(protocol, sel).types ? YES: NO;
}
私有方法。
@interface ImplemertorContext : NSObject
@property (nonatomic, weak) id implemertor; // 方法实现者,即最后调用方法的对象
@end
@implementation ImplemertorContext
@end
ImplemertorContext 是每个实现者的封装。
@interface ProtocolDispatcher ()
@property (nonatomic, strong) Protocol * prococol; // 协议
@property (nonatomic, strong) NSArray * implemertors; // 实现者数组
@end
@implementation ProtocolDispatcher
+ (id)dispatcherProtocol:(Protocol *)protocol toImplemertors:(NSArray *)implemertors
{
return [[ProtocolDispatcher alloc] initWithProtocol:protocol toImplemertors:implemertors];
}
- (instancetype)initWithProtocol:(Protocol *)protocol toImplemertors:(NSArray *)implemertors
{
if (self = [super init]) {
self.prococol = protocol;
NSMutableArray *implemertorContexts = [NSMutableArray arrayWithCapacity:implemertors.count];
[implemertors enumerateObjectsUsingBlock:^(id implemertor, NSUInteger idx, BOOL * _Nonnull stop) {
ImplemertorContext *implemertorContext = [ImplemertorContext new];
implemertorContext.implemertor = implemertor;
[implemertorContexts addObject:implemertorContext];
objc_setAssociatedObject(implemertor, _cmd, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}];
self.implemertors = [implemertorContexts copy];
}
return self;
}
- (BOOL)respondsToSelector:(SEL)aSelector
{
// 如果协议未包含方法,直接调用 super
if (!ProtocolContainSel(self.prococol, aSelector)) {
return [super respondsToSelector:aSelector];
}
for (ImplemertorContext *implemertorContext in self.implemertors) {
if ([implemertorContext.implemertor respondsToSelector:aSelector]) {
return YES;
}
}
return NO;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
// 如果协议未包含方法,直接调用 super
if (!ProtocolContainSel(self.prococol, aSelector)) {
return [super methodSignatureForSelector:aSelector];
}
struct objc_method_description methodDescription = MethodDescriptionForSELInProtocol(self.prococol, aSelector);
return [NSMethodSignature signatureWithObjCTypes:methodDescription.types];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
SEL aSelector = anInvocation.selector;
// 如果协议未包含方法,直接调用 super
if (!ProtocolContainSel(self.prococol, aSelector)) {
[super forwardInvocation:anInvocation];
return;
}
for (ImplemertorContext *implemertorContext in self.implemertors) {
if ([implemertorContext.implemertor respondsToSelector:aSelector]) {
[anInvocation invokeWithTarget:implemertorContext.implemertor];
}
}
}
五、总结
HJProtocolDispatcher 与 AOMultiproxier 的思想和功能大体相同。
AO 功能更齐全,它会去父协议中检查方法是否存在,且对 required 方法添加了逻辑判断。
AO 继承自 NSProxy,HJ 继承自 NSObject。NSObject 寻找方法顺序:本类->父类->动态方法解析->消息转发;NSproxy 顺序:本类->消息转发,同样做“消息转发”,NSObject 会比 NSProxy 多做好多事,也就意味着耽误很多时间,所以 NSProxy 效率更高。
iOS 协议分发的更多相关文章
- ios实现分发下载
背景:原来公司Jenkins打包后的ipa和apk都是通过第三方的平台托管,手动上传,然后去扫二维码下载.虽然第三方平台有Jenkins插件来直接上传到该平台,但是想自己进行管理.所以就自己来做安装包 ...
- iOS事件分发
前段时间项目有一个需求,要在点击闪屏的时候做一些处理,刚接到这个需求觉得很简单啊,在原有的view上加个button或者手势识别啥的,后面实现的时候发现还是有点坑.无论我在闪屏上面加button还是手 ...
- 不通过App Store实现ios应用分发下载安装
最近公司的项目准备着手宣传工作了,宣传手册上要印制App的下载地址二维码,但是客户端应用还未上线,需要一种临时的方案解决应用分发下载问题,通常ios应用必须通过苹果应用商店才能下载安装,但是也可以看到 ...
- 【App】不通过App Store实现ios应用分发下载安装(转)
转自:https://www.cnblogs.com/star91/p/5018995.html 最近公司的项目准备着手宣传工作了,宣传手册上要印制App的下载地址二维码,但是客户端应用还未上线, ...
- iOS协议
ios中的协议:大家猛一看 感觉挺高深的 其实ios中的协议就是c#,java中的接口 只是变了一个形式: 自我感觉ios中的协议没有c#中的接口好 人家的接口就是固定你的程序内容的 而ios中 ...
- ios 协议分析
1 基本用途 可以用来声明一大堆方法(不能声明成员变量) 只要某个类遵守了这个协议,就相当于拥有了这个协议中的所有方法声明 只要父类遵守了某个协议,就相当于子类也遵守了 2 格式 协议的编写 @pro ...
- IOS内测分发策略
当苹果应用没有上交appstore审核,出于开始内侧阶段时,我们如何邀请别人测试和使用? plist苹果安装包实现 使用七牛云存储解决ios7.1的app部署问题 推荐两个现在比较流行的app内测辅助 ...
- iOS 协议
协议分为三部分:声明.引用.实现. 通常,声明协议和声明协议类型的属性都是在同一个类中.声明协议和声明协议作为属性在头文件中,引用在声明类的实现文件中.而实现协议则在其它类中.
- ios协议和委托
在iPhone开发协议和委托是常接触到的东西,到底什么是协议什么是委托,他们什么关系? 一 协议 (1)协议相当于没有与类相关联的接口,他申明一组方法,列出他的参数和返回值,共享给其他类使用,然后不进 ...
随机推荐
- 93-time模块
目录 time模块 一.time模块 1.1 时间戳 1.2 格式化时间 1.3 结构化时间 1.4 不同格式时间之间的转换 1.5 其它用法 time模块 一.time模块 import time ...
- 从头认识js-js客户端检测
常用的客户端检测方式有以下三种: 1.能力检测 2.怪癖检测 3.用户代理检测 能力检测 最常用也是最为人们广泛接受的客户端检测形式是能力检测(又称特性检测).能力检测的目标不是识别特定的浏览器,而是 ...
- Asp.Net Core Endpoint 终结点路由之中间件应用
一.概述 这篇文章主要分享Endpoint 终结点路由的中间件的应用场景及实践案例,不讲述其工作原理,如果需要了解工作原理的同学, 可以点击查看以下两篇解读文章: Asp.Net Core EndPo ...
- preload & prefetch
原文地址在 我的笔记里,觉得还行就给个 star 吧:) 关于 preload 和 prefetch 早有耳闻,知道它们可以优化页面加载速度,然具体情况却了解不多.搜索了相关的资料后对其有了些认识,在 ...
- Javascript元编程之Annotation
语言的自由度 自由度这个概念在不同领域有不同的定义,我们借鉴数学中构成一个空间的维数来表达其自由度的做法,在此指的是:解决同一个问题彼此不相关的设计方法学数量. 例如,解决一个比如商品打折的问题,如何 ...
- ts文件的编译和运行
hello.ts代码 function sayHello(person: string): string { return 'Hello, ' + person; } let user = 'Tom' ...
- MapReduce 简单数据统计
1. 准备数据源 摘录了一片散文,保存格式为utf-8 2. 准备环境 2.1 搭建伪分布式环境 https://www.cnblogs.com/cjq10029/p/12336446.html 上传 ...
- Python3基础语法和数据类型
Python3基础语法 编码 默认情况下,Python3源文件以UTF-8编码,所有字符串都是unicode字符串.当然你也可以为原码文件制定不同的编码: # -*- coding: 编码 -*- 标 ...
- 什么是YUM
什么是Yum Yum(全称为 Yellow dog Updater, Modified)是一个在RedHat以及CentOS等Linux系统中的Shell前端软件包管理器.基于RPM包管理,能够从指定 ...
- django 知识点小结
以下内容为用django写blog中的一些知识点,权当复习. 一.定义view 1.get_object_or_404()是用get()查询数据,如果不存在就直接返回404 参数: get_objec ...