停止计时器时释放计时器块中使用但已分配的内存
我声明一个计时器,用一个块指定其代码(以便每 x 秒执行此代码)。
我希望计时器在用户点击按钮时启动,因此我在 IBAction 函数内创建并恢复计时器。
最后,这就是问题所在,因为块中管理的数据始终具有相同的大小,为了避免每次计时器触发时分配和释放内存,我将内存分配为块外的 __block 指针,但在块内函数(不能在本地范围之外声明它们)。
一切正常,但我想用另一个按钮停止并重新启动计时器几次,那么如何释放函数中分配的内存呢? 我想在每次点击“开始按钮”时分配它,而不是每次计时器触发时分配它,并在点击“停止按钮”时释放它。 这个代码结构可以吗? ¿做我想做的事的最好方法是什么?
这是代码:
dispatch_source_t creaTimer(uint64_t interval,uint64_t leeway, dispatch_queue_t queue, dispatch_block_t block){
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
if (timer)
{
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
dispatch_source_set_event_handler(timer, block);
}
return timer;
}
-(IBAction) begin{
__block double *array;
array = (double*) malloc (512);
timer = creaTimer(5ull * NSEC_PER_SEC, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)
,^{
//it uses the space allocated in *array;
});
dispatch_resume(timer);
}
I am declaring a timer specifying its code with a block (in order to executing this code every x seconds).
I want the timer to start when the user taps a button, so I create and resume the timer inside a function which is an IBAction.
Finally, and this is the problem, as the data managed in the block have always the same size, in order to avoiding allocating and freeing memory each time the timer fires, I allocate the memory as __block pointers out of the block, but inside the function (they can't be declared out of this local scope).
Everything works fine, but I want, with another button, to stop and restart the timer several times, so ¿how could I free the memory allocated in the function?
I want to allocate it each time the "Begin Button" is tapped, not each time the timer fires, and free it when the "Stop Button" is tapped.
¿Is it possible with this code structure? ¿What is the best way to do what I want?
This is the code:
dispatch_source_t creaTimer(uint64_t interval,uint64_t leeway, dispatch_queue_t queue, dispatch_block_t block){
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
if (timer)
{
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
dispatch_source_set_event_handler(timer, block);
}
return timer;
}
-(IBAction) begin{
__block double *array;
array = (double*) malloc (512);
timer = creaTimer(5ull * NSEC_PER_SEC, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)
,^{
//it uses the space allocated in *array;
});
dispatch_resume(timer);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是通过将“array”设置为实例变量(通过在 .h 文件中声明它)来解决吗?
还有一个问题:你真的想使用 GCD 的低级 API 吗? NSTimer 还不够吗?或者我没有正确解释你的代码?
Isn't this solved by making 'array' an instance variable (by declaring it in you .h file)?
Just another question: do you really want to use the low level API's of GCD? Won't NSTimer suffice as well? Or didn't I interpret your code right?