对象与字符串的名称
问题描述:
如果我创建一个类的对象,我做:
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];
谢谢!
答
如果要通过字符串的名称引用对象,则可以将对象存储在 NSMutableDictionary 并将键设置为名称。
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.
:
// 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"];