Search code examples
iphoneiosobjectsdkclone

How do I create new instances of an object in ios?


I'm working on a concept that will have objects falling from the top of the screen. For this example lets say, 4 objects: red square, blue square, green square, yellow square.

I have all of these objects placed in the interface builder and connected with the names given in the .h files: IBObject UIImageView *greenSquare; for example.

I able to interact with the "greenSquare" fine and have it fall from the top of the view to the bottom and disappear off the view. Right now I want to be able to recreate the "greenRectangle" and have it fall again. I can't just reset that one instance since at any given point 1 or more of the same object would be falling.

The end result would be x number of the squares of any of the colors would be showing and falling.

I'm sure my workflow for this would be:

  • Set time to pick square
  • position square
  • show square
  • drop square at x rate

Any push in the right direction would be great. Thanks everyone!


Solution

  • here is what I did:

    in my .h file I created the object instances:

    UIImageView *yellowImage;
    UIImageView *greenImage;
    UIImageView *orangeImage;
    UIImageView *redImage;
    
    UIImage *yellow;
    UIImage *green;
    UIImage *orange;
    UIImage *red;
    

    I then set the images:

    green = [UIImage imageNamed:@"greenball.png"];
    yellow = [UIImage imageNamed:@"yellowball.png"];
    orange = [UIImage imageNamed:@"orangeBall.png"];
    red = [UIImage imageNamed:@"redball.png"];
    

    I called a method and set a timer:

    [NSTimer scheduledTimerWithTimeInterval:(0.5) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    

    finally, inside the onTimer I create a random number that chooses a ball and creates it like this:

    greenImage = [[UIImageView alloc] initWithImage:green];
    greenImage.frame = CGRectMake(startX,0,43,43);
    [self.view insertSubview:greenImage belowSubview:bottomBar];