The Gas Effect
The Gas Effect

Reputation: 31

Calling a static method on a class

Given a method like the one below, that returns a Class...

-(Class)getClass
{
    return [MyAwesomeClass class];
}

...how do I call a static method on that class? I tried this, but it didn't work...

Class theClass = [anInstance getClass];
[theClass someStaticMethod];

How should I call a static method on theClass?

Edit to add: It seems I was doing the right thing, and something else was causing the crash. Now I need to figure out how to get rid of the warning that the method someStaticMethod isn't found. What should I cast theClass to?

Upvotes: 3

Views: 5458

Answers (2)

buttcmd
buttcmd

Reputation: 651

It is an old question but i answer it for completeness. if you use id instead of Class it will work

id theClass = [anInstance getClass];
[theClass someStaticMethod];

Compiler will be happy with this dynamic typing but you must be sure that Class will respond to +someStaticMethod or it will crash at runtime

Upvotes: 4

Chuck
Chuck

Reputation: 237020

You do it exactly the way you've written it, assuming the class in question responds to someStaticMethod.

If it isn't working correctly, then one of these is most likely the case:

  • You don't have the class you think
  • The class doesn't respond to the message
  • You declared the method incorrectly
  • You haven't imported the header where the method is declared
  • The method itself is buggy

Upvotes: 4

Related Questions