views:

53

answers:

2

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?

+2  A: 

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...

Tom H
To clarify, this returns the `Class` object of your class, not only the *name* as is implied by the answer.
Denis 'Alpheus' Čahuk
actually, [self class] is the same as self in a class method. The docs (ok fine the GNUStep docs) actually say it is implemented just with 'return self;'. It only exists for passing classes as arguments, see http://stackoverflow.com/questions/3107213/why-do-we-have-to-do-myclass-class-in-objective-c
Jared P
Thank you very much! I didn't know that 'self' can be used in class method!
taichino
+1  A: 

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)

Jared P
anyone want to tell me why I was downvoted?
Jared P
I'm trying to add some utility methods(like all() in django) to NSManagedObject. So I need to distinguish the caller.Using 'self' is what I wanted to know! Thanks!
taichino
It wasn't me who down voted, but I just checked, and in a class method self==[self class]Just saw this had been said in another comment, but to clarify, they're IDENTICAL, in a class method at least.So you were right, and so was I
Tom H