2

ok without using NSInvocation, let's say I have this code:

...
array = [NSMutableArray arrayWithObjects:@"Yoda", @"Jedi", @"Darth Vader", @"Darth Vader", @"Darth Vader" , @"Darth Vader", nil];

SEL removeObjectMessage = @selector(removeObject:inRange:);

//does array allow us to remove and object in a range? if so let's do this    
if ([array respondsToSelector:removeObjectMessage]){   
    NSRange darthVaderRange=NSMakeRange(2, 3);
    [array removeObject:@"Darth Vader"inRange:darthVaderRange];
}

how would I perform that last line in the form of the SEL removeObjectMessage? I would have to put a wrapper around the range? I just want to see the syntax of how all that mess would look...

CodaFi
  • 43,043
  • 8
  • 107
  • 153
Dave Kliman
  • 441
  • 4
  • 17

3 Answers3

2

You could do:

if ([array respondsToSelector:removeObjectMessage]){   
    NSRange darthVaderRange=NSMakeRange(2, 3);
    objc_msgSend(array, removeObjectMessage, @"Darth Vader", darthVaderRange);
}

Though that seems pretty fragile...

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
1

Unfortunately, if you're passing an argument that's not of type id, you have to use an NSInvocation object. (Otherwise, you could use performSelector:withObject:withObject:.)

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • hm. Ok... I guess I'll just have to learn more about NSInvocation. I may as well since I'm already this deep into SEL anyway... – Dave Kliman Jun 27 '11 at 19:04
1

There's no existing method that allows you to pass a selector and non-object arguments and get a valid method call. If it were a method that took only object arguments, you would do [array performSelector:removeObjectMessage withObject:@"Darth Vader" withObject:someHypotheticalRangeObject].

But to do it with an NSRange, you would have to either use NSInvocation (which you've said you don't want to do) or create a category on NSObject and use the low-level Objective-C runtime functions to define a method that takes a selector, an object argument and a non-object argument and calls the appropriate method.

Chuck
  • 234,037
  • 30
  • 302
  • 389