NSTimer 分别分基础篇和深入篇,深入篇会设计到NSRunloop所以现在先不详述,会在NSTimer - 2 篇里面学习。
基础篇也是非常好学习的,因为NSTimer提供的接口方法少而已很少理解和使用。
初始化 和 使用也是非常简单,例如:
_hideFlowButtonTimer = [NSTimer timerWithTimeInterval:4.0f target:self selector:@selector(hideFlowButton) userInfo:nil repeats:NO];
还可以立即触发,使用方法:
- (void)fire;
防止内存泄漏,关闭计时器:
[timer invalidate];
timer = nil;
还可以灵活地开启 、 关闭:
//页面将要进入前台,开启定时器
-(void)viewWillAppear:(BOOL)animated
{
//开启定时器
[scrollView.myTimer setFireDate:[NSDate distantPast]];
}
//页面消失,进入后台不显示该页面,关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
//关闭定时器
[scrollView.myTimer setFireDate:[NSDate distantFuture]];
}
而在参考文章 Reference - 1中提到一点没有想到的计时器和函数方法相关对象(Target)里面对象的retain关系是怎么样的,详细查看Reference - 1。
这里给出一个计时器结合UIView的动画的简单实现:
在moveFlowButton初始化定时器:
- (void)moveFlowButton
{
//洋葱头缩进到屏幕边缘定时器
_hideFlowButtonTimer = [NSTimer timerWithTimeInterval:4.0f target:self selector:@selector(hideFlowButton) userInfo:nil repeats:NO];
float durationTime = _flowButton.superview.bounds.size.width * 0.00125f ; //动画持续时间
if (_flowButton.center.x < _flowButton.superview.bounds.size.width / 2) {
[UIView animateWithDuration:durationTime animations:^{
_flowButton.center = CGPointMake(_flowButton.bounds.size.width / 2, _flowButton.center.y);
_flowMenu.center = CGPointMake(_flowMenu.bounds.size.width / 2 + _flowButton.bounds.size.width, _flowMenu.center.y - 5);
} completion:^(BOOL finished){
[_hideFlowButtonTimer fire];
}];
}
}
定时器相关的方法实现:
- (void)hideFlowButton
{
if (_flowButton.center.x < _flowButton.superview.bounds.size.width / 2) {
[UIView animateWithDuration:0.5f animations:^{
_flowButton.frame = CGRectMake(-_flowButton.bounds.size.width + 10, _flowButton.frame.origin.y, _flowButton.bounds.size.width, _flowButton.bounds.size.height);
} completion:^(BOOL finished){
_isFlowButtonDismiss = YES;
}];
}
}
参考文章:
Reference - 1 : 定时器的关闭和开启 :http://blog.csdn.net/enuola/article/details/8099461
Reference - 2 : 全面深入定时器 - target对象的retain值 、定时器的延时 、 与runloop的关系 : http://blog.csdn.net/enuola/article/details/9163051#comments