objective-c - 具有字符串名称的对象

标签 objective-c cocoa

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

Item *item01 = [[Item alloc] init];

但是我如何给它一个字符串中的名称呢? (我提出这个问题是因为我必须在循环中执行此操作,并且对象的名称是动态的)

NSString *aString = [NSString stringWithFormat:@"%@", var];
Item *??? = [[Item alloc] init];

谢谢!

最佳答案

如果您想通过字符串名称引用对象,则可以将对象存储在 NSMutableDictionary 中并将 key 设置为名称。

例如:

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

关于objective-c - 具有字符串名称的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6164134/

相关文章:

objective-c - Cocoa 应用程序最简单的 Markdown 实现是什么?

iphone - 嵌套 CALayers 不接受透视变换

objective-c - 如何从我的类列表中找到从特定类继承的类?

Cocoa/CoreGraphics/Quartz - 无边框 Quicktime X 窗口,具有圆边

objective-c - NSImage initWithContentsOfFile : display progress

iphone - MKMapView map 类型没有改变?

objective-c - 如何居中 NSSegmentedControl

objective-c - 声明变量 "id"和 "NSObject *"有什么区别?

objective-c - CoreData,单独线程上的子 MOC,意外 : error: NULL _cd_rawData but the object is not being turned into a fault

objective-c - 如何在 objective-c 中以编程方式设置标签栏项目标题?