Use NSTimer in Iphone

We create a small project using NSTimers.Its simple to use in a application. For the random movement of square, we are used timer.

Step 1: Create a new project in Xcode using View-base application.

Step 2: In your viewcontroller class, need to add the following code:

- (void)viewDidLoad {
    [super viewDidLoad];

	CGRect RectFrame;
	RectFrame.origin.x = 25;
	RectFrame.origin.y = 300;
	RectFrame.size.width = 20;
	RectFrame.size.height = 20;

	for(int i = 0; i < 10; i++)
	{
	 UIView *myView = [[UIView alloc] initWithFrame:RectFrame];
	[myView setTag:i];
	[myView setBackgroundColor:[UIColor yellowColor]];

	RectFrame.origin.x = RectFrame.origin.x + RectFrame.size.width + 10;
	[self.view addSubview:myView];
	}

	Timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(moveRect) userInfo:nil repeats:YES];
}


-(void)moveRect
{
	int r = rand() % 10;

	for(UIView *aView in [self.view subviews])
	{
		if([aView tag] == r)
		{
		 int movement = rand() % 100;
		 CGRect RectFrame = aView.frame;
		 RectFrame.origin.y = RectFrame.origin.y - movement;

		 [UIView beginAnimations:nil context:NULL];
		 [UIView setAnimationDuration:.2];
		 [aView setFrame:RectFrame];
		 [UIView commitAnimations];

		 if(RectFrame.origin.y < 0)
		{
		  [Timer invalidate];
		}
	   }
	}
}



Step 3: Now compile and run your Simulator.(See Figure 1)

Figure 1: Random movement of Square.

You can downloaded SourceCode from here TimerExample 2

  • Rick
  • February 3, 2010
  • iOS

About the Author

Leave a Reply 0 comments

Leave a Reply: