<?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>Blog Pav Blog &#187; Programming</title>
	<atom:link href="http://www.pavley.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.pavley.com</link>
	<description>“A great leap in the dark” – Thomas Hobbes</description>
	<lastBuildDate>Thu, 05 Jan 2012 05:02:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>ARC Memory Management in iOS 5 and Cocos2d-iPhone 2.0</title>
		<link>http://www.pavley.com/2012/01/04/arc-memory-management-in-ios-5-and-cocos2d-iphone-2-0/</link>
		<comments>http://www.pavley.com/2012/01/04/arc-memory-management-in-ios-5-and-cocos2d-iphone-2-0/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 05:02:05 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ARC]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[iOS 5]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Xcode 4]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=520</guid>
		<description><![CDATA[My rewrite of Dungeonators is crawling along at a glacial pace. Mostly because I can only work a couple of hours a week on the project. But the iOS 5 way to manage memory with ARC (automated reference counting) is making the process far less painful than it was the first time I wrote my [...]]]></description>
			<content:encoded><![CDATA[<p>My rewrite of Dungeonators is crawling along at a glacial pace. Mostly because I can only work a couple of hours a week on the project. But the iOS 5 way to manage memory with ARC (<a href="http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html#//apple_ref/doc/uid/TP40011226">automated reference counting</a>) is making the process far less painful than it was the first time I wrote my game. ARC uses annotations and some new key words to manage memory on your behalf. It works very well if you&#8217;re doing simple client-side game development and don&#8217;t have to worry about backward compatibility with iOS 4.</p>
<p>Here is an example of how ARC changes your life for the better&#8230;</p>
<p>In the old days you would declare out your ivars, declare your properties, then synthesize and map them together, and release them in a dealloc method. This little design pattern required 4 repetitive lines of code for every ivar (instance variable) and engendered flamewars about  coding style and where underscore should go (if you thought it was necessary to distinguish an ivar name from a property name).</p>
<p>Pre-ARC Entity.h</p>
<pre class="brush: c++">#import "cocos2d.h"
@interface Entity : CCSprite {
BOOL isActive_;
NSString * name_;
}
@property (nonatomic) BOOL isActive;
@property (nonatomic, copy) NSString * name;
@end</pre>
<p>Pre-ARC Entity.m</p>
<pre class="brush: c++">#import "Entity.h"
@implementation Entity
@synthesize isActive = isActive_;
@synthesize name = name_;
- (id) init {
  self = [super init];
  if (self) {
    isActive_ = YES;
    name_ = @"Fang";
  }
  return self;
}
- (void) dealloc {
  [name_ release];
  name_ = nil;
  [super dealloc];
}</pre>
<p>In this new modern era of automated reference counting I just declare properties, I don&#8217;t worry about accessing the ivars directly, and I don&#8217;t write my own dealloc. It&#8217;s a lot less code in a complex game where characters and objects have dozens of properties.</p>
<p>Post-ARC Entity.h</p>
<pre class="brush: c++">#import "cocos2d.h"
@interface Entity : CCSprite
@property (nonatomic) BOOL isActive;
@property (nonatomic, strong) NSString * name;
@end</pre>
<p>Post-ARC Entity.m</p>
<pre class="brush: c++">#import "Entity.h"
@implementation Entity
@synthesize isActive;
@synthesize name;
- (id) init {
  self = [super init];
  if (self) {
    isActive = YES;
    name = @"Fang";
  }
  return self;
}</pre>
<p>To get Cocos2d-iPhone to work with ARC was really easy: I just replace the NSAutoreleasePool object in main.m with the new ARC friendly @autoreleasepool annotation. (I might not have had to do this but it&#8217;s supposedly more efficient.)</p>
<pre class="brush: c++">int main(int argc, char *argv[]) {
//    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//    int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
//    [pool release];
//    return retVal;
  int retVal;
  @autoreleasepool {
    retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
  }
  return retVal;
}</pre>
<p>The downside, as I stated above, is that your app will only run on iPhones, iPads, and iPods running iOS 5 and you need to use Cocos2d-iPhone 2.0. But I think that&#8217;s a fair tradeoff. Backward compatibility is a killer of the artistic soul and should be avoided where possible. <em>To Err is human, but to upgrade is divine</em> <img src='http://www.pavley.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Check out <a href="http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1">Ray Wenderlich&#8217;s excellent ARC tutorial</a> for all the gritty details!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2012/01/04/arc-memory-management-in-ios-5-and-cocos2d-iphone-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sprite Playground</title>
		<link>http://www.pavley.com/2011/12/02/sprite-playground/</link>
		<comments>http://www.pavley.com/2011/12/02/sprite-playground/#comments</comments>
		<pubDate>Sat, 03 Dec 2011 04:37:29 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Sprite]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=483</guid>
		<description><![CDATA[I wrote a little Cocos2d-iPhone test app and committed the project to GitHub. (Like every dutiful hacker should.) You&#8217;re welcome to download the project and fool around with the code. My goal was to figure out how to create a composite sprite, make sure it could respond to touches, and rotate and move it round [...]]]></description>
			<content:encoded><![CDATA[<p><iframe width="560" height="315" src="http://www.youtube.com/embed/DfsTaC5dkJc" frameborder="0" allowfullscreen></iframe></p>
<p>I wrote a little Cocos2d-iPhone test app and committed the <a href="https://github.com/jpavley/SpritePlayground">project</a> to GitHub. (Like every dutiful hacker should.) You&#8217;re welcome to download the project and fool around with the code.</p>
<p>My goal was to figure out how to create a composite sprite, make sure it could respond to touches, and rotate and move it round the screen. With a little trial and error I got it working. Here&#8217;s how I did the hard parts:</p>
<p>I created a sprite from an PNG file and got it&#8217;s dimensions:</p>
<pre class="brush: c++">CCSprite * cocos2dGuy = [CCSprite spriteWithFile:@"avatar_n1_tang.png"];
CGSize spriteSize = cocos2dGuy.textureRect.size;</pre>
<p>Then I created a CCNode to be the parent of my sprite sandwich. (I originally tried to use my cocos2dGuy CCSprite as the parent but Cocos2d stacks added on top of partent nodes and I wanted the particle effect under the cocos2dGuy not on top of him.) I set the size of the CCNode to the dimensions of the cocos2dGuy so that when you touch the CCNode it responds as if you&#8217;re touching the image. Then I add the CCNode to the layer. It&#8217;s also important to set the CCNode&#8217;s anchorPoint to the center (0.5, 0.5) as it&#8217;s default is bottom-left. CCSprite default to center anchorPoints and I want my CCNode to act like a proper sprite.</p>
<pre class="brush: c++">CCNode * composite = [CCNode node];
composite.anchorPoint = ccp(0.5,0.5);
composite.contentSize = spriteSize;
composite.position = centerPt;
[self addChild:composite z:0 tag:kCompositeTag];</pre>
<p>Next I added the cocos2dGuy sprite to the center of the composite CCNode. These two entities are now both the same size and stacked on top of each other. (It&#8217;s probably not necessary for me to set the cocos2dGuy&#8217;s anchorPoint and so I&#8217;ll remove that line of code down the road.)</p>
<pre class="brush: c++">cocos2dGuy.anchorPoint = ccp(0.5, 0.5);
CGSize compositeSize = composite.contentSize;
CGPoint compositeCenterPt = ccp(compositeSize.width/2,compositeSize.height/2);
cocos2dGuy.position = compositeCenterPt;
[composite addChild:cocos2dGuy z:1 tag:1];</pre>
<p>Finally I created the custom CCParticleSystem from a <a href="http://particledesigner.71squared.com/">Particle Designer</a> file and added it to the composite CCNode but at a lower Z value show it shows up under the cocos2dGuy sprite. See how I had to set the position and the anchorPoint to ensure everything lined up.</p>
<pre class="brush: c++">CCParticleSystem * fx = [ARCH_OPTIMAL_PARTICLE_SYSTEM particleWithFile:@"fireball_small_fast_green.plist"];
fx.anchorPoint = ccp(0.5, 0.5);
fx.position = compositeCenterPt;
fx.duration = kCCParticleDurationInfinity;
fx.scale = 2.0f;
fx.autoRemoveOnFinish = YES;
[composite addChild:fx z:0 tag:1];</pre>
<p>Movement and animation are easy in the world of Cocos2d. I really like the visual effect of  CCEaseExponentialInOut. It has a nice punch.</p>
<p>Handling touches are bit harder. I had to remember to set  self.isTouchEnabled = YES in my init method and override both registerWithTouchDispatcher and ccTouchBegan. The key bit of code for responding to a touch is isTouchForMe:</p>
<pre class="brush: c++">bool hit = false;
for(CCNode * node in [self children]) {
    if(node.tag == kCompositeTag) {
         hit = CGRectContainsPoint([node boundingBox], touchLocation);
         if (hit) {
             [self hiliteSprite:(CCSprite *)node];
         } else {
             [self turnSprite:(CCSprite *)node andAttackPoint:touchLocation];
         }
    }
}</pre>
<p>The main thing here is to give each touchable node a unique tag and test each node in the layer for that tag. If you touch the sprite he inflates for a moment. If you touch an empty part of the screen the sprite turns and launches himself at your finger. Ouch!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/12/02/sprite-playground/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cocos2d-iPhone Sprite Rotation to an Arbitrary Point</title>
		<link>http://www.pavley.com/2011/11/28/cocos2d-iphone-sprite-rotation-to-an-arbitrary-point/</link>
		<comments>http://www.pavley.com/2011/11/28/cocos2d-iphone-sprite-rotation-to-an-arbitrary-point/#comments</comments>
		<pubDate>Tue, 29 Nov 2011 04:15:05 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Sprite]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=474</guid>
		<description><![CDATA[I had some time during the Thanksgiving weekend to work on Dungeonators. I&#8217;m hoping to get an upgrade out to the App Store soon. One thing I needed //TODO: is refactor my rather poor implementation of rotating a sprite to face another sprite. My original code worked ok, in a roundabout way, but was ugly [...]]]></description>
			<content:encoded><![CDATA[<p>I had some time during the Thanksgiving weekend to work on <a href="http://itunes.apple.com/us/app/dungeonators/id463233923?mt=8">Dungeonators</a>. I&#8217;m hoping to get an upgrade out to the App Store soon. One thing I needed //TODO: is refactor my rather poor implementation of rotating a sprite to face another sprite. My original code worked ok, in a roundabout way, but was ugly and mysterious.</p>
<p>(My iPhone game is full of ugly mysterious code: As I implement my ideas in code I first focus on getting it to work. Then, if I have time I go back and fix it to work cleanly. Generally <em>cleanly</em> means boiling the code down to the fewest number of lines possible, making it as functional as possible, and using functions from the operating system or open source code libraries as much as possible.)</p>
<p>I won&#8217;t show you my original sprite rotation implementation. Some things are too gross even for the Internet. Let&#8217;s just say it was written as if I was trying to remember high school trigonometry by trial and error.</p>
<p>Instead below is the final implementation, useful to any <a href="http://www.cocos2d-iphone.org/">Cocos2d-iPhone</a> programmer who wants a sprite to rotate to face an opponent at any point on the screen:</p>
<pre class="brush: c++">- (void) rotateSourceSprite:(CCSprite *)sourceSprite toFaceTargetSprite:(CCSprite *)targetSprite {

    // Calculation
    CGPoint difference = ccpSub(sourceSprite.position, targetSprite.position);
    CGFloat rotationRadians = ccpToAngle(difference);
    CGFloat rotationDegrees = -CC_RADIANS_TO_DEGREES(rotationRadians);
    rotationDegrees += 90.0f;
    CGFloat rotateByDegrees = rotationDegrees - sourceSprite.rotation;

    // animation
    CCRotateBy * turnBy = [CCRotateBy actionWithDuration:0.5f angle:rotateByDegrees];
    CCEaseIn * ease = [CCEaseIn actionWithAction:turnBy rate:4];
    [sourceSprite runAction:ease];
}</pre>
<p class="brush: c++">And here&#8217;s how it works, just incase you&#8217;re curious&#8230;</p>
<ul>
<li>The method takes a source sprite and as target sprite as parameters. After it runs it will rotate the source to face the target.</li>
<li>The calculation part uses Cocos2d helper functions and macros (ccpSub, ccpToAngle, and CC_RADIANS_DEGREES) to figure the maths. In my original implementation I had written my own versions. Using the Cocos2d API makes my code easier to read and perhaps faster.</li>
<li>The maths work like this: Create a vector out of the distance between to points. Convert the vector to an angle. Convert the angle from radians to degrees and negate it*. Add 90 degrees to the angle to get the proper orientation. (The +=90.0f value is game specific: My sprites are rotated 90 degrees to start with.) Subtract the penultimate result of the calculation from the current rotation property (angle) of the source sprite to get the final result (the amount to rotate by).</li>
<li>The animation, which could easily be factored out into a method of its own, uses Cocos2d&#8217;s CCRotateBy and CCEaseIn to turn the source sprite to face the target in half a second. This part didn&#8217;t change from the original code. I didn&#8217;t factor it out because in my game I always use these two pieces together. I don&#8217;t like to do too much work in the abstract because I usually end up making my code too complex.</li>
</ul>
<p>* The need to negate the value produced by CC_RADIANS_DEGREES is a bit of a mystery to me. If I don&#8217;t do it my sprite ends up facing in the opposite direction.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/11/28/cocos2d-iphone-sprite-rotation-to-an-arbitrary-point/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dungeonators iPhone Game Released in the App Store!</title>
		<link>http://www.pavley.com/2011/10/13/dungeonators-iphone-game-released-in-the-app-store/</link>
		<comments>http://www.pavley.com/2011/10/13/dungeonators-iphone-game-released-in-the-app-store/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 03:34:50 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Development]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=454</guid>
		<description><![CDATA[Writing a real game, from scratch, in Objective-C, with original Art and sound effects, took a heck of a lot longer than I imagined. Even with the help of the Cocos2d-iPhone framework! You can find it here: http://bit.ly/rkZvCJ Here&#8217;s what the sprite atlas looks like (formatted by Zwoptex) &#8230; And here are some stats: 28 sounds [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.pavley.com/wp-content/uploads/2011/10/dunfirstkill.png"><img class="aligncenter size-medium wp-image-455" title="Meet the Dungeonators" src="http://www.pavley.com/wp-content/uploads/2011/10/dunfirstkill-300x300.png" alt="" width="300" height="300" /></a>Writing a real game, from scratch, in Objective-C, with original Art and sound effects, took a heck of a lot longer than I imagined. Even with the help of the Cocos2d-iPhone framework!</p>
<p>You can find it here: <a href="http://bit.ly/rkZvCJ">http://bit.ly/rkZvCJ</a></p>
<p>Here&#8217;s what the sprite atlas looks like (formatted by <a href="http://zwoptexapp.com/">Zwoptex</a>) &#8230;</p>
<p><a href="http://www.pavley.com/wp-content/uploads/2011/10/dungeonators_atlas3.png"><img class="aligncenter size-medium wp-image-457" title="dungeonators_atlas3" src="http://www.pavley.com/wp-content/uploads/2011/10/dungeonators_atlas3-300x300.png" alt="" width="300" height="300" /></a>And here are some stats:</p>
<ul>
<li>28 sounds files (converted to 22K CAF format) &#8211; edited with <a href="http://audacity.sourceforge.net/">Audacity</a> or bought from <a href="http://www.soundrangers.com/">SoundRangers</a></li>
<li>3 bitmap fonts &#8211; edited with <a href="slick.cokeandcode.com/demos/hiero.jnlp">Hiero Font Tool</a></li>
<li>24 custom Objective-C classes based on the <a href="http://www.cocos2d-iphone.org/">Cocos2d-iPhone</a> framework</li>
<li>30 plist files &#8211; edited with <a href="http://www.fatcatsoftware.com/plisteditpro/">PlistEdit Pro</a></li>
<li>5 particle effect files &#8211; edited with <a href="http://particledesigner.71squared.com/">ParticleDesigner</a></li>
<li>348 custom images &#8211; created with Adobe <a href="http://www.adobe.com/products/fireworks.html">Fireworks</a> (not Photoshop!)</li>
</ul>
<p>Now you know all my secrets!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/10/13/dungeonators-iphone-game-released-in-the-app-store/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fraction: Does not recognize selector forward::</title>
		<link>http://www.pavley.com/2011/07/23/fraction-does-not-recognize-selector-forward/</link>
		<comments>http://www.pavley.com/2011/07/23/fraction-does-not-recognize-selector-forward/#comments</comments>
		<pubDate>Sat, 23 Jul 2011 16:30:04 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Nerd Fun]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=396</guid>
		<description><![CDATA[If you&#8217;re crazy like me you love reading really good primers on programming. Not just to learn about a particular language but to enjoy well written technical prose. (Yeah, I said I was crazy). Yesterday, I started reading Stephen Kochan&#8217;s classic Programming in Objective-C (original edition), which was published in 2003. What I like about [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re crazy like me you love reading really good primers on programming. Not just to learn about a particular language but to enjoy well written technical prose. (Yeah, I said I was crazy). Yesterday, I started reading Stephen Kochan&#8217;s classic <a href="http://www.amazon.com/Programming-Objective-C-Stephen-Kochan/dp/0672325861">Programming in Objective-C (original edition)</a>, which was published in 2003. What I like about <a href="http://classroomm.com/objective-c/index.php">Kochan</a> is how he presents the principles of object oriented programming and the syntax of Objective-C without jumping into writing a fancy application. Kochan takes his time to teach each component of the language and the paradigm instead of glossing over the details to quickly get to a utilitarian example.</p>
<p>If you want to understand how a great tutorial is written you can&#8217;t do much better than Kochan. Unfortunately a lot has changed in the Mac OS X world since 2003 and the code examples don&#8217;t compile. The code is fine. It&#8217;s the default compiler setting that have changed. A Google search on the compile error brought me to a a good <a href="https://discussions.apple.com/thread/2140085?start=15&amp;tstart=0">discussion</a> on the problem on Apple&#8217;s developer support forum. You have to dig but the fix is pretty trivial if you know gcc complier flags (which the target audience of a primer are unlikely to know).</p>
<p>My advice to students and armchair time travelers who want to follow the original book is to resist the urge to change the source code examples to inherit from NSObject. Instead use the <em>-arch i386 flag</em> as suggested by very helpful forum user <a href="https://discussions.apple.com/people/Kostantino">Constantino</a>. (Mysteriously Constantino&#8217;s forum name is spelled with a K.)</p>
<p>In other words instead of compiling with</p>
<blockquote>
<pre>gcc <em>ClassName.m</em> -o <em>ProgramName</em> -l objc</pre>
</blockquote>
<p>use</p>
<blockquote>
<pre>gcc -arch i386 -o <em>ProgramName</em> <em>ClassName.m</em> -lobjc</pre>
</blockquote>
<p>To compile and run the OOP first example of the book from the terminal you can copy and paste the following 2 lines:</p>
<pre>gcc -arch i386 -o Fraction Fraction.m -lobjc</pre>
<pre>./Fraction</pre>
<p>And for the full experience, don&#8217;t use Xcode or a fancy text editor. VI is fun, old school, and Apple&#8217;s Terminal a joy to work with.</p>
<p><em>Notes:</em></p>
<ul>
<li>There is a third edition that probably addressed this issue. But what fun is that if you only have the original edition? I would love to set up an old Mac with a vintage version of the Mac OS X to really immerse  myself in the experience!</li>
<li>There is also also a <a href="http://books.google.com/books?printsec=frontcover&amp;id=WM7aTX2hr7EC#v=onepage&amp;q&amp;f=false">Programming in Objective-C 2.0 3rd Edition</a> which looks like a lot of fun to read and which might actually be more relevant if you have an urgent need to write a modern Mac application.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/07/23/fraction-does-not-recognize-selector-forward/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hey It&#8217;s Easier Than You Think (Xcode 4 and Subversion)</title>
		<link>http://www.pavley.com/2011/06/12/hey-its-easier-than-you-think-xcode-4-and-subversion/</link>
		<comments>http://www.pavley.com/2011/06/12/hey-its-easier-than-you-think-xcode-4-and-subversion/#comments</comments>
		<pubDate>Sun, 12 Jun 2011 14:42:07 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Source Code Control]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[Xcode 4]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=376</guid>
		<description><![CDATA[I love how the new Xcode 4 shows you code changes side-by-side with it&#8217;s version editor view. But I had a little problem. I&#8217;m a subversion fan. Yes, I know, totally not cool. I keep this flaw a secret and I don&#8217;t force my preference on my co-workers nor do I tweet about it. I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>I love how the new Xcode 4 shows you <a href="http://developer.apple.com/library/mac/#documentation/ToolsLanguages/Conceptual/Xcode4UserGuide/SCM/SCM.html">code changes side-by-side</a> with it&#8217;s version editor view. But I had a little problem. I&#8217;m a subversion fan. Yes, I know, totally not cool. I keep this flaw a secret and I don&#8217;t force my preference on my co-workers nor do I tweet about it. I&#8217;m sure with years of therapy and the love and support of my family I&#8217;ll get over it.</p>
<p>But in the meantime I&#8217;m working on an iPhone game and I have a free subversion repository from my <a href="http://dreamhost.com">ISP</a>. I want to continue to use this fee repository even though Apple gently nudges you to GIT with Xcode 4.</p>
<p>I&#8217;m stubborn. I tried GIT and it&#8217;s not doing anything for me. My change control needs are small. The functionality that makes <a href="http://stackoverflow.com/questions/871/why-is-git-better-than-subversion">GIT great</a> is way more than I need: I&#8217;m not working on a large team with a complex build system that has to commit changes with the finesse of a <a href="http://www.imdb.com/title/tt1155592/">tightrope walker</a>.</p>
<p>Today I went back to subversion and my free repository when I had to update my iPhone to the release candidate 3 of the <a href="http://www.cocos2d-iphone.org/">Cocos2d framework</a> (which is host on Github BTW). Back when Xcode 4 was release I just could get Subversion and Xcode to play nice. But being stubborn, I tried again and to my surprise succeeded.</p>
<p>I don&#8217;t think Apple changed much. I think I was just impatient and misinformed. There is a lot of silliness about how to set up Xcode 4 to work with a Subversion repository on the Internets. What worked for me is the functionality that Xcode gives you out-of-the-box (without using the terminal). It was point-and-click but just not automated.</p>
<p>If you&#8217;re interested here is how you get a hosted subversion repository to work with Xcode 4. Have fun and don&#8217;t sweat the snickers from your more version control evolved friends <img src='http://www.pavley.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<ol>
<li>Create a new Subversion repository that you can access via your protocol of choice (mine is the open Internet and HTTP because that&#8217;s what Dreamhost provides). Leave this repository empty&#8211;we&#8217;ll use Xcode 4 to set up all the directories. Just remember your URL and password.</li>
<li>Open Xcode 4 and go the Repository tab in the Organizer Window.  Click the tiny little plus sign in the lower left corner to add a connection to a Repository. Enter in the URL and password and wait for the little circle to turn green. Xcode 4 should automagically detect the type of repository. Be patient. This process takes a bit of time and there is absolutely no feedback: Apple forgot to spin the beach ball here.</li>
<li>When you get the green circle click on the root directory icon on the left under the name of the repository and create 3 directories using the New Directory button on the bottom: trunk, branches, tags. Be patient again and wait for the directories to show up in the center pane of the Organizer window.</li>
<li>Click on the name repository on the left and enter the names of our your 3 directories in the 3 fields provided. (See the genius of naming them trunk, branches, tags?) If your spelling is good you&#8217;ll get 3 more green circles.</li>
<li>Click on the Trunk directory on the left and then click on the Import button on the bottom. Select the folder that contains the project you want to put under source code control. Now go away. Get a drink and watch an episode of South Park. You have to be patient because not only is there no beach ball, spinner, or progress bar, there is <em>no green circle</em>!</li>
<li>When you come back you should see your imported directory listed on the main pane. If you click the arrow to the left of it you&#8217;ll find your Xcode 4 project file and a subdirectory of files. Remember to be patient. Your poor overworked laptop has to ask the Subversion server for all this info and it takes way longer than 200 milliseconds to get back to you.</li>
<li>Make sure your original Xcode project is closed and hidden away for safe keeping. Click on the imported project in the main pane of the Organizer window and click on the Checkout button on the bottom. Select a location on your hard disk to store your working copy of the project that won&#8217;t conflict with the original project. It should be OK to overwrite the original but I&#8217;m just paranoid. (Years of experience will do that to you.)</li>
<li>Get a cup of coffee and troll <a href="http://www.reddit.com/r/funny">Reddit</a> for some laughs. When you come back Xcode should ask you in a dialog box if you want to open the project that you just checked out. Say yes and run it just to be sure it&#8217;s all there. (Paranoia again, sorry.)</li>
<li>Now make a change to your and look for the little M to the right of the file name in the Project Navigator pane to show up. Be patient. If it&#8217;s not showing go back the the Organizer Window, back to your Project folder (by selecting its name on the left), and click the Commit button. The little M should now and forever show up next to your modified files in the Project Navigator.</li>
</ol>
<p>I&#8217;m still having a little problem committing from the context menu in the Project Navigator but I can commit just fine from the Organizer Window. Maybe that&#8217;s just how Subversion works with Xcode or more maybe I have to be even more patient. I&#8217;ll let you know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/06/12/hey-its-easier-than-you-think-xcode-4-and-subversion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cocos2d Tip#3: Making Your iPhone Game Fast</title>
		<link>http://www.pavley.com/2011/04/09/cocos2d-tip3-making-your-iphone-game-fast/</link>
		<comments>http://www.pavley.com/2011/04/09/cocos2d-tip3-making-your-iphone-game-fast/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 18:00:50 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=349</guid>
		<description><![CDATA[My first iPhone game, that might actually make it to the App Store, is just about done. (Not done done but almost ready for testing and tweaking.) With the idea that other people beside me might actually play my game I&#8217;ve started to do a very dangerous and high risk activity: Optimization! The all the [...]]]></description>
			<content:encoded><![CDATA[<p>My first iPhone game, that might actually make it to the App Store, is just about done. (Not <a href="http://blog.phpdeveloper.org/?p=148">done done</a> but almost ready for testing and tweaking.)</p>
<p>With the idea that other people beside me might actually play my game I&#8217;ve started to do a very dangerous and high risk activity: <a href="http://en.wikipedia.org/wiki/Program_optimization#Quotes">Optimization</a>!</p>
<p>The all the famous Computer Scientists and Software Architects agree: Optimizing your program is a necessary evil, like the death penalty or bug tracking systems, and to be avoided at all costs.</p>
<p>Well, that&#8217;s not quite true. It&#8217;s premature optimization that is the bad guy here. Don&#8217;t start out programming with performance or scalability in mind, least you optimize code that doesn&#8217;t need it and miss optimizing code that really needs it. (It&#8217;s the same for bug tracking systems&#8211;don&#8217;t put all your junk in Jira or Bugzilla&#8211;just the verifiable, repeatable bugs that you might actually fix one day.)</p>
<p>When I started my game I knew my ideas were going to evolve and I didn&#8217;t want to hard code myself into a corner. I consciously wrote code that I knew would be slow but flexible.</p>
<p>For example I used expensive string comparisons instead of testing for cheap numeric constants. During the initial development phases of my game the strings were self-documenting (I could read them like little notes to myself) and easy to change. Later, when my game solidified and the string comparison were easy to find using Xcode&#8217;s Find in Project command (which is now Xcode 4&#8242;s Find in Workspace command)&#8230;</p>
<pre class="brush: c++">// before optimization
if ([goodGuy.role isEqualToString(@"tank") {
   // aggro something
} else if ([goodGuy.role isEqualToString(@"healer") {
   // fix something
}</pre>
<pre class="brush: c++">// after optimization
switch (goodGuy.role) {
   case CharacterRole_tank:
      // aggro something
      break;
   case CharacterRole_healer:
      // fix something
      break;
   default:
      // oops! This should not happen
      CCLOG(@"unknown character role in %@",NSStringFromSelector(_cmd));
      break;
}</pre>
<p>Changing the type of Character's role property from NSString* to CharacterRole (a typedef'ed int) sped up my game in update methods which were called with every frame change. It was a pain to add all the constants but at least I only had to do it once--even though my conception of a Character and a role changed quite a bit.</p>
<pre class="brush: c++">// Character.h
typedef enum {
    CharacterRole_tank = 0,
    CharacterRole_healer = 1,
    CharacterRole_melee = 2,
    CharacterRole_ranged = 3,
    CharacterRole_boss = 4,
    CharacterRole_add1 = 5,
    CharacterRole_add2 = 6,
} CharacterRole;

// Character.m
@interface Character : NSObject  {
   NSString* _name;
   CharacterRole _role;
   // ...
}
@property (readwrite, copy, nonatomic) NSString* name;
@property (readwrite, assign, nonatomic) CharacterRole role;</pre>
<p>Another big optimization I did was to replace for-loops and with Cocos2d's fast enumeration macros...</p>
<pre class="brush: c++">// before optimization
Character* goodGuy = nil;
for (int i = 0; i &lt; self.goodGuys.count; i++) {
   goodGuy = [self.goodGuys objectAtIndex:i];
   // do something with good guy
}

// after optimization
Character* goodGuy = nil;
CCARRAY_FOREACH(self.goodGuys, goodGuy) {
   // do something with good guy
}</pre>
<p>My list of good guys changes during the game so I stored them in a CCArray&#8211;Cocos2d&#8217;s version of a NSMutuableArray. CCARRAY_FOREACH is a Cocos2d macro supercharged for fast array access. I could have used the Objective-C version of a fast numerator but I like to use as much of Cocos2d as I can. That way when I port my game to <a href="http://www.cocos2d-x.org/">Cocos2d-x</a> (C++ cross-platform version) it will be less work <img src='http://www.pavley.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>One of the biggest optimizations I did was to upgrade from Cocos2d 0.99.5-rc1 to 1.0.0-rc. You have to be smart about when you upgrade to a new version of a framework. I don&#8217;t agree with the idea of living on the bleeding edge&#8211;stability of the platform allows me to focus on my own bugs!</p>
<p>Upgrading from Xcode 3 to Xcode 4 also seemed to help, or at least not hurt, performance. The new version of Cocos2d seems to work better with Xcode 4. I&#8217;m still getting used to the shiny new Xcode&#8211;it acts weird and slow on my Mac Mini.</p>
<p>To make framework and Xcode upgrades easy I put very little code into my app delegate class. All I have to do is to comment out&#8230;</p>
<pre class="brush: c++">//[[CCDirector sharedDirector] runWithScene: [HelloWorldLayer scene]];</pre>
<p>and replace it with&#8230;</p>
<pre class="brush: c++">[[CCDirector sharedDirector] runWithScene: [HomeScreen scene]];</pre>
<p>There are lots more optimization I can do if my performance isn&#8217;t where I want it to be: Unroll my loops and get rid of Character lists altogether. But I&#8217;ll lose a lot of abstraction and flexibility so I&#8217;m not going to optimize anything more unless my beta testers complain!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/04/09/cocos2d-tip3-making-your-iphone-game-fast/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cocos2d Tip #2: Using CCTimer in Your iPhone Game</title>
		<link>http://www.pavley.com/2011/03/25/using-cocos2ds-cctimer-in-your-iphone-game/</link>
		<comments>http://www.pavley.com/2011/03/25/using-cocos2ds-cctimer-in-your-iphone-game/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 10:02:18 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Sprite]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=291</guid>
		<description><![CDATA[If you&#8217;re writing almost any type of game, from a puzzler to a FPS to an RTS, tracking time is critical element of the game play. (Except for Angry Birds. You can ponder an Angry Birds level until your iPhone battery runs dry without penalty.) Cocos2d-iPhone provides several means for tracking time in your game [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re writing almost any type of game, from a puzzler to a FPS to an RTS, tracking time is critical element of the game play. (Except for Angry Birds. You can ponder an Angry Birds level until your iPhone battery runs dry without penalty.)</p>
<p>Cocos2d-iPhone provides several means for tracking time in your game and scheduling methods to be called at both regular heartbeats and at arbitrary points in the future. The easiest way to manage time in a Cocos2d-based game is to use a CCLayer&#8217;s <em>scheduleUpdate</em> or <em>schedule</em> methods. Both methods are explained nicely in the <a href="http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:best_practices#timers">timers</a> section of the <em>Cococ2d Best Practices </em>guide. The guide also explains why you should try to avoid using iOS&#8217;s NSTimer class. (Your game will miss out on automatic pause and resume if do use NSTimer.)</p>
<p>But what if you can&#8217;t use scheduleUpdate or schedule in your game because you&#8217;re putting your game logic into a custom class instead of a CCLayer or CCSprite?</p>
<p>For the sake of simplicity and portability I don&#8217;t subclass CCSprite in my games. Instead, I create custom classes to represent my game objects and call update:(ccTime)delta on them from CCLayer objects to make stuff happen. I needed a nice timer class and started to write my own. About halfway though this project I ran into Cocos2d&#8217;s CCTimer. Since I&#8217;m trying to write as little code as possible I abandoned my timer. CCTimer is a nicely written, lightweight timer class that uses NSInvoker to create callbacks and still integrates will with the rest of the Cocos2d-iPhone framework.</p>
<p>Here&#8217;s how it use it&#8230;</p>
<p>First, I store a reference to a timer in my non-Cocos2d class:</p>
<pre class="brush: c++">
// Zombie.h
#import "cocos2d.h"
@interface Zombie : NSObject {
    BOOL _resurrectable;
    ccTime _resurrectionCountdown;
    CCTimer* _resurrectionTimer; // own
    float _rebirthPenalityPercent;
}
@property (readwrite, nonatomic, assign) BOOL resurrectable;
@property (readwrite, nonatomic, assign) ccTime resurrectionCountdown;
@property (readwrite, nonatomic, retain) CCTimer* resurrectionTimer; // own
@property (readwrite, nonatomic, assign) float rebirthPenalityPercent;
- (void) startResurrectionTimer;
- (void) stopResurrectionTimer;
@end
</pre>
<pre class="brush: c++">
// Zombie.m
#import Zombie.h
@implementation Zombie
@synthesize resurrectable = _resurrectable;
@synthesize resurrectionCountdown = _resurrectionCountdown;
@synthesize resurrectionTimer = _resurrectionTimer;
@synthesize rebirthPenalityPercent = _rebirthPenalityPercent;
+ (id) getInstance {
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
    return [[[self alloc] init] autorelease];
}

- (id) init: {
    CCLOG(@"** %@: %@", NSStringFromSelector(_cmd), self);
    if ((self = [super init])) {
        self.resurrectable = YES;
        self.resurrectionCountdown = 30.0f; // half a second
        self.resurrectionTimer = nil;
        self.rebirthPenalityPercent = 0.10f; // 10% less health
    }
}
@end
</pre>
<p>Second, I define a call back method to stop the timer:</p>
<pre class="brush: c++">
// later on in Zombie.m
- (void) stopResurrectionTimer {
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
    if (self.resurrectionTimer != nil) {
    // the only way stop a timer is to deallocate it
        [_resurrectionTimer release];
        _resurrectionTimer = nil;
    }
    // do stuff when the zombie dies...
}
</pre>
<p>Third, I define a method to start the timer:</p>
<pre class="brush: c++">
- (void) startResurrectionTimer {
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
    if (self.resurrectionTimer != nil) {
         // if there is an old resurrectionTimer then deallocate it
         // (this is the only way to stop a timer)
        [_resurrectionTimer release];
        _resurrectionTimer = nil;
    }
    //  allocate a new timer with a built-in factory method
    // the stopResurrectionTimer method is called when
    // the time is up!
    self.resurrectionTimer = [CCTimer timerWithTarget:self
                                             selector:@selector(stopResurrectionTimer)
                                             interval:self.resurrectionCountdown];
}
</pre>
<p>Fourth, I add a call to update the timer in my CCLayer&#8217;s update method:</p>
<pre class="brush: c++">
// ZombieGameLayer.m
- (void) update:(ccTime)delta {
    [self.zombie.ressurrectionTimer update:delta];
}
</pre>
<p>Finally, Somewhere deep in my game logic I start the timer at the right dramatic moment.</p>
<pre class="brush: c++">
// somewhere else in Zombie.m
- (void) die {
    // call when killed
     CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

    // if resurrectable start resurrectionTimer
    if (self.resurrectable) {
        [self startResurrectionTimer];
    }
}
</pre>
<p>It&#8217;s important to note that at the time of this blogging, the CCTimer documentation claims the interval value used to determine the length is in seconds, but really it&#8217;s in milliseconds (that is 1/60 of a second). If want your timer&#8217;s call back to run in 2 minutes set the CCTimer interval to 160.0f.</p>
<p>It&#8217;s also important to note that CCTimer is independent of frame rate: This might be obvious but sometime you want to execute an action every frame an sometime you want to execute it every few milliseconds.</p>
<p>If things aren&#8217;t working make sure you&#8217;ve told your layer to schedule updates in it&#8217;s init method and make sure you are updating your timers from your layer <img src='http://www.pavley.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/03/25/using-cocos2ds-cctimer-in-your-iphone-game/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Objective-C Memory Management For Newbies</title>
		<link>http://www.pavley.com/2011/02/12/objective-c-memory-management-for-newbies/</link>
		<comments>http://www.pavley.com/2011/02/12/objective-c-memory-management-for-newbies/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 21:32:51 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=305</guid>
		<description><![CDATA[Below you will find a list of memory management rules that will make your Coco2d game coding experience easier and your games less buggy. But before you dive in please read the caveats below: These rules are based on several sources written by engineers with much more experienced than me in Objective-C and Cocos2D development. [...]]]></description>
			<content:encoded><![CDATA[<p>Below you will find a list of memory management rules that will make your Coco2d game coding experience easier and your games less buggy. But before you dive in <em>please</em> <em>read</em> the caveats below:</p>
<ul>
<li>These rules are based on several sources written by engineers with much more experienced than me in Objective-C and Cocos2D development. Any mistakes are my own, any good idea belong to them.</li>
<li>My sources include this <a href="http://www.raywenderlich.com/2657/memory-management-in-objective-c-tutorial">tutorial</a> by Ray Wenderlich and the <a href="http://www.raywenderlich.com/forums//viewtopic.php?f=2&amp;t=154#p543">comments</a> by fufie. Ray&#8217;s tutorials should be read by every aspiring Coco2d-iPhone developer!</li>
<li>I also found this Stack Overflow <a href="http://stackoverflow.com/questions/588866/atomic-vs-nonatomic-properties">question and answer</a> on property declarations and this <a href="http://cocoacast.com/?q=node/103">blog post</a> on properties by CocoaCast really helpful as well.</li>
<li>Of course all this info is contained in Apple&#8217;s <a href="http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html">Memory Management Programming Guide</a> in greater detail. RTFM, as they cheerfully remind us in IRC, is a great way to learn.</li>
<li>In many ways this blog post is just a briefing on all of the above material and my motivation for posting this info is just to have it all in once place and neatly summarized.</li>
<li>Finally, these rules are guidelines for inexperienced developers, not laws. Engineers who are experienced with Objective-C memory management and Cocos2d don&#8217;t need these rules and shouldn&#8217;t even bother to waste their time and read my post. Following these rules will keep newbies out of trouble with their first game or two.</li>
</ul>
<p><strong>10 rules that make memory management a breeze&#8230;</strong></p>
<p><strong>Rule #1</strong>: Always create properties for your <em>ivars</em> in your .h and <em>synthesize</em> them in your .m.</p>
<pre class="brush: c++">// in MyClass.h
@interface MyClass : NSObject {
@public NSString* _moniker;
}
@property (nonatomic, copy, readwrite) NSString* moniker;
@end

// in MyClass.m
@implementation MyClass
@synthesize moniker = _moniker;
@end</pre>
<p><strong>Rule #2</strong>: Use an <em>underscore</em> so the compiler can distinguish an ivar from a property with a common root name. When synthesizing remember to associate the ivar with the property. This way the compiler will yell at you if you try to set an ivar as if it were a property.</p>
<pre class="brush: c++">@synthesize moniker = _moniker; // ivar = property</pre>
<p><strong>Rule #3</strong>: Always access your internal properties through <em>self</em> using <em>dot syntax</em> to ensure proper memory management through property declarations.</p>
<pre class="brush: c++">self.moniker = @"Betty"; // the ivar _moniker now refers to a new copy of the string "Betty"</pre>
<p style="padding-left: 30px;"><strong>Note:</strong> In C, C++, and Objective-C the operand on the left must be an <a href="http://stackoverflow.com/questions/579421/often-used-seldom-defined-terms-lvalue">lvalue</a> so you can&#8217;t chain assignments. Code like</p>
<pre class="brush: c++" style="padding-left: 30px;">self.rectangle.top = 10;</pre>
<p style="padding-left: 30px;">generates a compiler error.<br />
Instead you have to unpack the object and assign it back to the property:</p>
<pre class="brush: c++" style="padding-left: 30px;">Rectangle* rect = self.rectangle;
rect.top = 10;
self.rectangle = rect;</pre>
<p><strong>Rule #4</strong>: Always provide an <em>object factory class method</em> to create an instance of your custom objects using autorelease for simple memory management.</p>
<pre class="brush: c++">+(id) getInstance {
	return [[[self alloc] init] autorelease];
}</pre>
<p><strong>Rule #5</strong>. When declaring a property for a basic type or for objects you don&#8217;t own use the <em>assign</em> attribute.</p>
<pre class="brush: c++">@interface MyClass : NSObject {
@public int  _counter;
@public NotYourObject* _notMyObject;
}
@property (nonatomic, assign, readwrite) int counter;
@property (nonatomic, assign, readwrite) notMyObject;
@end</pre>
<p><strong>Rule #6</strong>: When declaring a property for a subclass of NSObject use the <em>retain</em> attribute to retain the object on assignment and release the original object (if any) associated with the property.</p>
<pre class="brush: c++">@interface MyClass : NSObject {
@public Something*  _thing;
}
@property (nonatomic, retain, readwrite) Something*  thing;
@end</pre>
<p><strong>Rule #7</strong>: When declaring a property for an NSString use the <em>copy</em> attribute to create a copy on assignment and release the original string (if any) associated with the property. You probably want the assigned string and the original string to be two independent objects.</p>
<pre class="brush: c++">@interface MyClass : NSObject {
@public NSString*  _moniker;
}
@property (nonatomic, copy, readwrite) NSString* moniker;
@end</pre>
<p><strong>Rule #8</strong>: Use the <em>autorelease</em> to automatically release objects when you are done with them.</p>
<pre class="brush: c++">self.thing =  [[[SomeThing alloc] init] autorelease];</pre>
<p><strong>Rule #9</strong>: Apple API calls that begin with &#8220;init&#8221; or &#8220;copy&#8221; need to be managed by you and released when you&#8217;re done with them. You can use rule #8 to make releasing objects at the end of a method painless.</p>
<pre class="brush: c++">self.moniker = [NSString stringWithFormat:@"%@ number %i", @"Betty, 2]; // already autoreleased
self.moniker = [[NSString initWithFormat:@"%@ number %i", @"Betty, 3] autorelease]; // needs autorelease</pre>
<p><strong>Rule #10</strong>: Always use the <em>nonatomic</em> attribute when declaring properties unless you are working with multiple threads&#8211;and if you are working with multiple threads you are way above the level of these rules.</p>
<pre class="brush: c++">@property (nonatomic, assign, readwrite) int counter;</pre>
<p><strong>Rule #11: </strong>Always use the ivar in your delloc method to release objects you own and set them to nil (to ensure safe subclassing).</p>
<pre class="brush: c++">[_moniker release];
_moniker = nil;</pre>
<p><strong>A thought on static analysis&#8230;</strong></p>
<p>Xcode&#8217;s <em>Build and Analyze</em> (Shift-Cmd-A) always drives me crazy with false positives. First, it finds potential issues with the Cocos2D framework source files and I&#8217;m not about to worry about or fix any of those. Second, all the issues it finds in my source files are either trivial non-issues (an assignment hidden inside an if-then-else block) or not problems at all (releasing object that it thinks I don&#8217;t own). But perhaps it&#8217;s my coding style that needs to improve. I hate letting warnings go by unresolved and as soon as figure out a way to write code the makes static analysis happy I&#8217;ll let you know.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/02/12/objective-c-memory-management-for-newbies/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cocos2d Tip #1: Changing a Sprite&#8217;s Image Simply</title>
		<link>http://www.pavley.com/2011/02/05/cocos2d-tip-1-changing-a-sprites-image-simply/</link>
		<comments>http://www.pavley.com/2011/02/05/cocos2d-tip-1-changing-a-sprites-image-simply/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 06:08:05 +0000</pubDate>
		<dc:creator>pav</dc:creator>
				<category><![CDATA[Cocos2d-iPhone]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Sprite]]></category>

		<guid isPermaLink="false">http://www.pavley.com/?p=292</guid>
		<description><![CDATA[I&#8217;m writing an iPhone game using the Cocos2d-iPhone framework. It&#8217;s been smooth sailing except for one little detail: I want a sprite to change it&#8217;s image based on a touch. I think the problem is that there are a dozen ways to do this in Cocos2d. I wanted to find the simplest way to do [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m writing an iPhone game using the <a href="http://www.cocos2d-iphone.org/">Cocos2d-iPhone framework</a>. It&#8217;s been smooth sailing except for one little detail: I want a sprite to change it&#8217;s image based on a touch.</p>
<p>I think the problem is that there are a dozen ways to do this in Cocos2d. I wanted to find the simplest way to do it. A quick Google search pointed me in the direction of CCAnimationCache and CCTextureCache.</p>
<p>CCAnimationCache is used for running multi-frame animations inside a single sprite. I only have 2 frames for my sprite! CCAnimationCache could do it but it&#8217;s a more power than I need to respond to a touch. (If you want to give animation a try check out Ray Wenderlich&#8217;s wonderful <a href="http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d">tutorial</a>.)</p>
<p>CCTextureCache would have been the way to go if I hadn&#8217;t already used CCSpriteFrameCache to load all my sprite images at the start of my game. CCSpriteFrameCache uses a plist that divides up a large image into rectangle so you can pack all your sprite images into one memory saving &#8220;texture atlas.&#8221; And you can use <a href="http://zwoptexapp.com/">Zwoptex</a> to generate the image and the plist for you. CCTextureCache is the manual way to do what CCSpriteFrameCache and Zwoptex automates for you. (If you like to be hard core check out Ben&#8217;s post on <a href="http://allseeing-i.com/Performance-tips-for-Cocos2d-for-iPhone">optimizing texture loading</a>.)</p>
<p>I figured there had to be a way to use my sprite frames in my existing cache without having to resort to manually loading textures or creating animations I didn&#8217;t need.</p>
<p><strong>There was! </strong>It&#8217;s simple and here&#8217;s how to do it&#8230;</p>
<p>First, create your texture atlas with Zwoptex and add the .plist and .png files to your Resources folder in your Xcode project.</p>
<p>Second, load the texture atlas into the shared frame cache early in your game&#8230;</p>
<pre class="brush: c++">
CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
[frameCache addSpriteFramesWithFile:@"textureAtlas.png"];
</pre>
<p>Third, create your sprite in your layer&#8217;s &#8211; init method&#8230;</p>
<pre class="brush: c++">
// Note: niceSprite is a CSprint* instance variable so we can reuse it
niceSprite = [CCSprite spriteWithSpriteFrameName:@"initial_image.png"];
niceSprite.position = CGPointMake(240, 160);
[self addChild:niceSprite z:0 tag:0];
</pre>
<p>Fourth, in your &#8211; ccTouchBegan or &#8211; ccTouchesBegan method add the following code to change the image associated with your sprite&#8230;</p>
<pre class="brush: c++">
CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
CCSpriteFrame* frame = [frameCache spriteFrameByName:@"new_image.png"];
[niceSprite setDisplayFrame:frame];
</pre>
<p>That was easy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pavley.com/2011/02/05/cocos2d-tip-1-changing-a-sprites-image-simply/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

