Search code examples
garbage-collectionobjective-c++

Leak Observed with NSThread


While we are developing some application in XCode4 for IOS, we have stumbled upon a strange problem:

In an NSThread, we are periodically updating a GUI element(an image) in an infinite loop. In order to update it, we have created a background thread in the loop and the update operation is handled for every 0.1 seconds. On the other hand, when we looked at the Profile View, a small amount of memory (a constant 10kb) was leaking with a period of 10 seconds.

Then we just switched to performSelectorOnMainThread for the component update operation inside the infinite loop in NSThread and the leak just disappeared.

I wonder if this is a design mistake which must be avoided and if there are any other basic pitfalls related to the garbage collector.

Thanks in advance.


Solution

  • This is surely unrelated to any sort of GC. Objective-C on iOS has no garbage collection.

    Also, yes, this is a huge design mistake. A background thread, in which there's an infinite loop, in which there are frequent calls to the main thread, huh...

    Better stick the update to the run loop, call UIKit only from the main thread, use GCD if you really need to call that method periodically (although probably you don't actually need it and this should be redesigned as well, but it's hard to tell without some context.)

    Also don't forget to create an autorelease pool for every thread you dispatch, because by default, they are not handled automatically (not even under ARC).