美文网首页
delegate实现一对多

delegate实现一对多

作者: 紫嫣沁 | 来源:发表于2021-09-01 10:57 被阅读0次

NSMapTable:类似字典

NSPointerArray:类似数组

NSHashTable:类似于集合的集合,和NSSet相似

设计思路的话也比较简单,就是使用一个中间类,去遵守各种协议,然后当有对象需要遵守协议的时候,只需要将对象注册到中间类中,只要委托方调用了协议方法,那么代理方法实现的地方就会走相应的方法。

protocols:NSMapTable:协议存储表【Key:协议的遵守者  Value:代理】,就是存的:哪些遵守者 遵守了哪个协议

targets:NSPointerArray:协议的遵守者

首先会定义一个单例【KGDelegate shareInstance】

1,-addTarget: withProtocol:

先判断protocols中存储的有没有targets,如果有targets但是没有包含这个target,就把当前这个target和对应的协议添加到protocols中,如果没有targets,直接创建个targets,然后把当前这个target和对应的协议添加到protocols中【self.protocols setObject : targets forKey:protocol】

2,-respondsToSelector:判断遵守者能不能响应方法

3,-methodSignatureForSelector:方法签名,慢速转发

4,-forwardInvocation:消息转发,判断target能不能执行该方法,如果能 就invokeWithTarget:target去执行方法

其他还可以进行移除协议代理,移除遵守者

使用:

【KGDelegate shareInstance】addTarget:self  withProtocol:NSProtocolFromString(@" 需要遵循的代理的名字 ")


在iOS中直接调用某个对象的消息方式有两种:

1,performSelector:WithObject:

2,NSInvocation

NSInvocation;用来包装方法和对应的对象,它可以存储方法的名称,对应的对象,对应的参数,

//创建签名对象的时候不是使用NSMethodSignature这个类创建,而是方法属于谁就用谁来创建NSMethodSignature*signature=[ViewController instanceMethodSignatureForSelector:@selector(sendMessageWithNumber:WithContent:)];

//1、创建NSInvocation对象

NSInvocation*invocation=[NSInvocation invocationWithMethodSignature:signature];

invocation.selector=@selector(sendMessageWithNumber:WithContent:);

invocation.target=self;

NSString*number=@"1111";

[invocation setArgument:&number atIndex:2];/*第一个参数:需要给指定方法传递的值

          第一个参数需要接收一个指针,也就是传递值的时候需要传递地址*///第二个参数:需要给指定方法的第几个参数传值

[invocation invoke];  // [invocation invokeWithTarget:target]; 指定target去执行某个方法

相关文章

网友评论

      本文标题:delegate实现一对多

      本文链接:https://www.haomeiwen.com/subject/leyuiltx.html