Sunday, May 5, 2013

Enabling ARC for your Cocos2D iOS projects

A quick video tutorial on how to enable Automatic Reference Counting for your Cocos2D iOS game projects.  The process is fairly simple, but its not trivial and its easy to get wrong, so I've taken the time out to record how its done in XCode.

I use the technique described by Steffen Itterheim in his book Learn cocos2d Game Development with iOS 5 which I thoroughly recommend if you're getting started with Cocos2D on iOS.

Here's the video.

Here's the why - although I do explain this in the video, you might want to know why you need it before you invest the time.

Cocos2D by default does not build as a seperate library - the Cocos2D templates just inject all the source code as a tree of files right into your new project.  That gets built alongside your own source code right into the same binary target.

Now Cocos2D currently does not support ARC since I guess the project was started before ARC came along and its a big effort to do the conversion while ensuring nothing breaks.  That means that your whole project can't use ARC - so you would have to do all your release and retains and other Objective-C memory management as per the bad old days before automatic reference counting.

To fix it we build Cocos2D as a seperate compilation unit - a static library - and it builds without ARC as before.  But now your game code is seperate and it can have ARC enabled.  Simple idea, and easy enough to do, once you know how.

Hope the video helps and happy game hacking with Cocos2D!

Update:  I just discovered that Steffen has his own video tut on this already.  Maybe you guys will still get some value from my take on this process, so I'll leave my version up for now.

Update 2: If you get a run-time error like this:

-[CCPhysicsSprite setPTMRatio:]: unrecognized selector sent to instance

...then its because you need to do one more step when you enable ARC by making Cocos2D a static library that includes Box2D.  That is to add the macro


into the Build Settings for the Cocos2D library target.  Here's a screenshot:

Thanks to Komet163B on my YouTube channel for reporting on this issue.

No comments:

Post a Comment