我正在使用这种方法将方法分派给委托,不幸的是我发现大多数时候NSMethodSignature都是nil,这是因为选择器来自协议.我想知道哪种方法是正确的:
[编辑]
根据newacct用户观察我的问题是不正确的,签名是零是正常的,但不是因为是协议,而是因为我要求方法签名对错误的对象.在这种情况下,它不实现我想要分派的方法,它是使用和实现它们的委托.
这是代码:
- (BOOL) dispatchToDelegate: (SEL) selector withArg: (id) arg error: (NSError*) err { NSMethodSignature *methodSig = [[self class] instanceMethodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig]; [invocation setTarget:self.delegate]; BOOL result = NO; if([self.delegate respondsToSelector: selector]) { if(arg != NULL) { [invocation setArgument:&arg atIndex:2]; [invocation setArgument:&err atIndex:3]; }else { [invocation setArgument:&err atIndex:2]; } if ([NSThread isMainThread]) { [invocation invoke]; } else{ [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:YES]; } [invocation getReturnValue:&result]; } else NSLog(@"Missed Method"); return result; }
- (NSMethodSignature *)methodSignatureForSelector:(SEL)inSelector { NSMethodSignature *theMethodSignature = [super methodSignatureForSelector:inSelector]; if (theMethodSignature == NULL) { struct objc_method_description theDescription = protocol_getmethodDescription(@protocol(GameCenterManagerDelegate),inSelector,NO,YES); theMethodSignature = [NSMethodSignature signatureWithObjCTypes:theDescription.types]; } return(theMethodSignature); }
它有效,但我会遵循bbum的建议,代码变得非常复杂……就像很快就会破解.
解决方法
做就是了:
if ([delegate respondsToSelector:@selector(someMethod:thatDoesSomething:)]) { dispatch_async(dispatch_get_main_queue(),^{ [delegate someMethod:foo thatDoesSomething:bar]; } }
对运行时变得神奇的诱惑很强烈,但它只会导致过于复杂的代码难以理解,速度较慢,而且并没有真正保存那么多行代码.重构也更难.
这显然不能解释返回值.但是,为此,你真的想避免任何类型的阻止调用.告诉主线程去做一些事情,然后让它在完成后安排一个块在适当的队列上执行.这将降低死锁的风险,并使您的整体应用程序设计更加简单.
请注意,上面的代码将导致在从主线程调用时,在下一次通过主事件循环时执行该块.这可能是你想要的,因为它将与并发案例的行为一致.