NSTimer 的初始化
初始化方法:有五種初始化方法
- (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
//例如:
//初始化一個(gè)Invocation對(duì)象
NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];
[invo setTarget:self];
[invo setSelector:@selector(timerAction)];
NSTimer * timer = [NSTimer timerWithTimeInterval:1 invocation:invo repeats:YES];
//加入主循環(huán)池中
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
//開始循環(huán)
[timer fire];
- (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
//例如:
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 invocation:invo repeats:YES];
- (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
//例如:
NSTimer * timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
- (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
//例如:
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:@"123" repeats:YES];
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)repeats:(BOOL)yesOrNo;
//例如:
NSTimer * timer = [[NSTimer alloc]initWithFireDate:[NSDate distantPast] interval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
它的屬性
@property (copy) NSDate *fireDate;//這是設(shè)置定時(shí)器的啟動(dòng)時(shí)間践付,常用來管理定時(shí)器的啟動(dòng)與停止
//啟動(dòng)定時(shí)器
timer.fireDate = [NSDate distantPast];
//停止定時(shí)器
timer.fireDate = [NSDate distantFuture];
@property (readonly) NSTimeInterval timeInterval;//這個(gè)是一個(gè)只讀屬性烁峭,獲取定時(shí)器調(diào)用間隔時(shí)間
@property NSTimeInterval tolerance;//這是7.0之后新增的一個(gè)屬性胶台,因?yàn)镹STimer并不完全精準(zhǔn)尚骄,通過這個(gè)值設(shè)置誤差范圍
@property (readonly, getter=isValid) BOOL valid;//獲取定時(shí)器是否有效
@property (readonly, retain) id userInfo;//獲取參數(shù)信息
釋放,銷毀定時(shí)器
[timer invalidate];//是唯一的方法將定時(shí)器從循環(huán)池中移除
timer=nil;//同時(shí)置空