gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:29:42 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com