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];
}