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.
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"];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With