iOS實戰(zhàn)-更精準的定時器

iOS中腌巾,常用的定時器有三種:NSTimer,CADisplayLink立叛,GCD负敏。在一定基礎(chǔ)之上,做進一步探究秘蛇。

NSTimer,CADisplayLink

在使用scheduleTimerWithTimeInterval:target:selector:userInfo:repeats:方式創(chuàng)建的定時器會以默認方式添加到當前線程runloop中顶考,無需手動添加赁还。
如果有需求:點擊屏幕觸發(fā)定時器,不需要時點擊返回

@interface TestViewController ()

@property(nonatomic,strong)NSTimer *timer;

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
}

-(void)run
{
    NSLog(@"%s",__func__);
}

-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    
    NSLog(@"%s",__func__);
}

@end

經(jīng)測試驹沿,這段代碼dealloc方法不會執(zhí)行艘策,存在循環(huán)引用。因為NSTimer內(nèi)部有強指針target渊季,所以不管外部傳入的是weak還是strong朋蔫,都會將傳入的內(nèi)存地址賦值給形參target,所以不管target存儲的是weak的地址還是strong的地址却汉,NSTimer對target都是強引用驯妄,所以timer和self產(chǎn)生了循環(huán)引用。

通過GNUStep中源碼可以看出合砂,傳入的object被retain一次青扔,被timer強持有。

NSTimer
schedule:target:
init

代碼所產(chǎn)生的循環(huán)引用

timer-self循環(huán)引用

要想解決這個循環(huán)引用翩伪,使其中一個強引用變成弱引用微猖。


打破循環(huán)引用
  • 方法一:使用block創(chuàng)建方式
    block存儲在timer中,timer對block強引用缘屹,block對self是弱引用凛剥,定時器對self是弱引用。
__weak typeof(self)wself = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
  [wself run];
}];
  • 方法二
    如果使用scheduleTimerWithTimeInterval:target:方法轻姿,就要引入中間變量犁珠,將中間對象的指針置為弱指針逻炊。
@interface SSProxy : NSObject
//弱指針,打破循環(huán)引用
@property(nonatomic, weak)id target;

+(instancetype)proxyWithTarget:(id)target;

@end

@implementation SSProxy

+(instancetype)proxyWithTarget:(id)target
{
    SSProxy *proxy = [[SSProxy alloc] init];
    proxy.target = target;
    return proxy;
}
//消息轉(zhuǎn)發(fā)階段盲憎,返回值不為空嗅骄,直接給某個對象發(fā)送消息
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return self.target;
}

@end
@interface TestViewController ()

@property(nonatomic,strong)NSTimer *timer;

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[SSProxy proxyWithTarget:self] selector:@selector(run) userInfo:nil repeats:YES];
}

-(void)run
{
    NSLog(@"%s",__func__);
}

-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    
    NSLog(@"%s",__func__);
}

@end
  • 方法三:使用CADisplayLink
@interface TestViewController ()

@property(nonatomic,strong)CADisplayLink *timer;

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.timer = [CADisplayLink displayLinkWithTarget:[SSProxy proxyWithTarget:self] selector:@selector(run)];
    [self.timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

-(void)run
{
    NSLog(@"%s",__func__);
}

-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    
    NSLog(@"%s",__func__);
}

@end

存在的弊端:
1.NSTimer和CADisplayLink底層是runloop實現(xiàn)的,所以有可能并不準時饼疙,如果runloop任務(wù)過于繁重溺森,每一圈的處理就會耗時,就導致不準時窑眯。
2.對于CADisplayLink屏积,當CPU忙于其他計算,就無法保證每秒60次的頻率執(zhí)行屏幕繪制磅甩。

GCD定時器

GCD定時器直接和系統(tǒng)內(nèi)核掛鉤炊林,不依賴于runloop,相對精準卷要。

@interface TestViewController ()

@property(nonatomic,strong)dispatch_source_t timer;

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
  dispatch_queue_t queue = dispatch_get_main_queue();
    
  dispatch_source_t timer = dispatch_source_create(&_dispatch_source_type_timer, 0, 0, queue);
    
  dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
  dispatch_source_set_event_handler(timer, ^{
        NSLog(@"%@",[NSThread currentThread]);
    });
    
  dispatch_resume(timer);
    
  self.timer = timer;
}

-(void)run
{
    NSLog(@"%s",__func__);
}

-(void)dealloc
{
    NSLog(@"%s",__func__);
}

@end
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末渣聚,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子僧叉,更是在濱河造成了極大的恐慌奕枝,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瓶堕,死亡現(xiàn)場離奇詭異隘道,居然都是意外死亡,警方通過查閱死者的電腦和手機郎笆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門谭梗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宛蚓,你說我怎么就攤上這事激捏。” “怎么了苍息?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵缩幸,是天一觀的道長。 經(jīng)常有香客問我竞思,道長表谊,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任盖喷,我火速辦了婚禮爆办,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘课梳。我一直安慰自己距辆,他們只是感情好余佃,可當我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著跨算,像睡著了一般爆土。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上诸蚕,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天步势,我揣著相機與錄音,去河邊找鬼背犯。 笑死坏瘩,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的漠魏。 我是一名探鬼主播倔矾,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼柱锹!你這毒婦竟也來了哪自?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤禁熏,失蹤者是張志新(化名)和其女友劉穎提陶,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體匹层,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年锌蓄,在試婚紗的時候發(fā)現(xiàn)自己被綠了升筏。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡瘸爽,死狀恐怖您访,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情剪决,我是刑警寧澤灵汪,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站柑潦,受9級特大地震影響享言,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜渗鬼,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一览露、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧譬胎,春花似錦差牛、人聲如沸命锄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽脐恩。三九已至,卻和暖如春侦讨,著一層夾襖步出監(jiān)牢的瞬間驶冒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工搭伤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留只怎,地道東北人。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓怜俐,卻偏偏與公主長得像身堡,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子拍鲤,可洞房花燭夜當晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容