计时器的写法

 1 @interface MyPlanarCodeViewController ()
 2 //定义计时器
 3 @property (nonatomic, strong) NSTimer *timer;
 4 @end
 5   
 6 @implementation MyPlanarCodeViewController
 7 -(ApiGetCodeExcutor *)apiGetCodeExcutor{
 8     if (_apiGetCodeExcutor == nil) {
 9         _apiGetCodeExcutor = [ApiGetCodeExcutor excutor];
10     }
11     return _apiGetCodeExcutor;
12 }
13 - (void)viewDidLoad {
14     [super viewDidLoad];
15     //启动计时器
16     [self startTimer];
17 }
18 - (void)startTimer {
19     //60秒调用一次timerRepeat:方法
20     _timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerRepeat:) userInfo:nil repeats:YES];
21     [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
22     [_timer fire];
23 }
24 //重复进行的操作放到这里
25 -(void)timerRepeat:(NSTimer *)timer {
26     ApiRequestStateHandler * apiRequest = [ApiRequestStateHandler apiRequestStateHandlerOnSuccess:^(ApiExcutor *apiExcutor, BOOL *cache) {
27         if(self.apiGetCodeExcutor.status == 1){
28             [self.codeImageView sd_setImageWithURL:[NSURL URLWithString:self.apiGetCodeExcutor.imageURL] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
29                 [self hideHud];
30                 [[SDImageCache sharedImageCache] removeImageForKey:self.apiGetCodeExcutor.imageURL];
31             }];
32             self.codeImageView.userInteractionEnabled = NO;
33         }else{
34             [self hideHud];
35             [self showAlertViewWithTitle:@"请等待老师开启签到后点击二维码区域重新获取"];
36         }
37     } onFail:^(ApiExcutor *apiExcutor, NSError *error) {
38         //
39         [self hideHud];
40         [self showHint:@"网络通讯异常"];
41     }];
42     [self.apiGetCodeExcutor getQRCodeWithUserid:[CUserManager sharedManager].user.userid withCourseId:self.course.sjddid type:self.type withDeviceIdentifier:device withApiRequestStateHandler:apiRequest];
43 }
44 //销毁计时器。避免计时器一直在运行状态
45 - (void)viewDidDisappear:(BOOL)animated {
46     [_timer invalidate];
47     _timer = nil ;
48 }
49 //- (void)dealloc {
50 //    [_timer invalidate];
51 //     _timer = nil;
52 //}
53 @end
View Code

 

posted @ 2015-11-09 14:18  yelan@yelan  阅读(440)  评论(0编辑  收藏  举报