消息转发,适用于把操作给另外一个类来实现
-(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];
}
}
上例中,一个UIViewController包含了UIlable 属性 displayLabel, 如果UIViewController 实例调用[instance setText:@"string"]方法,由于类没有实现setText:方法,通过上面两行代码,将会转发,由 displayLabel 实现。
另:消息转发的使用,下面的类别拓展解决了对NSNull对象操作导致的崩溃(在网络数据返回为空的时候经常遇到)
- (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];
}
详细例子参照:https://github.com/caigee/iosdev_sample下的
ClassForward