Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a variable type from string?

I don't know the technical term for this.I am wondering in Objective C, if it is possible to declare a variable like this:

NSClassFromString(aClassName) *var;

or

[NSClassFromString(aClassName) class] *var;

Apparently, the above two are not correct. What I want is to dynamically declare a variable. Thanks.

like image 226
yibuyiqu Avatar asked Aug 14 '26 02:08

yibuyiqu


2 Answers

You should make the ivar of id type, and then make it dynamically typed. For example, if you want to dynamically type it NSString, you can do like this :

id ivar;
Class myClass = NSClassFromString(@"NSString");

ivar = [[myClass alloc] initWithString:@"abc"];
like image 74
Guo Luchuan Avatar answered Aug 16 '26 02:08

Guo Luchuan


You'll have to declare var as an id, and then instantiate it like:

var = [[NSClassFromString(aClassName) alloc] init];

The only point of declaring a type is compile-time type-checking, so there shouldn't be a problem as long as you only throw messages at the object that it can handle.

like image 44
Aaron Brager Avatar answered Aug 16 '26 02:08

Aaron Brager