Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c: How can I get Class instance in class method

I have 2 classes, Parent and Child, and Parent has a class method named func. Now I want to get Class instance in func method to distinguish which class is caller.

@interface Parent : NSObject
+ (void)func;
@end

@implementation Parent

+ (void)func {
    Class *class = howToGetClass();
    NSLog(@"%@ call func", class);
}

@end

@interface Child : Parent
@end

int main() {
    [Child func];    // call func from Child
}

Is there any way to get class instance (or class name) in class method?

like image 525
taichino Avatar asked Jun 26 '10 18:06

taichino


People also ask

How do you call an instance method in Objective-C?

YourClass *object = [[YourClass alloc] init]; [object someInstanceMethod]; The above is an instance method, because you must create an instance of YourClass (in this case, the object variable) before you can call the method " someInstanceMethod ".

How do you declare a class in Objective-C?

Unlike other C-based languages, Objective-C uses “@” for declarative statements. You always declare a new class with @interface, followed by your custom class name, followed by a colon and ended with the name of your class' superclass.


2 Answers

If you just want to log it/get it as a Class, you just need self. Thats it. So like

+ (void)func {
    Class class = self;
    NSLog(@"%@ call func", class);
}

or

+ (void)func {
    NSLog(@"%@ call func", self);
}

also, if you want to get the name as an NSString, NSStringFromClass(self) has you covered. (As a char *, class_getName(self) is what you're looking for)

like image 178
Jared Pochtar Avatar answered Oct 19 '22 23:10

Jared Pochtar


To get the current class object, you should be able to do:

[self class];

As self will refer to the class instance, because it's a class method. Class is a method defined in NSObject, which returns the class for the object.

Edited to avoid confusion...

like image 29
Tom H Avatar answered Oct 20 '22 00:10

Tom H