object with the name of a string
if I create an object of a class, I do:
Item *item01 = [[Item alloc] init];
but how do I give it a name I have in a string? (I make this question because I have to do this in a 开发者_开发百科loop, and the name of object is dynamic)
NSString *aString = [NSString stringWithFormat:@"%@", var];
Item *??? = [[Item alloc] init];
thanks!
If you want to refer the object by the name of the string, you would store your objects in 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"];
You cannot have variable name from a string. What are you trying to achieve here? You can use dictionary for looking up variable from a string key.
Check this similar question
the need to change the name of a variable (Item *???
) is very unusual -- it's often preprocessor abuse.
instead, i think you may be looking to create instances of types by name.
to do this use a combination of id
, Class
apis, NSClassFromString
.
id
is a pointer to an undefined objc object, which the compiler will 'accept' any declared message to:
id aString = [NSString stringWithFormat:@"%@", var];
now you can request aString
to perform selectors it may not respond to. it's similar to a void*
for an objc type. note that you'll get a runtime exception if you message an id
variable using a selector it does not respond to.
next, the Class
type:
Class stringClass = [NSString class];
NSString * aString = [stringClass stringWithFormat:@"%@", var];
to combine all this to create an instance of 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];
精彩评论