简体   繁体   English

如何创建与已经拥有的对象相同类的新对象?

[英]How can I create a new object of the same class as an object I already have?

I've an array which holds different kinds of objects: UIButton s, UILabel s, UITableView s, etc. 我有一个包含不同类型对象的数组: UIButtonUILabelUITableView等等。

Is there any way that I can dynamically create these objects while looping through the array without using if / else conditions like below: 有什么方法可以在不使用if / else条件的情况下遍历数组时动态创建这些对象,如下所示:

for (NSObject *obj in objectsArray)
{
    if ([obj isKindOfClass:[UIButton class]]) 
    {
         UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
         [self.view addSubview:btn];
    }
    else if ([obj isKindOfClass:[UILabel class]]) 
    {
        UILabel *lbl = (UILabel*)obj;
        [self.view addSubview:lbl];
    }
}

Can we create objects like UIButton *btn or UILabel *lbl using reflection or something dynamically? 我们是否可以使用反射或动态方式创建UIButton *btnUILabel *lbl类的对象?

you could either do 你可以做

for (Class _class in classArray) {
    id object = [[_class alloc] init];
}

or 要么

for (NSString *className in classNameArray) {
    id object = [[NSClassFromString(className) alloc] init];
}

so you dont need Instances for the class-reference. 因此您不需要实例作为类引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我必须创建一个新的 object 还是可以使用方法参数? - do I have to create a new object or can I use a method param? 如何使用与上一个相同的对象引用在可变数组中添加新对象实例 - How can i add new object instance in a mutable array using same object reference as the previous one 我如何从用户输入的NSString创建类的新对象 - How would i create an new object of my class from a user inputed NSString 如何检测我拥有的 object 是否真的是 NSProxy? - How can I detect if an object I have is really an NSProxy? 我是否将同一个对象与prepareForSegue一起传递回去? - Have i pass the same object with prepareForSegue back? 如何查找NSMutableArray中是否已经存在具有相同数据的类的对象? - How to find if an object of a class with same data already exists in a NSMutableArray? 如何获得在另一个类中声明的类对象? - How can I get a class object that is declared in another class? 如何将对象作为参数从一个类传递到另一个类? - How can i pass object as parameter from a class to another class? 如何创建名称存储在字符串中的类的对象? - How do I create an object of a class whose name is stored in a string? 将其设置为新对象时,是否必须在Objective-C保留类变量上调用release? - Do I have to call release on an objective-c retain class variable when setting it to a new object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM