//第一种,自动触发定时器
{
NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(t:) userInfo:@{@"sdfsdf":@"df"} repeats:YES];
NSTimer *time2 = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(t:) userInfo:@"sdfsdf" repeats:YES];
//这里是提前触发,不写也会在设定间隔时间触发
[time fire];
//对应的销毁函数
// [time invalidate];
}
//第二种,手动触发
{
NSTimer *time3 = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(t:) userInfo:@"sdf" repeats:YES];
NSRunLoop *runloop=[NSRunLoop currentRunLoop];
[runloop addTimer:time3 forMode:NSDefaultRunLoopMode];
}
//第三种
{
//初始化一个Invocation对象
NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];
[invo setTarget:self];
[invo setSelector:@selector(t:)];
NSTimer * timer = [NSTimer timerWithTimeInterval:1 invocation:invo repeats:YES];
//加入主循环池中
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
//开始循环
[timer fire];
}
}
-(void)t:(NSTimer*)n
{
//传参数 NSNumber 字典 字符串
id t = [n userInfo];
//触发的系统时间
NSData *d = n.fireDate;
}
//暂停、启动、销毁
if(btn.tag == k_link)
{
[heartTimer setFireDate:[NSDate distantFuture]]; //暂停
}
else if (btn.tag == k_link+1)
{
[heartTimer setFireDate:[NSDate distantPast]]; //启动
}
else
{
[heartTimer invalidate]; //销毁
heartTimer = nil;
}