1

我确信这是一个非常基本的程序,所以请原谅这个新手问题。

如何使用相同的代码初始化多个对象,但每个对象都有一个唯一的名称?我可以创建一个字符串来表示 theName,但我将如何将它应用为实际的对象名称?我可以重命名对象吗?

顺便说一句,目的是让我可以在以后对每个按名称引用它们的对象执行操作...我认为唯一的名称将是解决此问题的方法...

    NSString *theName = [NSString stringWithFormat:@"textView%d",tvNum];

    tvNum ++;

    UITextView *myTextView = [[UITextView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width /2, self.view.bounds.size.height /2, 100, 100)];
    [self.view addSubview:myTextView];
    NSString *theText = [[NSString alloc] initWithString:@"string"];
    [myTextView setText:theText];
4

2 回答 2

1

您可以稍后将标签添加到控制器以引用它。

myTextView.tag = somePreCalculatedTagValue;

然后通过将该标签值与控制器匹配,您可以做您想做的事

if(myTextView.tag == kTagForFirstTextView)
{
//do something
}  
于 2012-09-03T05:39:49.287 回答
1

最好创建一个对象数组。您可以使用 for 循环来设置它们:

NSMutableArray *objectArray = [[NSMutableArray alloc] initWithCapacity:NUM_OF_OBJECTS];

for (int i = 0; i < NUM_OF_OBJECTS; i++) {
    UITextView *myTextView = [[UITextView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width /2, self.view.bounds.size.height /2, 100, 100)];
    [myTextView setText:@"string"];
    [objectArray addObject:myTextView];
    [self.view addSubview:myTextView];
}

稍后通过它们的索引引用它们:

UITextView *thirdTextView = [objectArray objectAtIndex:2];
thirdTextView.text = @"Foobar";

要不就:

[objectArray objectAtIndex:2].text = @"Foobar";
于 2012-09-03T05:48:11.397 回答