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;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s