对象与字符串的名称 [英] object with the name of a string

查看:115
本文介绍了对象与字符串的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个类的对象,我做:

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"];

这篇关于对象与字符串的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆