开发者

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?


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜