I have to cast an object to a type which is contained in a string and I don’t know if it’s possible.
My class is in a string :
NSString *myClass = @"User";
and I have an object that I want to cast with this type.
object = (myClass)object; // Doesn't work
object = (myClass *)object; // Doesn't work
How can I do that ?
There’s no point to doing this — objects’ static types only get checked at compile time, and this could only happen at runtime even if there were a way to do it (since objects such as strings don’t actually exist until runtime).
If you’re trying to change the object from one class to another, that wouldn’t work anyway — casting from one pointer type to another only lies to the compiler about what type of data it points to, it doesn’t actually change the data. In order to convert objects from one type to another, there has to be a method or function that takes the data from the old object and creates a new object of the desired type (such as NSString’s
dataUsingEncoding:to convert from NSString to NSData).But if you have a dynamically selected class and you need some type to give the variables for instances of that class, you can just use
id(possibly with a protocol if all the possible classes respond to the same messages).