[英]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. 我有一个包含不同类型对象的数组:
UIButton
, UILabel
, UITableView
等等。
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 *btn
或UILabel *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.