Reputation: 2281
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 compiler 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
Upvotes: 0
Views: 121
Reputation: 86
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];
Upvotes: 1
Reputation: 51374
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];
Upvotes: 2
Reputation: 3415
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.
Upvotes: 1