NSTimer 使用

phone为咱们提供了一个很强大得时间定时器 NSTimer
他能够完成任何定时功能:
咱们使用起来也很简单,只要记住三要素就能够,具体得三要素是:时间间隔NSTimeInterval浮点型,事件代理
delegate和事件处理方法@selector();就能够用
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 来初始化一个 时间定时器

NSTimer是Cocoa中比较经常使用的定时器类,基本操做以下:
handleTimer方法能够自行定义。在须要的地方建立timer便可,handleTimer就能够每0.5秒执行一次。 spa

例: 代理

 

- (void) handleTimer: (NSTimer *) timer
{
   //在这里进行处理
}
 
NSTimer *timer;
 
timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
             target: self
             selector: @selector(handleTimer:)
             userInfo: nil
             repeats: YES]; orm

 

 

下面我写了一个很简单得例子
-(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];

                }
相关文章
相关标签/搜索