I want to use a user inputed name in the form of an NSString to create a new instance of my class. I have seen NSClassFromString but i’m not getting it. My end goal is to have the user enter a name of an expense and then use that entered name, which is stored in an NSString variable, to create a new instance of my class. Then the user will enter a few more things that will set the instance variable of the new object.
This will all be in a loop where the user will be able to create as many new objects as they want and the objects will be stored in an array for latter storage and use. But i’m stuck on how to dynamically create a new instance of my class.
What kind of object are you trying to create? Do you always want to create the same kind of object, or do you want to let the user enter the object type, and create an object of that type?
If you want to always create the same kind of object and set one of it’s properties to a user-entered string, that’s easy.
Add a UITextField and button to a view controller. In the action method for the button, get the text value from the text field, and use that to set the text in your object:
If you want the user to be able to input the class name, don’t. That is far too fragile. The user could easily enter a classname for a class that would cause your app to behave unexpectedly, or even crash. You would use NSClassFromString for that, but it is a really bad idea to let the user specify a class name. Don’t do it.
Instead, have the user pick from a list of different options (using buttons, or a table view, or a stepper, or something else) and then use a switch statement to create a new object of the requested type. You’d have a case for each supported type of object the user could create.