很多時(shí)候我們會想在多少秒以后執(zhí)行一個(gè)任務(wù)(方法),比如說 2s 后隱藏 ProgressHUD 什么的精钮,就可以使用
定時(shí)器
。
//
// ViewController.m
// 160623_小知識
//
// Created by angelen on 16/6/23.
// Copyright ? 2016年 ANGELEN. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 常見的 3 種定時(shí)器
// 第 1 種:performSelector
NSLog(@"1111");
// 3.0s 以后 執(zhí)行showNSLog: 方法,如果 withObject 不為 nil彭则,則是傳遞過去的參數(shù)
// 注意,這個(gè)方法不會影響后面代碼的執(zhí)行占遥,所以打印順序是 1111, 2222, look
[self performSelector:@selector(showNSLog) withObject:nil afterDelay:3.0];
NSLog(@"2222");
// 第 2 種:GCD
NSLog(@"3333");
// 這個(gè)是 GCD俯抖,執(zhí)行順序和上面一樣
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// code to be executed after a specified delay
NSLog(@"ok");
});
NSLog(@"4444");
// 第 3 種:NSTimer
// 如果 repeats 為 YES,那么就是沒隔 3.0s 就重復(fù)一次 showNSLog 這個(gè)方法
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(showNSLog) userInfo:nil repeats:NO];
}
- (void)showNSLog {
NSLog(@"look");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
開發(fā)常用瓦胎,記錄一下??