Message forwarding is applicable to the implementation of operations to another class
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.
- -(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
- {
- NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
- if (!signature) {
- signature = [self.displayLabel methodSignatureForSelector:aSelector];
- }
- return signature;
- }
- -(void)forwardInvocation:(NSInvocation *)anInvocation
- {
- SEL selector = [anInvocation selector];
- if ([self.displayLabel respondsToSelector:selector]) {
- [anInvocation invokeWithTarget:self.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)
- - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
- {
- NSMethodSignature* signature = [super methodSignatureForSelector:selector];
- if (!signature) {
- for (NSObject *object in NSNullObjects) {
- signature = [object methodSignatureForSelector:selector];
- if (signature) {
- break;
- }
- }
- }
- return signature;
- }
- - (void)forwardInvocation:(NSInvocation *)anInvocation
- {
- SEL aSelector = [anInvocation selector];
- for (NSObject *object in NSNullObjects) {
- if ([object respondsToSelector:aSelector]) {
- [anInvocation invokeWithTarget:object];
- return;
- }
- }
- [self doesNotRecognizeSelector:aSelector];
- }
For details, please refer to: https://github.com/caigee/iosdev_sample Lower
ClassForward