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

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

问题描述

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

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天全站免登陆