How to get classname in objective c Like 'NSSt

2019-09-01 12:45发布

问题:

I want to get the class name of an object as what we are using. That means now if I write this code

 NSString *s = [NSString string];
 NSLog(@"%@",[s class]);

The output is __NSCFConstantString

How can I get it as NSString itself ?

Note : NSString is just an example

I know __NSCFConstantString is correct. But my intention is to get like NSString. Is there any way to acheive this?

回答1:

Give these a try, they'll output NSString. Keep in mind, the second set requires importing the Objective-C runtime header.

#import <objc/runtime.h>

NSString *string = @"I'm a string.";


NSLog(@"%@",NSStringFromClass([string classForCoder]));
NSLog(@"%@",NSStringFromClass([string classForKeyedArchiver]));

NSLog(@"%s",class_getName([string classForCoder]));
NSLog(@"%s",class_getName([string classForKeyedArchiver]));

Now, this won't work in all cases. For example, trying to get the class of NSConstantString, in this manner will output NSString. If you require checking the class name as a string in this way, you probably should reconsider your approach to solving the problem.



回答2:

NSString is a so-called "class cluster". That means that the init methods will return an instance of some subclass (such as __NSCFConstantString or __NSCFString). You will never get an instance with the class equal to NSString.

If your intention is to check whether an object is a NSString or not then use isKindOfClass:

if ([s isKindOfClass:[NSString class]]) {
    // this is a string …
}

Other examples of class clusters are NSNumber, NSDictionary, NSArray and their mutable variants.



回答3:

NSLog(@"%@", NSStringFromClass([s class]));