Posts Tagged ‘Objective-C Cocoa Apple’

Cocoa – NSThread And Memory Management

Thursday, April 16th, 2009

As a C/C++ developer one tends to be acutely aware of the implications of dynamically allocating memory from the heap.  In the past couple of months I had decided to expand my horizons and engage in developing some applications for Mac OS X and iPhone using the Cocoa libraries and as such, Objective-C as my implementation language.

Everything was moving quite smoothly in my single threaded application.  At a certain point it became apparent that it was time to decouple the GUI and the data collection.  I had decided to implement the data collection in a thread.  A NSThread specifically.

As I began to implement the main function of my thread I began to notice some horrible messages showing up in the XCode console:

2009-04-15 20:51:35.030 HostWatch[18804:440b] *** _NSAutoreleaseNoPool(): Object 0x20f240 of class NSCFString autoreleased with no pool in place - just leaking

Stack: (0x9711373f 0x9701fe32 0x139e7 0x1441a 0x970267ed 0x97026394 0x962b1095 0x962b0f52)

2009-04-15 20:51:35.033 HostWatch[18804:440b] *** _NSAutoreleaseNoPool(): Object 0x276530 of class NSCFData autoreleased with no pool in place - just leaking

Stack: (0x9711373f 0x9701fe32 0x97034505 0x97086a48 0x1443c 0x970267ed 0x97026394 0x962b1095 0x962b0f52)

2009-04-15 20:51:35.033 HostWatch[18804:440b] *** _NSAutoreleaseNoPool(): Object 0x276480 of class NSCFData autoreleased with no pool in place - just leaking

Stack: (0x9711373f 0x9701fe32 0x97034505 0x97086a48 0x14463 0x970267ed 0x97026394 0x962b1095 0x962b0f52)

Just leaking!!  Oh my!  My spider senses were tingling.  My heap sensitive programming sensibility in shambles!  Something had to be done.  No one wants a program that should theoretically be running for a long time (or any amount of time) haphazardly shedding dynamically allocated memory.

The solution turned out to be quite simple.  The main function of a NSThread should always be wrapped in an autorelease pool.  So, the solution in code might look similar to this:

- (void)threadMainFunc:(void *)data
{
   NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
   ...

   ...
   [autoreleasepool release];
}

Sweet relief.  All of the nasty message pointing to blatant leaking of memory had disappeared. The details of Cocoa’s requirements with respect to autorelease pools and threads can be found here:

Autorelease Pools

and more specifically on the topic of threads:

Autorelease Pools and Threads

I hope that this has been helpful for anyone who has had this sort of issue show up in their newly NSThread-ed code.  My intent is to continue posting as I encounter and solve problems in my current Cocoa development projects.



© All rights reserved.