How to get class information at runtime in Objective-C?

I have an NSMutableArray with different objects in it of different classes. Now I want to get the class name, related things, and also check whether the corresponding NSString object or not. How can I do it?

I tried something like the following. Of course, this does not work.

for(NSString *string in array){
    NSLog(@"Name of the class : %@", [NSString stringWithCString:class_getName(Class id)];
+3
source share
3 answers

If you are on Mac OS X, you can use [object className], it returns NSString

for(id obj in array) NSLog(@"Name of the class: %@", [obj className]);

To check if this is an NSString, you should use something like this:

for(id obj in array) {
    if ([obj isKindofClass:[NSString class]]) {
        // do something
    }
}
+6
source
for(id object in array){
    NSLog(@"Name of the class: %@", [object className]);
    NSLog(@"Object is a string: %d", [object isKindOfClass:[NSString class]]);
}

NSObject class protocol .

+6

NSMutableArray . , , NSString .

. ? , ?

, -isKindOfClass: . - . , . , , .

, -respondsToSelector: . , .

+1

Source: https://habr.com/ru/post/1722925/


All Articles