How to create multiple objects with the same Obj C code, each with a unique name?

advertisements

How do I create multiple objects with the same code, but each with a unique name?

If I create an object in objective C something like:

MyClass *myObject = [[MyClass alloc] init];

I have an object named myObject that I can refer to, to do stuff like:

[myObject setBackgroundColor:[UIColor blueColor]];

But what if I want to create multiple objects with the same allocation code? For instance if I am using this code in an action so that every time a button is tapped a new object is created. Then I would have multiple objects named myObject. SO when I used the code to set the background color it would turn all of myObject's background color blue.

If each object created had a unique name this would not be an issue, but how to give each object created with the same code a unique name?

One way would be to rename the objects after creation and attach a number increment, but how can I rename an object? Or maybe I could set each object created with a unique name in the first place, but how can I insert a unique "string" for the name of each new object?

Thanks for reading!

UPDATE!!

I created an "init with tag method", but each time I create a new object the previously created object also receives the new tag, so each object has the same tag, not unique tags. Any help?

The init method:

- (id) initWithTag:(int) theTag
{
    self = [self init];
    if (self)
    {
        self.tag = theTag;
    }
    return self;
}

The object creation code:

MyClass *myObject = [[MyClass alloc] initWithTag:tagCount];
tagCount ++;


I had the same request, longer time ago.

I prefer to do it that way:

@implementation testViewController {
    NSMutableArray *myarray;
}

- (id)init
{
    self = [super init];
    if (self) {
        myarray = [NSMutableArray array];
    }
    return self;
}

- (void) buttonClickMethod {
    MyClass *myObject = [[MyClass alloc] init];
    [myObject setBackgroundColor:[UIColor blueColor]];
    [myarray addObject:myObject];
    [myObject release];
}

So you have an array with separate objects in it. You can iterate through it. You even can set the initial backgroundColor - when you tap the button - to a color based on the users choice. (in my example the color always would be blue)