NSTimer的用法

来源:互联网 时间:1970-01-01

iPhone为我们提供了一个很强大得时间定时器 NSTimer,它可以完成任何定时功能:

我们使用起来也很简单,只要记住三要素就可以,具体得三要素是:时间间隔NSTimeInterval浮点型,事件代理delegate和事件处理方法@selector();

就可以用

1 + (NSTimer *)scheduledTimerWithTimeIn

2 terval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

来初始化一个 时间定时器下面我写了一个很简单得例子:
 1 -(void)initTimer
2 {
3 //时间间隔
4 NSTimeInterval timeInterval =1.0 ;
5 //定时器
6 NSTimer showTimer = [NSTimer scheduledTimerWithTimeInterval:maxShowTime
7 target:self
8 selector:@selector(handleMaxShowTimer:)
9 userInfo:nil
10 repeats:NO];
11 }
12 //触发事件
13 - (void)handleMaxShowTimer:(NSTimer *)theTimer
14 {
15 NSDateFormatter dateFormator = [[NSDateFormatter alloc] init];
16 dateFormator.dateFormat = @"yyyy-MM-dd HH:mm:ss";
17 NSString *date = [dateformater stringFromDate:[NSDate date]];
18 if([date isEqualToString:@"2010-11-09 23:59:59"])
19 {
20 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:TITLE_NAME
21 message:@"现在马上就有新的一天了!"
22 delegate:self
23 cancelButtonTitle:nil
24 otherButtonTitles:CONFIRM_TITLE, nil];
25 [alert show];
26 [alert release];
27 }
28 [data release];
29 [dateFormator release];
30 }


另外附一个例子:方框赛跑
 1 - (void)viewDidLoad
2
3 {
4
5 [super viewDidLoad];
6
7 CGRect workingFrame;
8
9 workingFrame.origin.x = 15;
10
11 workingFrame.origin.y = 400;
12
13 workingFrame.size.width = 40;
14
15 workingFrame.size.height = 40;
16
17
18
19 for(int i = 0; i < 6; i++)
20
21 {
22
23 UIView *myView = [[UIView alloc] initWithFrame:workingFrame];
24
25 [myView setTag:i];//标记方块
26
27 [myView setBackgroundColor:[UIColor blueColor]];
28
29
30
31 workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width + 10;
32
33 [self.view addSubview:myView];
34
35 }
36
37
38
39 myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moveACar) userInfo:nil repeats:YES];//每隔一秒执行moveACar方法一次
40
41 }


      


相关阅读:
Top