Freeing memory used in a timer block but allocated out of it, when stopping the timer

294 views Asked by At

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); 

}
1

There are 1 answers

2
Jodocus On

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?