UISB 定时器

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    //定义一个定时器对象
    //可以在每个固定时间发送消息
    //调用此消息来调用相应的时间函数
    //通过此函数可以在固定时间段来完成一个根据时间间隔的任务
    NSTimer* _timerView ;
    
}

//定时器的属性对象 对外使用
@property (retain,nonatomic) NSTimer* timeView;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end


@implementation ViewController


//属性和成员变量的同步
@synthesize timeView= _timerView;


- (void)viewDidLoad {
    [super viewDidLoad];
    //启动定时器
    
    UIButton* btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame=CGRectMake(100, 100, 80, 40);
    [btn setTitle:@"定时器启动" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
   
    [self.view addSubview:btn];
    //停止定时器
    UIButton* btnStop= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnStop.frame=CGRectMake(100, 200, 80, 40);
    
    [btnStop setTitle:@"停止定时器" forState:UIControlStateNormal];
    [btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnStop];
    UIView* view=[[UIView alloc]init];
    view.frame=CGRectMake(0, 0, 80, 80);
    view.backgroundColor=[UIColor orangeColor];
    [self.view addSubview:view];
    //设置view的标签值
    //通过父亲视图对象以及view的标签值获得相应的视图对象
    
    
    view.tag=101;
    
    
    
   
}
-(void)pressStart
{
    //NSTime 的类方法创建一个定时器并且启动定时器
    //P1:每隔多长时间调用定时器函数 以秒为单位
    //P2: 表示实现定时器函数的对象
    //P3: 定时器函数对象
    //P4: 可以穿入定时器函数中一个参数
    //P5: 定时器是否重复操作 YES 重复调用定时器  NO 只完成一次函数调用
    //返回值为一个新建好的定时器对象
    
    _timerView=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer:) userInfo:@"小明" repeats:YES];
    
    
}
//定时器函数
//可以将定时器本身作为参数穿入
-(void)updateTimer:(NSTimer*) timer
{
    NSLog(@"test name=%@",timer.userInfo);
    UIView* view =[self.view viewWithTag:101];
    view.frame=CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5,80,80);
    
}
//按下停止定时器
-(void)pressStop
{
    if(_timerView!=nil){
        [_timerView invalidate];
        
    }
}


@end
原文地址:https://www.cnblogs.com/zhangqing979797/p/13659212.html