【问题标题】:object with the name of a string具有字符串名称的对象
【发布时间】:2011-05-28 20:17:48
【问题描述】:

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

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

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

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

谢谢!

【问题讨论】:

标签: objective-c cocoa


【解决方案1】:

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

例如:

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

【讨论】:

  • 工作正常,但如果我想从 SuperView 中删除 item01,我该怎么做?这样做,它不起作用 '[[myItems objectForKey:@"item01"] removeFromSuperview];'
  • 所以你的Item对象超类是UIView?如果是这样,您应该阅读UIView continues to exist after removeFromSuperview
【解决方案2】:

您不能从字符串中获得变量名。你想在这里达到什么目的?您可以使用字典从字符串键中查找变量。

检查这个类似的question

【讨论】:

    【解决方案3】:

    需要更改变量的名称 (Item *???) 是非常不寻常的——这通常是预处理器滥用。

    相反,我认为您可能希望按名称创建类型的实例

    为此使用idClass apis、NSClassFromString 的组合。

    id 是指向未定义的 objc 对象的指针,编译器将“接受”任何已声明的消息:

    id aString = [NSString stringWithFormat:@"%@", var];
    

    现在您可以请求aString 执行它可能无法响应的选择器。它类似于 objc 类型的 void*。请注意,如果您使用不响应的选择器向 id 变量发送消息,则会收到运行时异常。

    接下来,Class 类型:

    Class stringClass = [NSString class];
    NSString * aString = [stringClass stringWithFormat:@"%@", var];
    

    结合所有这些以按名称创建类型的实例:

    NSString * className = [stringClass stringWithFormat:@"%@", var];
    Class classType = NSClassFromString(className);
    assert(classType && "there is no class with this name");
    id arg = [[classType alloc] init];
    

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      相关资源
      最近更新 更多