开发者

How to call a method with parameters using @selector

开发者 https://www.devze.com 2022-12-20 11:48 出处:网络
I have two methods with same name but different parameters say: -(void)methodA:(NSString开发者_运维知识库*)string

I have two methods with same name but different parameters say:

-(void)methodA:(NSString开发者_运维知识库*)string
-(void)methodA:(NSNotification*)notification

Now i need to call those methods using @selector with the parameters. How to do it ?


SEL aSel = @selector(methodA:);

[objectTakesString performSelector:aSel withObject:@"A string!"]; [objectTakesNtfctn performSelector:aSel withObject:[NSNotification notificationWith...]];


-[NSObject performSelector:withObject:] takes both the selector to be invoked, and a pointer to the parameter to pass it.


In my opinion, both the preceding answers are wrong. If you use

-[NSObject performSelector:withObject:];

as Sixten Otto suggests, you would have to place this at the beginning of your method:

-(void)methodA:(id)stringOrNotification
{
   if ([stringOrNotification isKindOfClass:[NSString class])
   {
      ..do something..
   }
   if ([stringOrNotification isKindOfClass:[NSNotification class])
   {
      ..do something else..
   }
   . . .
}

Apart from this (bad) approach, what you're asking for can't in fact (easily) be done in Objective-C, because the language doesn't support parametric polymorphism. In other words, the type information is not used in the message dispatch. Yet another way to say this is that there can't be "two methods with same name but different parameters" in the same class. In fact, I'm surprised that you haven't yet seen a compiler error if you tried to declare this.

(If you've got the two methods defined on different classes, as dreamlax seems to assume, the message invocation will work trivially, even if you don't use performSelector:. Like so:

id eitherStringOrNotification;
[objectOfUncertainClass methodA:eitherStringOrNotification];

If that's what you're asking for, you don't have a problem. )

Note that the NSMethodSignature object does contain information about the parameter types, but it's generated by the receiving object, so you can't really use it to distinguish between messages based on what parameter types are handed in (since that information is not available when the method signature is instantiated).

0

精彩评论

暂无评论...
验证码 换一张
取 消