TweetFollow Us on Twitter

Developer to Developer: Thanks for the Memory-Part 2

Volume Number: 26
Issue Number: 11
Column Tag: Developer to Developer

Developer to Developer: Thanks for the Memory-Part 2

A look at how memory is managed in Objective-C

by Boisy G. Pitre

Introduction

If you followed last month's Developer to Developer column, you'll recall that we went through an introduction to memory management in Objective-C and Cocoa applications. That article was well suited to those who were new to Mac and iOS development, and touched on a number of concepts that are unique to Apple's development environment. For comparison, we also looked at how memory management is done in C and C++. Also, we touched on how Java programmers are greatly insulated from any memory considerations due to garbage collection.

This month we'll build upon the previous article and wade a little deeper into the waters of Objective-C memory management. We will start out by looking at a special subclass of NSObject that we can use to see just how our objects behave when they are created, retained, released and deallocated. We'll also take a look at the NSAutoreleasePool class, which gives us a convenient way to defer the release of an object and the return of its memory to the system. Finally, we will take Instruments, Apple's robust developer tool, for a spin.

Seeing Is believing

As we discussed last month, memory management in Objective-C consists of requesting an ownership interest in an object by retaining it, and relinquishing that ownership interest by releasing it. These operations can occur numerous times within an application for the same object. Balancing them is key to insuring that the memory that an object occupies is not left to leak while the application runs. Conversely, we must guard against the memory being returned to the system too soon, which could result in a crash, depending upon how that object is accessed later.

How convenient would it be to actually visualize this process happening in real-time? Well, it can be done, and quite readily, by subclassing NSObject and creating a new base class which overrides the retain and release methods, among others. And that's exactly what we will do. I highly recommend that you follow along by downloading the code for this month's article from the MacTech FTP source archive at ftp://ftp.mactech.com and launching the project file in Xcode. The application is made up of simple, contrived examples that are useful in illustrating the mechanics of object allocation and deallocation.

When determining what methods to override, we can consult two resources: the NSObject Class Reference (available in the Xcode's Developer Documentation, accessible from the Xcode Help menu) or the NSObject.h header file itself. Let's take the header file route and take a peek at NSObject.h directly. To do this easily from within Xcode, go to the File > Open Quicky... menu option, then type NSObject.h. It should appear in the drop down box; select it and it will be displayed in an Xcode text editor window.


Figure 1 - Opening the NSObject.h header file

The header file is composed of several sections: basic protocols, the base class, discardable content and object allocation/deallocation. For this article, we're going to focus on methods in the basic protocols and base class sections of the header file (starting at lines 11 and 63 respectively of the header file in the 10.6 SDK). Of the methods declared in the basic protocols section, let's override the following:

- (id)retain;
- (oneway void)release;
- (id)autorelease;

Similarly, let's override the following methods declared in the base class section:

- (id)init;
- (void)dealloc;

Lastly, for informational purposes, we'll override this method:

+ (id)allocWithZone:(NSZone *)zone;

There may be some questions as to the choice of methods to override. Remember, we are trying to capture the memory management operations in a way that allows us to visually confirm them as they happen. Most of the above methods are vectors for the retain count changing. By overriding these methods with methods in a subclass that (a) calls the same method in NSObject, and (b) logs the call itself and the retain count, we can see Objective-C memory management in action.

As mentioned earlier, overriding the methods requires subclassing NSObject. We'll create a new class just for the Developer to Developer column, DDObject, as a direct descendant of NSObject, so any class who inherits from DDObject will automatically benefit from the methods that we will embellish. Let's start out by looking at the code for the retain and release methods:

- (id)retain;
{
   id result = [super retain];
   NSLog(@"[%@ retain] (retainCount = %d)", [self className], [self retainCount]);
   return result;
}
- (oneway void)release;
{
   NSLog(@"[%@ release] (retainCount = %d)", [self className], [self retainCount] - 1) withLevel:TBLogLevelInfo];
   [super release];
}

Both methods mimic the return values of their original definitions in NSObject.h and use the NSLog() function to show the name of the class and the retain count. The retain method returns the retain count after the superclass' retain method is called, while the release method shows the retain count first. This ordering insures that we see the true retain count value at the appropriate place and time.

The init and dealloc methods are also points where observing the retain count can be instructive, so we'll extend these as well:

- (id)init;
{
   if (self = [super init])
   {
      NSLog(@"[%@ init] (retainCount = %d)", [self className], [self retainCount]);
   }
   
   return self;
}
- (void)dealloc;
{
   NSLog(@"[%@ dealloc]", [self className]);
   [super dealloc];
}

Even though we explicitly call retainCount in the init method, it will always print a retain count of 1. The dealloc method is called only when the retain count goes to 0; since a release call precedes this, we'll forego logging the retain count, and simply log that we are deallocating the object's memory here.

Finally, we'll override the allocWithZone: method, which will clue us in when an allocation is taking place (as we'll see shortly, the alloc method actually calls allocWithZone: with a zone of 0):

+ (id)allocWithZone:(NSZone *)zone;
{
   NSLog(@"[%@ allocWithZone:%d]", [self className], zone);
   return [super allocWithZone:zone];
}

Now that the pieces are in place, let's take a look at memexplore.m. This file contains the main() function, several test functions, and the interface and implementation for the MemObject class. This class extends the DDObject class which we just reviewed, so we would expect to see some interesting output when we run the test. Let's go ahead and do that now. First, build the memexplore target (Build > Build). Next, ensure that the Debugger Console is in focus so that the logging results can be seen (Run > Console). Finally, run the application (Run > Run). A menu appears where you can type the number of the test to perform. Let's run the allocRunRelease test by typing 1 then the return key.


Figure 2 – Output of the allocRunRelease test

The output of this test clearly shows the steps in which our MemObject comes to life, runs, then is finally released. As expected, the init method shows that the retain count is 1. The run method is then called, and finally the release method. Recall that this method decrements the retain count by 1; this is confirmed by the retain count falling to 0, and the dealloc method being implicitly called after that. Just to be convincing that the retain count can go higher, the allocRunReleaseMultiple test performs a retain after allocating and initializing the MemObject object, as well as an extra release. The net effect is the same: the object's dealloc method is called when the retain count falls to 0. Go ahead and run this test as well.


Figure 3 - Output of the allocRunReleaseMultiple test

One might conclude that the "hands-on" memory management aspect of Objective-C is a bit laborious. After all, we not only explicitly allocate and initialize an object, we must also take care to properly release it. Not releasing an object after we are done with it denies the use of that memory elsewhere; if an application doesn't release an object properly, it will stay around until the application quits, which could be a short time or a long time. Even though current systems contain gigabytes of memory and can accommodate a bit of sloppy memory management, it is considered bad programming practice to tolerate memory leaks. On mobile devices such as the iPhone and iPad where resources are limited, it is even more critical to wipe out these types of memory leaks.

Swimming In The NSAutoreleasePool

As we discussed, balancing retains with releases insures that we avoid memory leaks or crashes. It is a disciplined approach, and forces us to think about the lifetimes of our objects. However, Cocoa gives us a bit of a reprieve from the tedium of retain count management. We can make things a little easier for ourselves by conveniently deferring the return of an object's memory to the system using a special type of class provided by the Cocoa framework: NSAutoreleasePool.

An autorelease pool acts as a sort of dumping site for objects; upon receiving an object, the pool dutifully records a reference to the memory location of objects for later releasing. Any object can be relegated to the autorelease pool by having the autorelease message sent to it:

   SomeObject *s = [[[SomeObject alloc] init] autorelease];

The autorelease message allows us to pass complete responsibility of releasing the object to the NSAutoreleasePool. By doing this, we essentially wash our hands of further worry about the lifetime of the object and the memory that it is taking up. In the above code fragment, the object s receives the autorelease message after the alloc and init messages; subsequent to that, we can use the object as needed but should not send the release message to the object. That will be performed by the autorelease pool at a later time.

Exactly where autorelease pools are created depends upon the context in which you are writing your program. In Cocoa applications, an autorelease pool is created for you automatically, so you don't have to concern yourself with its creation. However, if you are using threads, you will need to create and manage your own autorelease pool for that thread. And in the case of a command line based program such as memexplore, it is necessary to create an autorelease pool as well.

Autorelease pools can be created many times, with the most recent pool being the one that receives any objects that receive the autorelease message. In essence, autorelease pools are stacked as they are created. When the topmost autorelease pool is destroyed, the next autorelease pool will receive autoreleased objects. Destroying an autorelease pool is similar to destroying any object: sending a release message to the pool will cause it to in turn send release messages to all objects that it holds, and finally the pool itself is deallocated. A slight twist on this is that since the release of Objective-C 2.0 and garbage collection, the drain message is the desired message to send to an autorelease pool instead. This message performs the same function as the release message, but does additional work in a garbage collected environment. For our code, we'll use the drain message when releasing our pools.

Can we peek into an autorelease pool? We certainly can, thanks to the NSDebug.h header file's NSAutoreleasePoolDebugging category. The showPool message, when sent to an autorelease pool object, will display the contents of all pools in the pool stack to the standard error path. We use this debugging method in several of our test programs to illustrate what the pool looks like just before it is drained. To illustrate this, run test 1 (allocRunRelease) then test 5 (allocRunReleaseWithPoolOverRetain). The final output will look like this:

==== top of stack ================
  0x100110b00 (NSCFString)
  0x100110ae0 (NSCFString)
  0x100110920 (MemObject)
  0x100110a70 (NSCFString)
  0x100110a50 (NSCFString)
  0x100110a30 (NSCFString)
==== top of pool, 6 objects ================
  0x1001109b0 (NSCFString)
  0x1001109e0 (NSCFString)
  0x100110990 (NSCFString)
  0x1001108b0 (NSCFString)
  0x100110070 (NSCFString)
==== top of pool, 5 objects ================

The pool appearing on the very top of the stack was created in the allocRunReleaseWithPoolOverRetain() function and has 6 objects, including a MemObject which we overretained and is just leaking. The next pool was created in the main() function has 5 objects. You may be wondering what is going on with all of the NSCFString objects in the autorelease pool. Those are the various string literals which appear in the NSLog() functions that have been executed during the program's run. As objects themselves, these strings require memory management, and they are automatically added to the autorelease pool when initialized.

Pool Hazards

As convenient as autorelease pools are, they must be used with care. The same problems that we discussed last month (overretaining/underreleasing or overreleasing/

underretaining) can still lead to memory leaks or crashes. A common mistake that many beginning programmers make is to send a release message to an object after it has been sent an autorelease message. The net effect of that transgression is that the object will end up being overreleased, and a crash is likely. The allocRunReleaseWithPoolOverRelease test illustrates this poignantly.

   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSLog(@"- allocRunReleaseWithPoolOverRelease -");
   MemObject *s1 = [[[MemObject alloc] init] autorelease];
   [s1 run];
   [s1 release];
   NSLog(@"----------------");
   [NSAutoreleasePool showPools];
   [pool drain];

Note that the autorelease message is sent to the s1 object upon creation, then a release message follows. It is at that point which the object's retain count goes to 0 and its dealloc method is called. Since its reference is also in the autorelease pool, the simple act of sending the showPools method is enough to trigger an access exception and crash the program.

Another interesting hazard is having no autorelease pool at all. Without an autorelease pool, objects sent an autorelease message (including NSCFString string literals that we saw above) have nowhere to go, and just leak all over the place. If you ever see a message like this coming from your application:

*** __NSAutoreleaseNoPool(): Object 0x100110770 of class NSCFString autoreleased with no pool in place - just leaking

then you know that somewhere, an autorelease pool is needed but doesn't exist. This most commonly happens when using threads and failing to create an autorelease pool. As a rule, your thread's entry point method should create an autorelease pool at the beginning, then drain the pool at the end.

Inspecting Memory Leaks With Instruments

Apple's Instruments is part of the Xcode development suite, and is a powerful tool for strengthening and bulletproofing your applications in a number of areas. When it comes to memory usage and management, it is particularly useful, and has handy two templates that are a must: Allocations and Leaks. The former template shows you exactly what objects and how many are being allocated by your application. The latter gives you insight into where your application may be leaking memory.

Typically, Instruments can be invoked from within Xcode's Run menu. Given that our application is a windowless application whose input and output appear on the console, we'll start Instruments from the Finder and then attach to the running process.

Before starting Instruments, go ahead and run the memexplore program from within Xcode. Now let's start Instruments by navigating to the /Developer/Applications folder in the Finder and double-click the Instruments icon. You will see a window with a drop-down sheet asking for the template to use. Select the Leaks template and click the Choose button.


Figure 4 - Selecting the Leaks template from Instruments

With the template chosen, you will see the main Instruments window with both the Allocations and Leaks templates shown. Since our application is running, we can attach to it from the Choose Target button and selecting the Attach to Process menu item, then navigate the list of running processes until we find memexplore. After memexplore has been selected, click the Record button in the toolbar. This starts the process of recording all object allocations as well as the leak detection procedure.


Figure 5 - Selecting the memexplore process from Instruments

With Instruments recording the memexplore application, switch to the Xcode console and select test 5 (allocRunReleasePoolWithPoolOverRetain). This test purposely performs an extra retain to the object so that it will leak. After the test is run, switch back to Instruments and click on the Leaks template header on the left side of the window. Within a a short time, the leaked object name should appear, along with the address and size. Clicking the third button of the view group in the toolbar will reveal the extended detail including the stack trace where the leak occurred. As we can see in the stack trace, the DDObject's allocWithZone: method is where the leak originated.


Figure 6 - Instruments showing the memory leak in memexplore

Summary

As we have seen, mismanaging an object's lifetime through its retain count can have ramifications for the health of your applications. Autorelease pools give us some convenience but even so, we must still be vigilant when balancing our retains and releases. Crashes are often caused by objects being released prematurely, and leaks are the result of retaining an object beyond its lifetime. It's times like these when Apple's Instruments can pinpoint the exact spot where the leak occurred, and we can take corrective action. For those of you who have started delving into Objective-C, these articles and the accompanying code should give you a basis for understanding memory management as well as a springboard to further experimentation.

Bibliography and References

Apple. Instruments User Guide. http://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/InstrumentsUserGuide.pdf

CocoaDev. DebuggingAutorelease.

http://www.cocoadev.com/index.pl?DebuggingAutorelease


Boisy G. Pitre lives in Southwest Louisiana and is the lead developer at Tee-Boy where he also consults on Mac and iOS projects with a variety of clients. He holds a Master of Science in Computer Science from the University of Louisiana at Lafayette. Besides Mac programming, his hobbies and interests include retro-computing, ham radio, vending machine and arcade game restoration, and playing Cajun music. You can reach him at boisy@tee-boy.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more

Jobs Board

IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.