{"id":20468832,"url":"https://github.com/xifenglang/jkautoreleasetimer","last_synced_at":"2026-05-10T10:19:56.799Z","repository":{"id":56916026,"uuid":"86898359","full_name":"XiFengLang/JKAutoReleaseTimer","owner":"XiFengLang","description":"\u003ciOS\u003e低耦合的自释放定时器（NSTimer + GCD 定时器）","archived":false,"fork":false,"pushed_at":"2019-04-10T17:56:57.000Z","size":562,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-18T18:16:09.585Z","etag":null,"topics":["autorelease","delay","gcd","nstimer","timer"],"latest_commit_sha":null,"homepage":"","language":"Objective-C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/XiFengLang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-04-01T08:36:05.000Z","updated_at":"2019-04-10T17:56:58.000Z","dependencies_parsed_at":"2022-08-20T21:20:26.077Z","dependency_job_id":null,"html_url":"https://github.com/XiFengLang/JKAutoReleaseTimer","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/XiFengLang%2FJKAutoReleaseTimer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/XiFengLang%2FJKAutoReleaseTimer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/XiFengLang%2FJKAutoReleaseTimer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/XiFengLang%2FJKAutoReleaseTimer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/XiFengLang","download_url":"https://codeload.github.com/XiFengLang/JKAutoReleaseTimer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242031457,"owners_count":20060586,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["autorelease","delay","gcd","nstimer","timer"],"created_at":"2024-11-15T14:06:58.708Z","updated_at":"2026-05-10T10:19:56.721Z","avatar_url":"https://github.com/XiFengLang.png","language":"Objective-C","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JKAutoReleaseTimer 自释放定时器（NSTimer + GCD 定时器） #\n\n * JKNSTimerHolder 基于NSTimer封装的自释放定时器\n * JKGCDTimerHolder 基于dispatch_queue_t封装的自释放定时器\n\n### CocoaPods\n\n```C\n\nsource 'https://github.com/CocoaPods/Specs.git'\n\npod 'JKAutoReleaseTimer', '~\u003e 1.0.0'\n```\n\n\n### 先思考一个问题：在一个由导航控制器NaviVC管理的控制器VC中运行一个定时器NSTimer，target为VC(self)，重复20次，假设在第10次的时候退出VC（出栈），怎么在最短的时间内停止定时器并释放VC？ ###\n\n\n常规的NSTimer用法中, self会被强引用，必须先释放_timer才能释放self，如果_timer没能及时释放，就会出现内存泄露，这个情况在《Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法》的第52条被提到。而基于GCD的dispatch_source_set_event_handler有类似的缺点,容易强引用外部变量，引起循环引用或者内存泄露。\n\n```Object-C\n    _timer = [NSTimer scheduledTimerWithTimeInterval:second\n                                              target:self\n                                            selector:@selector(handleTimerAction:)\n                                            userInfo:nil\n                                             repeats:yesOrNo];\n                                             \n```\n![self与timer](https://github.com/XiFengLang/JKAutoReleaseTimer/blob/master/QQ20170408.png)\n\n\n## JKNSTimerHolder ##\n\n而JKNSTimerHolder则在self和timer之间增加的\"桥梁对象\"类，将self和timer解耦。timerHolder管理timer，timer强引用timerHolder，两者之间存在引用环。但是timerHolder弱引用self，一旦self被释放就会主动废除定时器已实现自释放。而外部的self同样可以主动控制timerHolder，暂停或者废除定时器，达到释放效果。对于前面提出的问题，在这就能迎刃而解,一旦控制器VC出栈，VC没有被额外的强引用就会释放，timerHolder也会自动废除定时器实现自释放。\n\n![d](https://github.com/XiFengLang/JKAutoReleaseTimer/blob/master/QQ20170407.png)\n\n```Object-C\n\n    JKNSTimerHolder * timerHolder = [[JKNSTimerHolder alloc] init];\n    \n    /// 强/弱引用都有可以\n    self.timerHolder = timerHolder;\n\n\t[timerHolder jk_startNSTimerWithTimeInterval:0.5\n                                     repeatCount:self.repeatCount\n                                   actionHandler:self\n                                          action:@selector(jk_sel:)];\n\t\n\t/// 暂停\n\t/// self.timerHolder.suspended = YES;\n\n\n\t/// 废除定时器\n\t/// [self.timerHolder jk_cancelNSTimer];\n\n```\n\nJKNSTimerHolder同时还支持Block块，写法如下：\n\n```Object-C\n\n @param seconds 时间间隔\n @param repeatCount 重复次数，repeatCount == 运行总数 -1，达到重复次数后会自动停止定时器\n @param handler 回调响应者 == handle中的tempSelf\n @param handle 回调Block\n\n\n    [timerHolder jk_startBlockTimerWithTimeInterval:0.5\n                                        repeatCount:self.repeatCount\n                                      actionHandler:self\n                                             handle:^(JKNSTimerHolder * _Nonnull jkTimer, id  _Nonnull tempSelf, NSUInteger currentCount) {\n        \n        ///  tempSelf == 传入的actionHandler,使用tempSelf不会发生循环引用\n        [(NSTimerTestVC *)tempSelf jk_sel:jkTimer];\n    }];\n\n```\n\n在这呢需要理解一个知识点，即Block对参数对象的引用，非Block对外部对象的引用。经测试，Block会在执行过程强引用参数对象，执行完就会解除强引用。这个测试过程在文章[Block与Copy](http://www.jianshu.com/p/b554e813fce1)中提到，虽然文章中提到的结论有错误，一位大兄弟在评论中指出了错误所在，但是文章中的测试代码还是很有参考价值的。上面代码中Block有个tempSelf参数，这个参数就是传入的actionHandler：self，在handleBlock中使用tempSelf不会出现循环引用，但如果仍使用self，那就可能出现循环引用，需要对self进行weak strong转换才行。\n\n\n## JKGCDTimerHolder ##\n\nJKGCDTimerHolder基于GCD的dispatch_source_set_event_handler实现，但是原理、用法都和JKNSTimerHolder一样。\n\n```Object-C\n\n    JKGCDTimerHolder * gcdTimerHolder = [[JKGCDTimerHolder alloc] init];\n    \n    /// 强/弱引用都有可以\n    self.gcdTimerHolder = gcdTimerHolder;\n    \n    [self.gcdTimerHolder jk_startGCDTimerWithTimeInterval:0.5\n                                              repeatCount:self.repeatCount\n                                            actionHandler:self\n                                                   action:@selector(gcdTimerAction)];\n\n\n\n\t/// 废除定时器\n\t/// [self.gcdTimerHolder jk_cancelGCDTimer];\n```\n\n**Block写法**\n\n```Object-C\n    [timerHolder jk_startBlockTimerWithTimeInterval:0.5\n                                        repeatCount:self.repeatCount\n                                      actionHandler:self\n                                             handle:^(JKNSTimerHolder * _Nonnull jkTimer, id  _Nonnull tempSelf, NSUInteger currentCount) {\n        \n        ///  tempSelf == 传入的actionHandler,使用tempSelf不会发生循环引用\n        [(NSTimerTestVC *)tempSelf jk_sel:jkTimer];\n    }];\n```\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxifenglang%2Fjkautoreleasetimer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxifenglang%2Fjkautoreleasetimer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxifenglang%2Fjkautoreleasetimer/lists"}