zoukankan      html  css  js  c++  java
  • 消息异常处理

    
    #import "ViewController.h"
    #import <objc/runtime.h>
    #import "AppDelegate.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 调用一个没有实现的方法
        [self performSelector:@selector(haha)];
    }
    
    /*处理不能识别的方法,会经历如下步骤,前一个步骤走不通的时候就会走下一个步骤*/
    
    #if 1 //step1:决议机制,是否为该sel动态的添加一个方法实现
    + (BOOL)resolveInstanceMethod:(SEL)sel
    {
        NSString *selname = NSStringFromSelector(sel);
        if ([selname isEqualToString:@"haha"]) {
            class_addMethod(self, sel, class_getMethodImplementation([AppDelegate class], @selector(haha)), method_getTypeEncoding(class_getInstanceMethod([AppDelegate class], @selector(haha))));
            return YES;
        }
        return [super resolveInstanceMethod:sel];
    }
    
    - (void)oklala {
        NSLog(@"oklala");
    }
    #endif
    
    #if 1 // step2:转发给其它的对象处理
    - (id)forwardingTargetForSelector:(SEL)aSelector
    {
        return [[AppDelegate alloc] init];
    }
    #endif
    
    #if 1 // step3: 封装成NSInvocation对象转发处理,系统默认是调用doesNotRecognizeSelector,重写forwardInvocation:方法同时必需重写methodSignatureForSelector:(构造NSInvocation对象必需先有一个NSMethodSignature对象),
    - (void)forwardInvocation:(NSInvocation *)anInvocation
    {
        NSLog(@"~~~~%@", [anInvocation description]);
    }  
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
        NSLog(@"%@", NSStringFromSelector(aSelector));
        NSMethodSignature *sig = [NSMethodSignature signatureWithObjCTypes:"@@:"];
        return sig;
    }
    #endif
    
    @end
    
    终于明白,“喜欢”是一种莫大的能量!
  • 相关阅读:
    基于Spring的集群会话共享方案-spring session
    Tensorflow 模型线上部署
    Dijkstra算法
    BFS和DFS
    图的基本概念
    排序5
    排序4
    排序3
    排序2
    排序1
  • 原文地址:https://www.cnblogs.com/tml839720759/p/5510871.html
Copyright © 2011-2022 走看看