Reputation: 5132
I'm sure this is a very basic procedure, so excuse this newbie question.
How would I initialize several objects, with the same code, but each with a unique name? I can make a string to represent theName, but how would I apply that as the actual objects name? Can I rename the object?
BTW the purpose is so that I can perform operations on each object referring to them by name, at a later time... I think that unique names would be a solution to this issue...
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];
Upvotes: 1
Views: 254
Reputation: 3698
It would be better to create an array of objects. You can use a for loop to set them up:
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];
}
and later refer to them later by their index:
UITextView *thirdTextView = [objectArray objectAtIndex:2];
thirdTextView.text = @"Foobar";
or just:
[objectArray objectAtIndex:2].text = @"Foobar";
Upvotes: 1
Reputation: 574
You can add tags to your controller later to refer it.
myTextView.tag = somePreCalculatedTagValue;
and later by matching that tag value with controller you can do what you want
if(myTextView.tag == kTagForFirstTextView)
{
//do something
}
Upvotes: 1