3 回答

TA貢獻1880條經驗 獲得超4個贊
NSTimer
,
定時器 使用計時器
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats:NO];
targetMethod:
self
NSTimer
NSTimer
invalidate
NSTimer
[myTimer invalidate];myTimer = nil;
nil
nil
NSTimer
因為Run循環(huán)從內存管理的角度來維護計時器。 通常情況下,在調度計時器之后,不需要保留對它的引用..由于計時器在將其方法指定為選擇器時作為參數傳遞, 在適當的情況下,可以在該方法中使重復計時器失效。..然而,在許多情況下,您還想要使計時器無效的選項-甚至在計時器開始之前。 在這種情況下,您確實需要保持對計時器的引用,以便在適當的時候發(fā)送一條無效消息。..如果您創(chuàng)建了一個非計劃計時器(請參閱“非計劃計時器”),那么您必須維護對計時器的強烈引用(在引用計數環(huán)境中,您保留它),以便在使用它之前不會將它釋放。

TA貢獻1810條經驗 獲得超4個贊
1) 計劃計時器&使用選擇器
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector:@selector(onTick:) userInfo: nil repeats:NO];
如果將重復設置為“否”,則計時器將在運行選擇器之前等待2秒,然后停止運行; 如果重復:是的,計時器將立即啟動,并將重復調用選擇器每2秒; 若要停止計時器,請調用計時器的-無效方法:[t無效];
[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];
2) 自定時器
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];NSTimer *t = [[NSTimer alloc] initWithFireDate: d interval: 1 target: self selector:@selector(onTick:) userInfo:nil repeats:YES];NSRunLoop *runner = [NSRunLoop currentRunLoop]; [runner addTimer:t forMode: NSDefaultRunLoopMode];[t release];
這將創(chuàng)建一個定時器,該定時器將在您指定的自定義日期(在本例中為一分鐘后)啟動,并且每隔一秒重復一次。
3) 計劃外計時器&使用調用
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];[inv setTarget: self];[inv setSelector:@selector(onTick:)];NSTimer *t = [NSTimer timerWithTimeInterval: 1.0 invocation:inv repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];[runner addTimer: t forMode: NSDefaultRunLoopMode];
-(void)onTick:(NSTimer *)timer { //do smth}

TA貢獻1802條經驗 獲得超5個贊
NSTimer *timer; timer = [NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(handleTimer:) userInfo: nil repeats: YES];
- 3 回答
- 0 關注
- 508 瀏覽
添加回答
舉報