Jean Pierre
Jean Pierre

Reputation: 211

How to create a new UIImageView with a different instance variable every time a timer is called

how are you guy's?

I want to make a new instance variable every time a timer is called for e.g.

        numberofObjects += 1;
    i = numberofObjects;

    UIImageView *Object[i] = [[UIImageView alloc] initWithFrame:CGRectMake(randomx,0,36 ,36)];        
    UIImage *imag = [UIImage imageNamed:@"ball.png"];
    [Object[i] setImage:imag];
    [self.view addSubview:Object[i]];

Is there a way to do this?

Any comments will be appreciated.

Upvotes: 0

Views: 1351

Answers (2)

msgambel
msgambel

Reputation: 7340

This isn't too hard to do. I make the assumption that you are only going to have a maximum number of UIImageViews, as this can add a lot of overhead, and you may run into problems if it's allowed to continue forever. In the .h file,

@interface viewController : UIViewController {
  int numberAdded;
  NSTimer * timer;
  UIImageView * currentImageView;
  NSMutableArray * arrayOfImageViews;
}

- (void)addNewImageView;

@end

In the .m file:

#define MaxImageViews 20 // This is changeable!

@implementation viewController

- (void)viewDidLoad; {
  [super viewDidLoad];
  numberAdded = 0;
  arrayOfImageViews = [[NSMutableArray alloc] init];
  timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(addNewImageView) userInfo:nil repeats:YES];
}

- (void)addNewImageView; {
  if(numberAdded >= MaxImageViews){
    [timer invalidate];
    timer = nil;
    return;
  }
  int randomX = arc4random() % 320; // Gives value from 0 - 319.
  int randomY = arc4random() % 480; // Gives value from 0 - 479.
  UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(randomX, randomY, 36, 36)];
  imageView.image = [UIImage imageNamed:@"ball.png"];
  [self.view addSubview:imageView];
  [arrayOfImageViews addObject:imageView];
  [currentImageView release];
      currentImageView = imageView;
    }

- (void)dealloc; {
  [currentImageView release];
  [arrayOfImageViews release];
  [super dealloc];
}

@end

This should keep track of all of the imageViews in the array arrayOfImageViews, and you can access the i-th imageView by calling [arrayOfImageViews objectAtIndex:i]. The currentImageView pointer keeps track of the latest UIImageView added. Hope that helps!

Upvotes: 2

Peter Hosey
Peter Hosey

Reputation: 96333

Store the image views' pointers in an NSMutableArray object.

Upvotes: 0

Related Questions