crashbus
crashbus

Reputation: 1714

check dynamic if a class responds to a selector by respondsToSelector:

I am looking for a possibility to check in a dynamic way if a class responds to a selector.

For example I have a strict schema of method names in a class like "parse[CountryCode]Adress".

I tryed something like this:

SEL selector = NSSelectorFromString([NSString stringWithFormat:@"parse%@Address", @"DE"]);

if ([CountryTraderDataParser respondsToSelector:@selector(selector)]) {
    NSLog(@"responds to");
    [CountryTraderDataParser selector];
}

but this doesn't work.

With a hard coded line [CountryTraderDataParser respondsToSelector:@selector(parseDEAddress:)] this example works fine.

Is there an other/better way to get this example to work?

Upvotes: 5

Views: 6249

Answers (1)

user557219
user557219

Reputation:

The selector variable is already a selector (type SEL), so you shouldn’t use @selector().

Also,

[CountryTraderDataParser selector];

is not valid unless there’s a method called selector. If you want to an object to execute a method based on a variable selector, use -[NSObject performSelector:].

SEL selector = NSSelectorFromString([NSString stringWithFormat:@"parse%@Address", @"DE"]);

if ([CountryTraderDataParser respondsToSelector:selector]) {
    NSLog(@"responds to");
    [CountryTraderDataParser performSelector:selector];
}

Upvotes: 15

Related Questions