0

Is it possible to use "Forwarding" (http://en.wikipedia.org/wiki/Objective-C#Forwarding) in iOS?

I tried the following code I found here:

- (retval_t) forward: (SEL) sel : (arglist_t) args

But I get an error message:

error: expected ')' before 'retval_t'

So I read here and try:

- (retval_t)forward:(SEL)sel args:(arglist_t) args

But I got the same error message...

What am I doing wrong? Do I need to import something?


@bbum: I try to create a thread safe NSMutableArray and want to use the code I found here: NSMutableDictionary thread safety

Community
  • 1
  • 1
Manni
  • 11,108
  • 15
  • 49
  • 67

2 Answers2

5

Yes. What you're seeing there is the GNU variant of Objective-C, which is slightly different from the Apple variant.

You want to use -forwardInvocation: rather than -forward:: or -forward:args:. See http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html for more info on how to do it with iOS.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
  • That'll work, but you really *really **really** don't want to write software that relies on message forwarding of this nature unless it is unavoidable, which it is in all but the rarest of circumstances. – bbum Aug 08 '11 at 18:01
  • @bbum's right, of course--forwarding is Deep Magic and to be avoided unless no other option exists. I don't think I've found a need to implement it in years. – Jonathan Grynspan Aug 08 '11 at 18:05
1

Here's the pattern I use for iOS forwardInvocation (message forwarding):

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    if ([self.recipient respondsToSelector:[anInvocation selector]]) {
        [anInvocation invokeWithTarget:self.recipient];
    }
    else {
        [super forwardInvocation:anInvocation];
    }
}

It is important to note that the return value of the message that’s forwarded is automatically returned to the original sender.

Yup.
  • 1,883
  • 21
  • 18