Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using grand central dispatch inside class method causes memory leak

I get a memory leak when the view controller calls my model class method at the line where i create my gcd queue. Any ideas?

+(void)myClassMethod {
    dispatch_queue_t myQueue = dispatch_queue_create("com.mysite.page", 0); //run with leak instrument points here as culprit
    dispatch_async(myQueue, ^{});
}
like image 254
prostock Avatar asked Mar 23 '11 20:03

prostock


2 Answers

You should change it to ...

dispatch_queue_t myQueue = dispatch_queue_create("com.mysite.page", 0);
dispatch_async(myQueue, ^{});
dispatch_release(myQueue);

... you should call dispatch_release when you no longer need an access to the queue. And as myQueue is local variable, you must call it there.

Read dispatch_queue_create documentation:

Discussion

Blocks submitted to the queue are executed one at a time in FIFO order. Note, however, that blocks submitted to independent queues may be executed concurrently with respect to each other.

When your application no longer needs the dispatch queue, it should release it with the dispatch_release function. Any pending blocks submitted to a queue hold a reference to that queue, so the queue is not deallocated until all pending blocks have completed.

like image 85
zrzka Avatar answered Nov 06 '22 08:11

zrzka


The Leak tool reports where memory is allocated that no longer has any references from your code.

After that method runs, since there is nothing that has a reference to the queue you created, and dispatch_release() was never called, it's considered a leak.

like image 4
Kendall Helmstetter Gelner Avatar answered Nov 06 '22 09:11

Kendall Helmstetter Gelner