3 回答

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
NSTimer
,
定時(shí)器 使用計(jì)時(shí)器
[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
因?yàn)镽un循環(huán)從內(nèi)存管理的角度來(lái)維護(hù)計(jì)時(shí)器。 通常情況下,在調(diào)度計(jì)時(shí)器之后,不需要保留對(duì)它的引用..由于計(jì)時(shí)器在將其方法指定為選擇器時(shí)作為參數(shù)傳遞, 在適當(dāng)?shù)那闆r下,可以在該方法中使重復(fù)計(jì)時(shí)器失效。..然而,在許多情況下,您還想要使計(jì)時(shí)器無(wú)效的選項(xiàng)-甚至在計(jì)時(shí)器開(kāi)始之前。 在這種情況下,您確實(shí)需要保持對(duì)計(jì)時(shí)器的引用,以便在適當(dāng)?shù)臅r(shí)候發(fā)送一條無(wú)效消息。..如果您創(chuàng)建了一個(gè)非計(jì)劃計(jì)時(shí)器(請(qǐng)參閱“非計(jì)劃計(jì)時(shí)器”),那么您必須維護(hù)對(duì)計(jì)時(shí)器的強(qiáng)烈引用(在引用計(jì)數(shù)環(huán)境中,您保留它),以便在使用它之前不會(huì)將它釋放。

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
1) 計(jì)劃計(jì)時(shí)器&使用選擇器
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector:@selector(onTick:) userInfo: nil repeats:NO];
如果將重復(fù)設(shè)置為“否”,則計(jì)時(shí)器將在運(yùn)行選擇器之前等待2秒,然后停止運(yùn)行; 如果重復(fù):是的,計(jì)時(shí)器將立即啟動(dòng),并將重復(fù)調(diào)用選擇器每2秒; 若要停止計(jì)時(shí)器,請(qǐng)調(diào)用計(jì)時(shí)器的-無(wú)效方法:[t無(wú)效];
[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];
2) 自定時(shí)器
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)建一個(gè)定時(shí)器,該定時(shí)器將在您指定的自定義日期(在本例中為一分鐘后)啟動(dòng),并且每隔一秒重復(fù)一次。
3) 計(jì)劃外計(jì)時(shí)器&使用調(diào)用
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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
NSTimer *timer; timer = [NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(handleTimer:) userInfo: nil repeats: YES];
- 3 回答
- 0 關(guān)注
- 514 瀏覽
添加回答
舉報(bào)