Object named string
if i create a class object i do:
Item *item01 = [[Item alloc] init];
but how can I call this name in a string? (I am asking this question because I have to do it in a loop and the object name is dynamic)
NSString *aString = [NSString stringWithFormat:@"%@", var];
Item *??? = [[Item alloc] init];
thank!
source to share
If you want to pass an object by string name, you store your objects in an NSMutableDictionary and set the key to the name.
For example:
// Someplace in your controller create and initialize the dictionary
NSMutableDictionary *myItems = [[NSMutableDictionary alloc] initWithCapacity:40];
// Now when you create your items
Item *temp = [[Item alloc] init];
[myItems setObject:temp forKey:@"item01"];
[temp release];
// This way when you want the object, you just get it from the dictionary
Item *current = [myItems objectForKey:@"item01"];
source to share
the need to change the variable name ( Item *???
) is very unusual - there is often a preprocessor abuse.
instead, I think you can search for instances of types by name.
To do this, use a combination id
, Class
apis, NSClassFromString
.
id
is a pointer to an undefined object objc that the compiler will "accept" any declared message:
id aString = [NSString stringWithFormat:@"%@", var];
now you can query aString
for execution selectors that it cannot respond to. it is like a void*
for objc. note that you will get a runtime exception if you pass a variable id
using a selector it doesn't respond to.
next, type Class
:
Class stringClass = [NSString class];
NSString * aString = [stringClass stringWithFormat:@"%@", var];
to put it all together to instantiate a type by name:
NSString * className = [stringClass stringWithFormat:@"%@", var];
Class classType = NSClassFromString(className);
assert(classType && "there is no class with this name");
id arg = [[classType alloc] init];
source to share