NSTimer用法小结
Timers的替代方法
如果只是要延迟消息的发送,可以使用NSObject的方法
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget
创建Timer的三种方法
1.scheduling a timer with the current run loop
2.creating a timer that you later register with a run loop
3.initializing a timer with a given fire date
Scheduled Timers
以下两个方法自动注册新创建的timer到当前NSRunLoop对象,NSRunLoop的模式为默认的NSDefaultRunLoopMode
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds invocation:(NSInvocation*)invocation repeats:(BOOL)repeats
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
只发送一次
[plain] view plaincopyprint?
1 - (IBAction)startOneOffTimer:sender {
2
3 [NSTimer scheduledTimerWithTimeInterval:2.0
4 target:self
5 selector:@selector(targetMethod:)
6 userInfo:[self userInfo]
7 repeats:NO];
8 }
- (IBAction)startOneOffTimer:sender {
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(targetMethod:)
userInfo:[self userInfo]
repeats:NO];
}
重复发送消息
注:创建重复发送消息的timer一般需要保存一个引用,因为需要在某个时刻停止发送消息
[plain] view plaincopyprint?
9 - (IBAction)startRepeatingTimer:sender {
10
11 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
12 target:self selector:@selector(timerFireMethod:)
13 userInfo:[self userInfo] repeats:YES];
14 self.repeatingTimer = timer;
15 }
- (IBAction)startRepeatingTimer:sender {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self selector:@selector(timerFireMethod:)
userInfo:[self userInfo] repeats:YES];
self.repeatingTimer = timer;
}
Unscheduled Timers
创建未注册的timer,使用时调用addTimer:forMode注册到NSRunLoop对象
timerWithTimeInterval:target:selector:userInfo:repeats:
timerWithTimeInterval:invocation:repeats:
[plain] view plaincopyprint?
16 - (IBAction)createUnregisteredTimer:sender {
17
18 NSMethodSignature *methodSignature = [self methodSignatureForSelector:@selector(invocationMethod:)];
19 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
20 [invocation setTarget:self];
21 [invocation setSelector:@selector(invocationMethod:)];
22 NSDate *startDate = [NSDate date];
23 [invocation setArgument:&startDate atIndex:2];
24
25 NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 invocation:invocation repeats:YES];
26 self.unregisteredTimer = timer;
27 }
- (IBAction)createUnregisteredTimer:sender {
NSMethodSignature *methodSignature = [self methodSignatureForSelector:@selector(invocationMethod:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:self];
[invocation setSelector:@selector(invocationMethod:)];
NSDate *startDate = [NSDate date];
[invocation setArgument:&startDate atIndex:2];
NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 invocation:invocation repeats:YES];
self.unregisteredTimer = timer;
}
[plain] view plaincopyprint?
28 - (IBAction)startUnregisteredTimer:sender {
29 if (unregisteredTimer != nil) {
30 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
31 [runLoop addTimer:unregisteredTimer forMode:NSDefaultRunLoopMode];
32 }
33 }
- (IBAction)startUnregisteredTimer:sender {
if (unregisteredTimer != nil) {
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:unregisteredTimer forMode:NSDefaultRunLoopMode];
}
}
Initializing a Timer with a Fire Date
创建一个拥有指定发送日期的timer
[plain] view plaincopyprint?
34 - (IBAction)startFireDateTimer:sender {
35 NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
36 NSTimer *timer = [[NSTimer alloc] initWithFireDate:fireDate
37 interval:0.5
38 target:self
39 selector:@selector(countedtargetMethod:)
40 userInfo:[self userInfo]
41 repeats:YES];
42
43 timerCount = 1;
44 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
45 [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
46 [timer release];
47 }
- (IBAction)startFireDateTimer:sender {
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
NSTimer *timer = [[NSTimer alloc] initWithFireDate:fireDate
interval:0.5
target:self
selector:@selector(countedtargetMethod:)
userInfo:[self userInfo]
repeats:YES];
timerCount = 1;
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
[timer release];
}
Stopping a Timer
[plain] view plaincopyprint?
48 - (IBAction)stopRepeatingTimer:sender {
49 [repeatingTimer invalidate];
50 self.repeatingTimer = nil;
51 }
52
- (IBAction)stopRepeatingTimer:sender {
[repeatingTimer invalidate];
self.repeatingTimer = nil;
}
[plain] view plaincopyprint?
53 也可以从timer发送的消息中停止timer
也可以从timer发送的消息中停止timer
[plain] view plaincopyprint?
54 - (void)countedtargetMethod:(NSTimer*)theTimer {
55
56 NSDate *startDate = [[theTimer userInfo] objectForKey:@"StartDate"];
57 NSLog(@"Timer started on %@; fire count %d", startDate, timerCount);
58
59 timerCount++;
60 if (timerCount > 3) {
61 [theTimer invalidate];
62 }
63 }
- (void)countedtargetMethod:(NSTimer*)theTimer {
NSDate *startDate = [[theTimer userInfo] objectForKey:@"StartDate"];
NSLog(@"Timer started on %@; fire count %d", startDate, timerCount);
timerCount++;
if (timerCount > 3) {
[theTimer invalidate];
}
}
Memory Management
1. The run loop maintains the timer that is registered to it.
2. The timer is passed as an argument when you specify its method as a selector
3. You should maintain a strong reference to the unscheduled timer, in order to ensure that it's not deallocated before you use it.
4. A timer maintains a strong reference to its user info dictionary,
5. A timer maintains a strong reference to its target, so you should make sure that your timer's target survive longer than the timer itself.