[IOS learning] message forwarding and its practical application

Keywords: Attribute network github


Message forwarding is applicable to the implementation of operations to another class

  1. -(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector  
  2. {  
  3.     NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];  
  4.     if (!signature) {  
  5.         signature = [self.displayLabel methodSignatureForSelector:aSelector];  
  6.     }  
  7.     return signature;  
  8. }  
  9.   
  10. -(void)forwardInvocation:(NSInvocation *)anInvocation  
  11. {  
  12.     SEL selector = [anInvocation selector];  
  13.     if ([self.displayLabel respondsToSelector:selector]) {  
  14.         [anInvocation invokeWithTarget:self.displayLabel];  
  15.     }  
  16. }  
In the above example, a UIViewController contains the uilabel attribute displayLabel. If the UIViewController instance calls the [instance setText:@"string"] method, because the class does not implement the setText: method, through the above two lines of code, it will be forwarded and implemented by displayLabel.


Another: for the use of message forwarding, the following category expansion solves the crash caused by the operation of NSNull object (often encountered when the network data return is empty)

  1. - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector  
  2. {  
  3.     NSMethodSignature* signature = [super methodSignatureForSelector:selector];  
  4.     if (!signature) {  
  5.         for (NSObject *object in NSNullObjects) {  
  6.             signature = [object methodSignatureForSelector:selector];  
  7.             if (signature) {  
  8.                 break;  
  9.             }  
  10.         }  
  11.           
  12.     }  
  13.     return signature;  
  14. }  
  15.   
  16. - (void)forwardInvocation:(NSInvocation *)anInvocation  
  17. {  
  18.     SEL aSelector = [anInvocation selector];  
  19.       
  20.     for (NSObject *object in NSNullObjects) {  
  21.         if ([object respondsToSelector:aSelector]) {  
  22.             [anInvocation invokeWithTarget:object];  
  23.             return;  
  24.         }  
  25.     }  
  26.       
  27.     [self doesNotRecognizeSelector:aSelector];  
  28. }  


For details, please refer to: https://github.com/caigee/iosdev_sample Lower
ClassForward

Posted by thenewguy on Fri, 03 Apr 2020 10:51:23 -0700