NSProxy
一、什么是NSProxy
(1)NSProxy是一個(gè)抽象的基類甘有,是根類巾兆,與NSObject類似;
(2)NSProxy和NSObject都實(shí)現(xiàn)了<NSObject>協(xié)議棍现;
(3)提供了消息轉(zhuǎn)發(fā)的通用接口。
查看NSProxy類:
二伪朽、NSProxy和NSObject消息傳遞的異同
1轴咱、NSObject消息傳遞的流程:
(1)NSObject收到消息會(huì)先去緩存列表查找SEL汛蝙,若是找不到烈涮,就到自身方法列表中查找朴肺,依然找不到就順著繼承鏈進(jìn)行查找,依然找不到的話坚洽,那就是unknown selector戈稿,進(jìn)入消息轉(zhuǎn)發(fā)程序。
(2)調(diào)用+(BOOL)resolveInstanceMethod: 其返回值為BOOL類型讶舰,表示這個(gè)類是否通過class_addMethod新增一個(gè)實(shí)例方法用以處理該 unknown selector鞍盗,也就是說在這里可以新增一個(gè)處理unknown selector的方法,若不能跳昼,則繼續(xù)往下傳遞(若unknown selector是類方法般甲,那么調(diào)用 +(BOOL)resolveClassMethod:方法)
(3)調(diào)用-(id)forwardingTargetForSelector: 這是第二次機(jī)會(huì)處理unknown selector,即轉(zhuǎn)移給一個(gè)能處理unknown selector的其它對(duì)象鹅颊,若返回一個(gè)其它的執(zhí)行對(duì)象敷存,那消息從objc_msgSend (id self, SEL op, ...) 重新開始,若不能堪伍,則返回nil锚烦,并繼續(xù)向下傳遞,最后的一次消息處理機(jī)會(huì)帝雇。
(4)調(diào)用-(NSMethodSignature *)methodSignatureForSelector: 返回?cái)y帶參數(shù)類型涮俄、返回值類型和長(zhǎng)度等的selector簽名信息 NSMethodSignature對(duì)象,Runtime會(huì)基于NSMethodSignature實(shí)例構(gòu)建一個(gè)NSInvocation對(duì)象尸闸,作為回調(diào)forwardInvocation:的入?yún)ⅰ?/h6>
(5)調(diào)用-(void)forwardInvocation:這一步可以對(duì)傳進(jìn)來的NSInvocation進(jìn)行一些操作彻亲,把尚未處理的消息有關(guān)的全部細(xì)節(jié)都封裝在NSInvocation中,包括selector室叉,目標(biāo)(target)和參數(shù)等睹栖。
2、NSProxy消息傳遞的流程:
(1)接收到unknown selector后茧痕,直接回調(diào)methodSignatureForSelector:方法野来,返回?cái)y帶參數(shù)類型、返回值類型和長(zhǎng)度等的selector簽名信息 NSMethodSignature對(duì)象踪旷,Runtime會(huì)基于NSMethodSignature實(shí)例構(gòu)建一個(gè)NSInvocation對(duì)象曼氛,作為回調(diào)forwardInvocation:的入?yún)ⅰ?/h6>
(2)調(diào)用-(void)forwardInvocation:這一步可以對(duì)傳進(jìn)來的NSInvocation進(jìn)行一些操作,把尚未處理的消息有關(guān)的全部細(xì)節(jié)都封裝在NSInvocation中令野,包括selector舀患,目標(biāo)(target)和參數(shù)等。
三气破、NSProxy用法
1聊浅、實(shí)現(xiàn)多繼承
(2)調(diào)用-(void)forwardInvocation:這一步可以對(duì)傳進(jìn)來的NSInvocation進(jìn)行一些操作,把尚未處理的消息有關(guān)的全部細(xì)節(jié)都封裝在NSInvocation中令野,包括selector舀患,目標(biāo)(target)和參數(shù)等。
三气破、NSProxy用法
1聊浅、實(shí)現(xiàn)多繼承
場(chǎng)景:西紅柿作為一種常見的食物,既是水果又是蔬菜。用程序語言來說低匙,西紅柿類應(yīng)當(dāng)既繼承水果類旷痕,又繼承蔬菜類,但是在OC中只有單繼承顽冶,如何模擬實(shí)現(xiàn)多繼承呢欺抗?
首先识窿,實(shí)現(xiàn)Fruit和Vegetable類:
########水果類#########
////水果類:Fruit.h
@protocol FruitProtocol <NSObject>
@property (nonatomic, copy) NSString *texture;
@property (nonatomic, copy) NSString *name;
- (void)fruitDesc;
@end
@interface Fruit : NSObject
@end
////水果類:Fruit.m
@interface Fruit() <FruitProtocol>
@end
@implementation Fruit
//告訴編譯器至耻、texture屬性的setter、getter方法由編譯器來生成婶溯、同時(shí)用_texture來合成成員變量
@synthesize texture = _texture;
@synthesize name = _name;
- (void)fruitDesc
{
NSLog(@"%@间景,作為水果能夠促進(jìn)消化佃声。口感:%@", _name, _texture);
}
@end
########蔬菜類#########
////蔬菜類:Vegetable.h
@protocol VegatableProtocol <NSObject>
@property (nonatomic, copy) NSString *anotherName;
- (void)vegetableDesc;
@end
@interface Vegetable : NSObject
@end
////蔬菜類:Vegetable.m
@interface Vegetable() <VegatableProtocol>
@end
@implementation Vegetable
@synthesize anotherName = _anotherName;
- (void)vegetableDesc
{
NSLog(@"%@倘要,作為蔬菜可提供多種維生素秉溉。", _anotherName);
}
@end
其次,讓代理TomatoProxy類遵循協(xié)議<FruitProtocol, VegatableProtocol>碗誉。通過重寫forwardInvocation:和methodSignatureForSelector:方法將消息轉(zhuǎn)給TomatoProxy類來響應(yīng)召嘶。methodSignatureForSelector:方法,返回的是一個(gè)NSMethodSignature類型哮缺,來描述給定selector的參數(shù)和返回值類型弄跌。返回nil,表示proxy不能識(shí)別指定的selector尝苇。forwardInvocation:方法將消息轉(zhuǎn)發(fā)到對(duì)應(yīng)的對(duì)象上铛只。
########西紅柿類#########
////TomatoProxy.h
@interface TomatoProxy : NSProxy <FruitProtocol, VegatableProtocol>
+ (instancetype)tomatoProxy;
@end
////TomatoProxy.m
@implementation TomatoProxy
{
Fruit *_fruit;
Vegetable *_vegetable;
NSMutableDictionary *_targetMethodsHashMap;
}
+ (instancetype)tomatoProxy
{
return [[TomatoProxy alloc] init];
}
//創(chuàng)建init方法
- (instancetype)init
{
//初始化需要代理的對(duì)象(target),和存儲(chǔ)對(duì)象方法的哈希表
_targetMethodsHashMap = @{}.mutableCopy;
_fruit = [[Fruit alloc] init];
_vegetable = [[Vegetable alloc] init];
[self registerMethodsForTarget:_fruit];
[self registerMethodsForTarget:_vegetable];
return self;
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
SEL aSel = invocation.selector;
NSString *methodKey = NSStringFromSelector(aSel);
id targetObject = _targetMethodsHashMap[methodKey];
if (targetObject && [targetObject respondsToSelector:aSel]) {
[invocation invokeWithTarget:targetObject];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
NSString *methodName = NSStringFromSelector(sel);
id targetObject = _targetMethodsHashMap[methodName];
if (targetObject && [targetObject respondsToSelector:sel]) {
return [targetObject methodSignatureForSelector:sel];
}
return nil;
}
/**
將目標(biāo)對(duì)象的所有方法添加到哈希表中
@param aTarget 目標(biāo)對(duì)象
key 方法名
value 對(duì)象地址
*/
- (void)registerMethodsForTarget:(id)aTarget
{
unsigned int count = 0;
Method *methodList = class_copyMethodList([aTarget class], &count);
for(int i = 0; i < count; i++) {
Method aMethod = methodList[i];
SEL aSel = method_getName(aMethod);
const char *methodName = sel_getName(aSel);
[_targetMethodsHashMap setObject:aTarget forKey:[NSString stringWithUTF8String:methodName]];
}
free(methodList);
}
@end
最后糠溜,在main函數(shù)中就可以通過TomatoProxy類訪問Fruit類和Vegetable類的屬性和方法了淳玩。
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 1、使用NSProxy模擬多繼承非竿。
// TomatoProxy同時(shí)可以具備Fruit和Vegetable類的特性
TomatoProxy *tomato = [TomatoProxy tomatoProxy];
//設(shè)置Fruit類的屬性蜕着,調(diào)用Fruit類的方法
tomato.name = @"西紅柿";
tomato.texture = @"酸酸甜甜";
[tomato fruitDesc];
//設(shè)置vegetable類的屬性,調(diào)用vegetable類的方法
tomato.anotherName = @"番茄";
[tomato vegetableDesc];
}
return 0;
}
//打印結(jié)果:
2019-03-21 15:34:15.247663+0800 NSProxyTest[44704:13499339] 西紅柿红柱,作為水果能夠促進(jìn)消化承匣。口感:酸酸甜甜
2019-03-21 15:38:04.690131+0800 NSProxyTest[44704:13499339] 番茄锤悄,作為蔬菜可提供多種維生素
2韧骗、利用NSProxy解決NSTimer循環(huán)引用
//SecondViewController.m
@interface SecondViewController ()
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self startTimer];
}
- (void)startTimer
{
self.timer = [NSTimer timerWithTimeInterval:3.0
target:self
selector:@selector(timerInvoked:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerInvoked:(NSTimer *)timer
{
NSLog(@"======== timer ========");
}
- (void)dealloc
{
[self.timer invalidate];
self.timer = nil;
NSLog(@"SecondViewController dealloc");
}
@end
上面代碼中,從ViewController push到SecondViewController之后零聚,開啟一個(gè)定時(shí)器袍暴,當(dāng)頁(yè)面pop回ViewController之后些侍,定時(shí)器未被銷毀。其原因如下圖所示:
稍作修改:
////TimerWeakProxy.h
@interface TimerWeakProxy : NSProxy
/**
創(chuàng)建代理對(duì)象
@param target 被代理的對(duì)象
@return 代理對(duì)象
*/
+ (instancetype)proxyWithTarget:(id)target;
@end
////TimerWeakProxy.m
@interface TimerWeakProxy ()
@property (weak, nonatomic, readonly) id target; //被代理的對(duì)象為weak
@end
@implementation TimerWeakProxy
+ (instancetype)proxyWithTarget:(id)target
{
return [[self alloc] initWithTarget:target];
}
- (instancetype)initWithTarget:(id)target
{
_target = target;
return self;
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
SEL sel = [invocation selector];
if (_target && [_target respondsToSelector:sel]) {
[invocation invokeWithTarget:_target];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
return [_target methodSignatureForSelector:aSelector];
}
@end
////SecondViewController.m
- (void)startTimer
{
self.timer = [NSTimer timerWithTimeInterval:3.0
target:[TimerWeakProxy proxyWithTarget:self]
selector:@selector(timerInvoked:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
3政模、實(shí)現(xiàn)協(xié)議分發(fā)器(一對(duì)多代理)
在OC中娩梨,delegate一般用于對(duì)象之間一對(duì)一的通信,但是有時(shí)候我們希望可以有多個(gè)對(duì)象同時(shí)響應(yīng)一個(gè)protocol览徒。基于這種需求我們可以利用NSProxy實(shí)現(xiàn)一個(gè)消息分發(fā)器颂龙,將protocol中需要實(shí)現(xiàn)的方法交由分發(fā)器轉(zhuǎn)發(fā)給多個(gè)遵循protocol的對(duì)象习蓬,從而實(shí)現(xiàn)一對(duì)多的delegate。
一對(duì)一delegate的工作模式:
協(xié)議分發(fā)器的工作模式:
簡(jiǎn)言之措嵌,第一步:將需要遵循的protocol及遵循該protocol的對(duì)象交由分發(fā)器躲叼;第二步:分發(fā)器將消息轉(zhuǎn)發(fā)給可以響應(yīng)protocol中方法的多個(gè)delegate對(duì)象;第三步:每個(gè)delegate對(duì)象分別實(shí)現(xiàn)protocol中聲明的方法企巢。
協(xié)議分發(fā)器的實(shí)現(xiàn):
// 定義一個(gè)方法
//struct objc_method_description {
//SEL _Nullable name; /**< The name of the method */
//char * _Nullable types; /**< The types of the method arguments */
//};
//protocol_getMethodDescription: 為指定的method或者protocol返回一個(gè)method description structure
//protocol_getMethodDescription(Protocol * _Nonnull proto, SEL _Nonnull aSel, BOOL isRequiredMethod, BOOL isInstanceMethod)
//
struct objc_method_description MethodDescriptionForSelWithProtocol(Protocol *aProtocol, SEL aSel)
{
struct objc_method_description desc = protocol_getMethodDescription(aProtocol, aSel, YES, YES);
if (desc.types) {
return desc;
}
desc = protocol_getMethodDescription(aProtocol, aSel, NO, YES);
if (desc.types) {
return desc;
}
return (struct objc_method_description) {NULL, NULL};
};
// 判斷selector是否屬于某一Protocol
BOOL ProtocolContainsSelector(Protocol *aProtocol, SEL aSel)
{
return MethodDescriptionForSelWithProtocol(aProtocol, aSel).types ? YES : NO;
}
//*********** 協(xié)議消息轉(zhuǎn)發(fā)器 ***********//
@interface ProtocolMessageDispatcher ()
@property (nonatomic, strong) Protocol *prococol; //協(xié)議
@property (nonatomic, strong) NSArray *targets; //協(xié)議實(shí)現(xiàn)者對(duì)象(多個(gè))
@end
@implementation ProtocolMessageDispatcher
+ (id)dispatchProtocol:(Protocol *)aProtocol withTargets:(NSArray *)theTargets
{
return [[ProtocolMessageDispatcher alloc] initWithProtocol:aProtocol withTargets:theTargets];
}
- (instancetype)initWithProtocol:(Protocol *)aProtocol withTargets:(NSArray *)theTargets
{
self.prococol = aProtocol;
NSMutableArray *valideObjects = @[].mutableCopy;
for (id object in theTargets) {
if ([object conformsToProtocol:aProtocol]) {
objc_setAssociatedObject(object, _cmd, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[valideObjects addObject:object];
}
}
self.targets = valideObjects.copy;
return self;
}
- (BOOL)respondsToSelector:(SEL)aSelector
{
if (!ProtocolContainsSelector(self.prococol, aSelector)) {
return [super respondsToSelector:aSelector];
}
for (id object in self.targets) {
if ([object respondsToSelector:aSelector]) {
return YES;
}
}
return NO;
}
/*
返回?cái)y帶參數(shù)類型枫慷、返回值類型和長(zhǎng)度等的selector簽名信息 NSMethodSignature對(duì)象,Runtime會(huì)基于NSMethodSignature實(shí)例構(gòu)建一個(gè)NSInvocation對(duì)象浪规,作為回調(diào)forwardInvocation:的入?yún)?*/
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
if (!ProtocolContainsSelector(self.prococol, sel)) {
return [super methodSignatureForSelector:sel];
}
struct objc_method_description methodDesc = MethodDescriptionForSelWithProtocol(self.prococol, sel);
return [NSMethodSignature signatureWithObjCTypes:methodDesc.types];
}
/*
這一步可以對(duì)傳進(jìn)來的NSInvocation進(jìn)行一些操作或听,把尚未處理的消息有關(guān)的全部細(xì)節(jié)都封裝在NSInvocation中,包括selector笋婿,目標(biāo)(target)和參數(shù)等
*/
- (void)forwardInvocation:(NSInvocation *)invocation
{
SEL aSel = invocation.selector;
if (!ProtocolContainsSelector(self.prococol, aSel)) {
[super forwardInvocation:invocation];
return;
}
for (id object in self.targets) {
if ([object respondsToSelector:aSel]) {
[invocation invokeWithTarget:object]; //object是最后真正處理invocation的對(duì)象
}
}
}
使用協(xié)議分發(fā)器:
/// self和TableDelegate都成為tableView的代理
/// 當(dāng)點(diǎn)擊cell時(shí) self和TableDelegate中的方法都會(huì)被調(diào)用
self.tableView.delegate = [ProtocolMessageDispatcher dispatchProtocol:@protocol(UITableViewDelegate) withTargets:@[self, [TableDelegate new]]];
///點(diǎn)擊cell時(shí)誉裆,兩個(gè)delegate對(duì)象的方法都會(huì)執(zhí)行:
2019-04-03 17:02:31.733479+0800 NSProxyDemo[42445:13711860] -[DispatchMessageController tableView:didSelectRowAtIndexPath:]
2019-04-03 17:02:31.733687+0800 NSProxyDemo[42445:13711860] -[TableDelegate tableView:didSelectRowAtIndexPath:]
參考資料:
https://developer.apple.com/library/archive/samplecode/ForwardInvocation/Listings/main_m.html#//apple_ref/doc/uid/DTS40008833-main_m-DontLinkElementID_4
http://yehuanwen.github.io/2016/10/18/nsproxy/
http://www.olinone.com/?p=643
http://www.reibang.com/p/8e700673202b
http://www.reibang.com/p/b0f5fd3e4b7c
http://ggghub.com/2016/05/11/%E5%88%A9%E7%94%A8NSProxy%E8%A7%A3%E5%86%B3NSTimer%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E9%97%AE%E9%A2%98/
NSProxy和NSObject:http://www.reibang.com/p/5bfcc32c21c0
NSProxy與UIKit框架:https://mazyod.com/blog/2014/03/10/nsproxy-with-uikit/#Enter-the-NSProxy-Class
NSProxy與KVO:https://stackoverflow.com/questions/9054970/nsproxy-and-key-value-observing