消息转发,适用于把操作给另外一个类来实现
-(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
本文深入探讨了Objective-C中消息转发机制的应用,特别是在处理NSNull对象时避免崩溃的方法。通过具体示例展示了如何在UIViewController中转发调用至displayLabel属性,确保了代码的健壮性和用户体验。同时,介绍了针对NSNull对象操作的优化策略,有效防止了网络数据返回为空时导致的程序崩溃。
515

被折叠的 条评论
为什么被折叠?



