Posting arbitrary messages to any receiver



+ (id)sendToDelegate:(id)receiver message:(SEL)message arg1:(id)arg1, ...
{
   if (![receiver respondsToSelector:message])
   {
      @throw [NSException exceptionWithName:@"DelegaterException"
                   reason:[NSString stringWithFormat:@"Receiver doesn't respond to message %s",
                              sel_getName(message)]
                 userInfo:nil];
   }

   NSMethodSignature* sign = [receiver methodSignatureForSelector:message];
   NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:sign];
   [invocation setSelector:message];
   [invocation setTarget:receiver];
   [invocation setArgument:&arg1 atIndex:2];

   id arg;
   va_list args;
   va_start(args, arg1);
   int i = 3;
   while (arg = va_arg(args, id))
   {
      [invocation setArgument:&arg atIndex:i++];
   }
   va_end(args);

   [invocation invoke];
   id result;
   [invocation getReturnValue:&result];

   return result;
}