Testing for class type

When I submit an object to NSLog, I get a string with three attributes. The first is the class of the object, the second is the frame of the object, and the third is the CALayer of the object. The second and third attributes have a name (e.g. layer =), so I can name them by name (e.g. myObject.layer).

The first is not. How to check class type?

Thanks!

+4
source share
3 answers

To get the class of an object, just call [myObject class] . You can compare this with your desired class as follows:

 if ([myObject class] == [SomeClass class]) { /* ... */ } if ([myObject class] == [NSString class]) { /* ... */ } 

If you are just looking for the class name as a string, you can use the NSStringFromClass function as follows:

 NSString * className = NSStringFromClass([myObject class]); 
+10
source

If you also want to include subclasses of the target class, use:

 [object isKindOfClass:[SomeClass class]] 
+7
source

@eJames and @Diederik are both correct. However, there are several other options, some of which may be preferred depending on your taste.

For example, instead of checking for equality of class objects, you can also use -isMemberOfClass: which excludes subclasses, while -isKindOfClass: and -isSubclassOfClass: none. (This is definitely the case when one option may be more intuitive for some people than for others.)

In addition, [SomeClass className] or [anObject className] are convenient, shorter ways to get the class name as NSString . (I know -className defined in NSObject, and +className works for class prototypes, although I cannot find documentation for it easily.)

+3
source

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


All Articles