开发者

Objective C: Is there a way to call class methods on a class object without compiler complaints?

If you have a class object is there a way to use it to call class methods of that class. For example, if you have class A with method + (void)foo defined how can you achieve something like the example below without the c开发者_C百科ompiler warning that it can't find the method foo:

A* object = [[A alloc] init];
id objectClass = [object class];
[objectClass foo]; // complains that the method is not found


You don't have to create instances to call Class methods. Create instance if you have to call instance methods.

Method + (void)foo of class A should be called as,

[A foo];


Creating a class method in your .h:

MyClass.h

@interface MyClass : NSObject {    
}
+(void) test;

@end

MyClass.m

@implementation MyClass

-(id) init
{
    self = [super init];

    return self;
}

+(void) test
{
    NSLog(@"Test executed");
}

@end

You can then just call it like this:

MyClass* myClass = [[[MyClass alloc] init] autorelease];

[[myClass class] test];

Edit:

If the problem is the compiler warning, just create a @protocol that defines the foo method you want to call. Instead of calling:

id objectClass = [object class]; 

Try this;

id<MyProtocol> myCastedObject = (id<MyProtocol>)object;
[myCastedObject class] foo];


I just ran a quick test using one of my classes and was able to make it work using your syntax. What errors are you getting? What you are basically doing by the way is

  [A foo];

Calling a static member of the class. This will only work with methods marked as static with the + sign.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜