NSTimer的用法

来源:互联网 发布:听见下雨的声音 知乎 编辑:程序博客网 时间:2024/04/29 03:52
实现类似油表数字转动效果,用了时间定时器NSTimer,转载一篇小文。

iphone为我们提供了一个很强大的时间定时器 NSTimer可以完成任何定时功能:
我们使用起来也很简单,只要记住三要素就可以,具体得三要素是:时间间隔NSTimeInterval浮点型,事件代理
delegate和事件处理方法@selector();就可以用
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 来初始化一个 时间定时器
下面很简单的例子
-(void)initTimer
{
//时间间隔
NSTimeInterval timeInterval =1.0 ;
//定时器
NSTimer   showTimer = [NSTimer scheduledTimerWithTimeInterval:maxShowTime
                                                                 target:self
                                                           selector:@selector(handleMaxShowTimer:)
                                                               userInfo:nil
                                                                repeats:NO];
}
//触发事件
- (void)handleMaxShowTimer:(NSTimer *)theTimer
{
       NSDateFormatter dateFormator = [[NSDateFormatter alloc] init];
       dateFormator.dateFormat = @"yyyy-MM-dd  HH:mm:ss";
       NSString *date = [dateformater stringFromDate:[NSDate date]];
        if([date isEqualToString:@"2010-11-09 23:59:59"])
          {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:TITLE_NAME
                                                    message:@"现在马上就有新的一天了!"
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:CONFIRM_TITLE, nil];
                [alert show];
                [alert release];
          }
      [data release];
      [dateFormator release];
}
另外附一个例子:方框赛跑

      - (void)viewDidLoad

        {

                [super viewDidLoad];

                CGRect workingFrame;

                workingFrame.origin.x = 15;

                workingFrame.origin.y = 400;

                workingFrame.size.width = 40;

                workingFrame.size.height = 40;
 
               for(int i = 0; i < 6; i++)
                {

                        UIView *myView = [[UIView alloc] initWithFrame:workingFrame];
                        [myView setTag:i];//标记方块
                        [myView setBackgroundColor:[UIColor blueColor]];
 
                       workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width + 10;
 [self.view addSubview:myView];

                }

               
//每隔一秒执行moveACar方法一次
                myTimer = [NSTimer scheduledTimerWithTimeInterval:1 
target:self
selector:@selector(moveACar)
 userInfo:nil repeats:YES];
        }