Printable type string from parameter

Using clang and objective-c I am wondering if I can get a printed string describing the type of a potentially null parameter (i.e. compile time information).

For example, something like:

- (void)myFunc:(NSString *)aNilString { NSLog(@"%s", __typeof__(aNilString)); } 

Obviously this does not work, because __typeof__ gets me the actual type, not the string. In C ++, we have a typeid that returns std :: type_info, but this name is garbled, for example. "P12NSString *", not "NSString *".

Ideally, I would like something that can be passed to functions like objc_getClass (). Is there a way to get what I want?

Edit: I don't need to compile as C ++, so this solution is missing:

 abi::__cxa_demangle(typeid(*aNilString).name(), 0, 0, 0)); 
+4
source share
1 answer

To get a string that can be passed to functions like objc_getClass (), simply use the class object description.

In this example, I changed the type of your argument from NSString * to id , because if you already knew that the argument was NSString * , then this question will be quite controversial. Note that I call the class method of the passed object, and then the class description method to get the NSString * , which describes this class, and can be used with the methods you reference.

Note also that if the object is nil , then there is no class, and the description call will just return zero, and the NSLog will print (null) . You cannot determine the type of a pointer at runtime because it is just a pointer to a class object (and this does not exist for nil ).

 - (void)myFunc:(id)aClassObject { // Get the description of aClassObject class: NSString *classString = [[aClassObject class] description]; NSLog(@"%@", classString); // Prints __NSCFConstantString // Bonus: Get a new object of the same class if ([classString length] > 0) { id theClass = objc_getClass([classString UTF8String]); id aNewObjectOfTheSameType = [[theClass alloc] init]; NSLog(@"%@", [[aNewObjectOfTheSameType class] description]); // Prints __NSCFConstantString } } 
0
source

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


All Articles