<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Fancy Rat Studios &#187; memory management</title>
	<atom:link href="http://fancyratstudios.com/tag/memory-management/feed/" rel="self" type="application/rss+xml" />
	<link>http://fancyratstudios.com</link>
	<description>A Fancy Rat Blog</description>
	<lastBuildDate>Mon, 15 Mar 2010 21:34:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Memory Management in Objective-C</title>
		<link>http://fancyratstudios.com/2010/02/programming/memory-management-in-objective-c/</link>
		<comments>http://fancyratstudios.com/2010/02/programming/memory-management-in-objective-c/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 18:30:56 +0000</pubDate>
		<dc:creator>Terrance</dc:creator>
				<category><![CDATA[Objective C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[alloc]]></category>
		<category><![CDATA[dealloc]]></category>
		<category><![CDATA[memory management]]></category>

		<guid isPermaLink="false">http://fancyratstudios.com/?p=211</guid>
		<description><![CDATA[Looking at memory management in Objective-C for the first time can be a little bit strange whether you have programming experience or not. Some memory seems to be auto-magically handled for you; other times you need to comb through code looking for allocations and releases. I&#8217;ll attempt in this tutorial to concisely go over key [...]]]></description>
			<content:encoded><![CDATA[<p>Looking at memory management in Objective-C for the first time can be a little bit strange whether you have programming experience or not.  Some memory seems to be auto-magically handled for you; other times you need to comb through code looking for allocations and releases.  I&#8217;ll attempt in this tutorial to concisely go over key starting points in memory management and focus on the Objective-C beginner.  One major thing I will leave out or gloss over is retain count for this tutorial, I find it&#8217;s much easier to begin without thinking about retain count and just following some more general rules.  Make sure you do eventually learn about retain count though as it can be important in programming and debugging.  Let&#8217;s get started!<br />
<span id="more-211"></span></p>
<h2>Creating, Initializing, Allocating</h2>
<p>The first major thing that jumps out to those new to Obj-C is the little plus (+) or minus (-) sign sitting in front of methods. I&#8217;ll make use of the NSNumber class throughout this tutorial since it&#8217;s simple and it can also be useful in real programming.<br />
If you look into the Apple documentation for NSNumber you&#8217;ll find both &#8220;Creating an NSNumber Object&#8221; and &#8220;Initializing an NSNumber Object&#8221;. What the heck is the difference there?  Take a look!</p>
<pre class="brush: objc; title: ;">
// These would be found as part of the interface of NSNumber
// Creating an NSNumber
+ (NSNumber *)numberWithInt:(int)value;

// Initializing an NSNumber
- (id)initWithInt:(int)value;
</pre>
<p>Hmmmm, there isn&#8217;t much difference there but those little (+/-) are very important.  First off a little bit of terminology, those methods starting with the (+) are called class methods and the ones with (-) are called instance methods.  In simple terms this means you need to have an instance of a class to be able to use the (-) instance methods.  This means that to use those initialization instance methods we have to first allocate our class.  It&#8217;s easiest to see if we look at an example.</p>
<pre class="brush: objc; title: ;">
// Use a class method to get a new NSNumber
// Using
//	+ (NSNumber *)numberWithInt:(int)value;
NSNumber *newNumber = [NSNumber numberWithInt:5];

// Calling an instance method on our new number
NSLog(@&quot;%d&quot;, [newNumber intValue]);

// Allocating and initialization of NSNumber
// Using
//	- (id)initWithInt:(int)value;
NSNumber *newAllocedInitNumber = [[NSNumber alloc] initWithInt:5]];

// Calling an instance method on our other new number
NSLog(@&quot;%d&quot;, [newAllocedInitNumber intValue]);
</pre>
<p>So we can see the difference in use here, but initially it looks like we get the same usage for both of our new numbers, the NSLog calls in both cases will print out a &#8220;5&#8243;.  So why should we care about all of this?  If this was all the code we have then our program would have a memory leak! Despicable! A memory leak in such a simple little piece of code.  That [NSNumber alloc] call is the issue here, this means that our newAllocedInitNumber is being retained; it will hang around forever. We can look at a quick fix for this and hopefully it should make a little more sense.  There&#8217;s also some nuances about our newNumber object but we&#8217;ll go over that in a little bit.</p>
<pre class="brush: objc; title: ;">
// Allocating and initialization of NSNumber
// Using
//	- (id)initWithInt:(int)value;
NSNumber *newAllocedInitNumber = [[NSNumber alloc] initWithInt:5]];

// Calling an instance method on our other new number
NSLog(@&quot;%d&quot;, [newAllocedInitNumber intValue]);

// All done with our new number, lets smash that memory leak
[newAllocedInitNumber release];
</pre>
<p>Fixed! In this case it&#8217;s really just that simple and gives us a great general rule to follow. If you alloc you must release. Make sure you&#8217;ve always got that one in the back of your brain. If you alloc you must release.  </p>
<p>Now let&#8217;s get back to the newNumber object and see what&#8217;s happening there.  There&#8217;s no memory leak for this guy. In fact there&#8217;s nothing wrong with it at all, so what is there to talk about? Autorelease.  When you create an object in this way it will be automatically released for you.  Sounds great; and it is!  For the beginner and for a lot of programs that&#8217;s all you need to know and you won&#8217;t really need to worry about manually managing your memory.  Nothing in life is free though and the same is true for auto release.  You must remember that you can&#8217;t be sure about how long any auto released object will hang around for so it might possibly sit around for awhile taking up memory before it gets released.  If you&#8217;re writing a game or some other memory intensive program this may matter to you.</p>
<h2>Dealloc to the Rescue!</h2>
<p>Now that we understand a little bit about how our memory is or isn&#8217;t being managed we can look at an another important example that you&#8217;ll be sure to come across.  You want to make a spiffy new class that holds onto an NSNumber so you can do fancy things with it at a later time.  What does that look like?  Maybe something like this.</p>
<pre class="brush: objc; title: ;">
// Declare our spiffy new class
@interface SpiffyClass : NSObject {
	NSNumber *fancyNumber_;
}
@end

// Implement our spiffy new class
@implementation SpiffyClass
- (id) init {
	// A little bit of initialization, this is generally how most of your init methods will start
	if ((self=[super init])) {
		fancyNumber_ = [[NSNumber alloc] initWithInt:111];
	}
	return self;
}

// Doing fancy things with a fancy number
- (void)fancyPants {
	NSLog(@&quot;Fancy %d pants&quot;, [fancyNumber_ intValue]);
}
@end
</pre>
<p>Alright, we have a sparkly new SpiffyClass declaration with our fancyNumber_ object and a call to our fancyPants method will result in the logged message &#8220;Fancy 111 pants&#8221;.  Everything looks fine and dandy here, let&#8217;s move on. Wait! Another memory leak is lurking here.  We were so close!  Remember our little rule, if you alloc you must release.  We&#8217;re missing our release. Let&#8217;s try again.</p>
<pre class="brush: objc; title: ;">
// . . . interface is the same

// Implement our spiffy new class
@implementation SpiffyClass
- (id) init {
	// A little bit of initialization, this is generally how most of your init methods will start
	if ((self=[super init])) {
		fancyNumber_ = [[NSNumber alloc] initWithInt:111];
	}
	return self;
}

// Doing fancy things with a fancy number
- (void)fancyPants {
	NSLog(@&quot;Fancy %d pants&quot;, [fancyNumber_ intValue]);

	// We must remember, if we alloc then we release
	[fancyNumber_ release];
}
@end
</pre>
<p>Hmmm. Not too bad, we remembered our rule. Let&#8217;s try printing our fancy pants message 2 times.  Crash, burn, blech!  What happened?  Trying to call fancyPants more than once will try to release the fancyNumber_ object more than once.  Since it&#8217;s already been released and it was only allocated once this can cause some problems. (This would be a good point to look up retain count, but I won&#8217;t go over it here).  How then do we know when to release our fancyNumber_ object?  We probably want to hold onto fancyNumber_ until SpiffyClass dies.</p>
<pre class="brush: objc; title: ;">
// . . . interface is the same
// . . . init is the same

// Ahhhh, I'm dying!
- (void)dealloc {
	[fancyNumber_ release];

	// You'll pretty much always need this
	[super dealloc];
}

// Doing fancy things with a fancy number
- (void)fancyPants {
	NSLog(@&quot;Fancy %d pants&quot;, [fancyNumber_ intValue]);
}
@end
</pre>
<p>Adding the dealloc method is what we need here.  dealloc is called automatically whenever an instance of an object gets released.  No more memory leaks, no more crashing. Fantastic!</p>
<p>Hopefully this little beginner tutorial is helpful to get you started on the road to understanding memory management in Objective-C.  Pages and pages could be written about memory management and some key topics that I skipped over include, retain count, what is super dealloc, and more about auto release and auto release pools.  In the future we&#8217;ll be covering more of these topics in depth and piece-meal so check back often.</p>
]]></content:encoded>
			<wfw:commentRss>http://fancyratstudios.com/2010/02/programming/memory-management-in-objective-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

