foho
foho

Reputation: 779

Perform selector

I can't figure out why the code in if statement is not executed

 NSString *str = @"capitalizedString";
    NSString *name = @"chris";

    SEL selector = NSSelectorFromString(str);

    if([NSString respondsToSelector:selector]) {
        NSLog(@"%@", [name performSelector:selector]);
    }

EDIT // This code works fine

NSString *color = @"blueColor";
SEL selector = NSSelectorFromString(color); 
    if([UIColor respondsToSelector:selector])
    {
        myColor = [UIColor performSelector:selector];
    }

Upvotes: 0

Views: 1107

Answers (3)

Apurv
Apurv

Reputation: 17186

capitalizedString is not a static method. So you can not use NSString directly. Instead you should use the object of it. In your case it could ne name or str.

Upvotes: 2

Krrish
Krrish

Reputation: 2256

You can simply try this

if([NSString respondsToSelector:@selector(capitalizedString)]) {
        NSLog(@"%@", [name @selector(capitalizedString)]);
    }

Upvotes: 0

Wevah
Wevah

Reputation: 28242

You want

if ([name respondsToSelector:selector])

or

if ([NSString instancesRespondToSelector:selector])

The way you have it now, you're asking if the class object itself responds to the method, which it doesn't.

Upvotes: 1

Related Questions