Skip to content

Archive

Category: iOS/Cocoa

This is a flag you can pass along with ‘other linker flags’ in XCode build settings. It tells the linker that your project requires the C++ standard library.

If your project contains *.mm files this is set automatically (implicitly, rather). But what if you wrapped a C++ library using Objective C++ and carefully make sure that no C++ leaks into client code. Now you have a static library wrappedcpp.lib (speaks C++, OC++) and your app tries to link against this but doesn’t contain even one *.mm file?

What then? A bunch of ridiculously obscure linkage errors.

Thanks to Rob Napier, I can go back to my debugging (check the QA on stack overflow)

I haven’t worried about device orientation in a while. Supporting a variety of orientations is *nice*.

On iPad, supporting all orientations is strongly recommended; not supporting ‘upside down’ variants of your orientation is rarely tolerated(*). Unless you have a good reason not to (e.g. accelerometer freak app).

So I thought I’d rehearse a little. I learned new things and discovered an iOS 4.0 cherry that helps avoiding orientation caveats: UIWindow’s rootViewController property.

(*) Keep safe from harm.

How to support device orientation changes?

  • Edit the info.plist file for your target
  • Your views should be managed by view controllers. You can do without view controllers but then you’re pretty much on your own although at least there’s a system callback to tell you the orientation changed (seriously, you can find it yourself).
  • Your view controllers should override shouldAutorotateToInterfaceOrientation.
  • Your nib files should be nicely configured so your widgets won’t fly around in a happy mess when rotated.
  • Know more about how views are managed, and how view controllers relate to the key window (see caveats)

info.plist

Specify supported orientations in the info.plist for your target:

  1. Select your project in the navigator
  2. Select your target
  3. Press/Depress orientation toggles in the summary tab (big icons showing rotated devices).

view controller

Override this and return YES to your supported orientations:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

interfaceOrientation may take one of the following values:

UIDeviceOrientationLandscapeLeft, UIDeviceOrientationLandscapeRight, UIDeviceOrientationPortrait,

UIDeviceOrientationPortraitUpsideDown

Sadly this appears to have a life of its own. Setting the info.plist property doesn’t further restrict a view controller’s response to orientation changes. In other words your plist may say that you only support landscape left/right. If a VC returns yes to all orientations, this won’t prevent its views from rotating.

Configure your nib files

A savvy approach to managing rotation is to create documents that look good both in portrait and landscape mode. It is possible to use different nib files for different orientations (not covering this here).

  • In the attributes inspector for your document’s main view, set ‘Autoresize subviews’ to true.
  • In the size inspector, use the autosizing toggles to determine what should happen to each element when the view rotates. You (or your UI designer) should do this for each element in the UI, deciding whether that element should size to fit / use a fixed size, and how to anchor the element (left, right, top-left, bottom, …).
  • You can toggle the current ‘simulated’ orientation of a view using the orientation setting in the attributes inspector.

You can remove/resize elements programmatically (check Apple docs as referred below).

Caveats

In a worse case scenario, changing device orientation will do little other than moving the status bar (if there is one). Two possibilities:

  1. Your view controller isn’t notified of the change, so it can’t rotate its view.
  2. Your view isn’t managed by a view controller.

Read about custom view controllers (link to SDK docs). Under “Presenting a view controller’s view”:

” [...] use only the suggested techniques for displaying the views of your view controllers. In order to present and manage views properly, the system makes a note of each view (and its associated view controller) that you display directly or indirectly. [...] When the device orientation changes, a window uses this information to [notify] the frontmost view controller. If you incorporate a view [...] by other means (by adding it as a subview to some other view perhaps), the system assumes you want to manage the view yourself [...]“

And this, under “Understanding the rotation process”:

“[...] the window object does much of the work associated with changing the current orientation. [...] Specifically, it works with the view controller whose root view was most recently added to, or presented in, the window.”

Only one view controller will receive the event, and propagate it to it’s (unique) view (and the underlying hierarchy).

Note: if you search for UIVviewController in XCode docs, also read the lovely article: “Why won’t my UIViewController rotate with the device”.

Common Solutions

In my experience, using several view controllers and adding their views to the main window is error prone. Pity, because it feels like a natural, no-nonsense approach to displaying views (but see the nice solution, below).

  • Use a unique view controller. Doesn’t sound great but if you have a simple app, at least it’s safe.
  • Display the view controller’s view modally. This often makes sense since a view controller is meant to manage one screen’s worth of content. IMHO the downside is that system semantics are associated with modal transitions, and misinterpreting how these transitions should be used may hurt you. For example, you may be struck by lightning.
  • Use a navigation controller, a tab bar interface or a popover.
  • Hacking a controller’s view down the hierarchy of the controller that receives orientation events. Ugly. However, note that hiding and showing views is a lot faster than adding and removing views. On older devices this may affect the user experience.

A nice solution

I wasn’t desperately happy with *any* of the above. Following the ‘one controller manages one screen’s worth of content’ idea, it would make sense if…

  • APIs prevented us from adding several views to the main window.
  • Any view added to the main window must be managed by a view controller.
  • We could actually tell the window which controller it should be working with.

In IOS4.0 and later, there is a public, documented property that works with UIWindow. You can assign a window’s rootViewController property. This does a lot of work underhand:

  • Remove the existing view hierarchy displayed by the window
  • Add the new root controller’s view hierarchy to the window
  • Make the VC ‘frontmost’. That VC will now receive notifications when the orientation changes.

I tried this and it works like a charm. I seemed less lucky when combining [window addSubview:] with the root view controller property, but maybe it can still work.

Resizing OpenGL surfaces

EAGLView is a utility class for displaying OpenGL content. You can find it in iOS SDK samples and it is often used as a starting point for OpenGL applications.

When an instance of EAGLView is rotated, it calls its [layoutSubviews] method. If you created your EAGLView programmatically, remember to set the autoresizing mask, as follows:

view.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;

Otherwise your EAGLView won’t resize, and [layoutSubviews] is never called.

layoutSubviews calls this onto another utility class, aka ‘renderer’ (typically, ES1/ES2Renderer).

[renderer resizeFromLayer: (CAEAGLLayer*) self.layer];

The sample code provided in ES1/ES2Renderer resizes the underlying buffers correctly, so you could use it as a starting point. I get wimpy when it comes to buffers, but I still managed to get it right using the following ideas:

  • The color buffer is resized from the CAEAGLLayer.
  • We then retrieve the backing width/height from that same buffer.
  • Other buffers (depth, MSAA etc…) can be reallocated using whatever method we already know (remember to use the updated width/height).

Now that we’re a little more familiar with targets. How about we actually stopped being lazy and created a shared library?

How to do it

  1. Select File > New > Target (can also click on the project to open the target list and select the (+) symbol at the bottom left)
  2. Pick ‘Framework & Library’ in iOS templates.
  3. Select ‘Cocoa Touch Static Library’

I have a few files that I find useful whatever project I’m working on; for now I have just removed these files from all my existing targets, and added them to my newly created ‘utilities’ library target. This builds without issues.

Next, I opened the Build Phases tab for a target that should use the library. I drag and drop the library in the ‘Link Binary With Libraries’ section. Ordering is sensitive, so I add my library at the bottom of the list, after the frameworks.

Remember that the library should be listed by every target that uses the library. If your main target depends on a test target, and somehow your test code implies using the library as well, then both the main target and the test target should link against the library.

OK, how do I include the headers in my project?

  1. Click on your project (the project that you want to use your library with) to open the build related stuff.
  2. Select the project. It’s especially useful to include headers at project level if you have tests or use several targets.
  3. search for ‘User Header Search Paths’.
  4. Add the path to the library source file. It’s better to add a relative path. So if your project is under foo/myProj.xcodeproj and the library headers are under foo/myLib/myLib, then typically the path would be ../myLib/myLib
  5. You may need to set the matching target settings (the user header search path in each target) to $(inherited). This explicitly tells a target to inherit the setting from project level.

I feel there should be a cleaner way to do it, but I’ve seen it done by other devs, works for me.

Why do it?

Maybe you have qualified reasons for using a static library instead of sharing files across targets. Or maybe you just want to create a library that other developers can use.

However, even if we’re working on small projects and the ‘dev team’ is just one guy, the bottom line is that static libraries are the better way as soon as you want to share code between your apps.

Even if you define your apps using several products in the same project (a lightweight, moderately evil technique I describe in my previous post), that changes little to the fact that editing target associations in xcode is a manual process that requires patience. So rather than having to add every other code file to a new target whenever we start a new project (or removing undesirable files from a cloned target), we just add our files to the library, and link the library against our project, once and for all.

What cannot be included in a static library?

Pictures, text files, nib files and other non code files cannot be included in a library target. Code and header files can be included. It is interesting that Test and Library targets both allow *.h files, whereas product targets do not.

Can I get my static library to build automatically whenever I rebuild my product target?

Yes; it works the same as target dependencies for test targets.

Under ‘build phases’, drag the library target into the ‘target dependencies’ list. Ben Artin explained very nicely (here) that ‘dependencies are orthogonal to linking, if you want both, you need to specify both’

Reading further

You may find this article useful (from “The Carbon Emitter”).

What if we just wanted to share a little bit of code?
What if we where extremely lazy and didn’t want to learn about XCode 4 workspaces?
What if we didn’t want to create and maintain static libraries?

What if we wanted a solution that’s not even scalable, but does the trick while we bide our time?

And finally, what if we had a bunch of similar products based on a budding ‘framework’. Then we might decide to be evil, and dump all of our products in the same XCode project. Yay.

I decided to have a try. Until I hire another programmer, every day of my life is a Sunday. I found that cloning targets is easy, and just a little fiddling will take us from cloning targets to cloning apps and mutating them into something new.

Creating new targets isn’t hard, but then we have all these files we want to add to the new target. That should be easy as pie, but it’s not.

You can try this on a Saturday too, unless you’re working overtime.

1. Duplicating targets

(right click on an existing target, select ‘duplicate’ and follow the signposts).

If two products (an existing one and a new one we’re about to make) are rather similar, duplicating targets may be the fastest way to setup the new product. It doesn’t duplicate any code or resource. Initially both targets use exactly the same stuff. To ‘fork’ a new product, we then duplicate the resources that ‘aren’t the same’.

The big advantage of this approach is that all existing resources are added to the target right away. So this approach is easy if somebody bothers defining a ‘product template’ that contain little / no product specific stuff.

But first and foremost…

We don’t want the same info.plist, right?

Correct. If we use the same info.plist, we can still have two different products on the desktop, but we won’t have different products in-store. A lot of the meta-data distinguishing a ‘product’ (something users can eventually download) from another is the metadata in the plist.

The fastest way I found to actually clone the plist file is to do it from the desktop (sigh) and adjust the Info.plist File setting in Build settings.

Why my ‘target names’ don’t update in the build selection drop-down? Why do I still see an entry there after deleting a target?

At this point I had created, deleted and renamed several targets. My ‘build selection drop-down’ ignored whatever name change or deletion I carried out.

After a few minutes of deep anxiety, I realized that the build thingy doesn’t directly relate to targets. At the bottom of the drop-down thing XCode 4 shows 3 options: Edit Scheme, Add Scheme, Manage Schemes.

  • After deleting targets, delete the associated schemes (go to ‘manage schemes’).
  • After renaming targets, delete all schemes (go to ‘manage schemes’) then press the top right button (‘auto create schemes now’).

2. Setting up a new target

Setting up a new target and adding resources to it is the slower, meaner way to (loosely speaking) ‘clone an existing product’:

  1. Go to File > New > New Target.
  2. Choose Window-based application (or whatever you please)
  3. Select a product name and fill in the company id.
  4. Leave ‘include Unit Tests’ checked (no need to be THAT evil)
  5. Press finish.

The sad point here is that no existing files are included in the new target (other than the boiler plate generated by the wizard) and XCode 4 doesn’t provide much of a nice, quick and easy way to add all these files we want to share across targets. We can select several files at once and edit their target setting in the file inspector, but we can only do this for files that belong to the same group.

3. to share or not to share…

There are several types of resources we might want to share across products:

  • Code
  • Frameworks
  • XIB files
  • Data files
  • Image files

If you use the ‘target clone’ method, at some point you definitely want to introduce these classes that make your app what it is (a new app! with some resources and code borrowed from the old one). Then comes the ‘forking’ question:

  • Do the targets use the same MainWindow.xib?
  • Do they use the same app delegate

If the two targets use a different xib as entry point, it’s easy to fork (because the xib is listed in the info.plist, and surely the info.plist is forked).

Otherwise, the quick and dirty way is to use homonyms. So we may have two ‘MyAppDelegate’ classes (same name, different folder); and we associate one with each target. IMHO this is really evil, but it’s like chocolate. A tiny bit won’t hurt.

You could also check PrEV’s Demystifying app startup article. Knowing more about app startup can help us resolve certain questions pedantically.

I also found a post about renaming projects. I kinda managed it before, but maybe the post is useful.

Conclusion

Maintaining several apps in the same XCode project is possible. It doesn’t mean it’s a good idea. Learning how to do it is a moderately fun way to learn about targets in XCode.

Are we finally migrating to XCode 4?

Laggards start with an edge when it comes to migrating to new/updated solutions: most of the problem areas have already been identified, discussed and resolved. Oh really?

Bread and butter: where’s our stuff?

Apple kindly provides an XCode 4 Transition guide. I’ve only skimmed through it and find myself moderately able to build my existing project.

  • Where is Get Info? It’s kind of been moved to a side panel which is disabled by default. Go to View > Utilities > File Inspector.
  • I added my file, it’s there! But when I build the file is missing. I had several flavors of this error:
    • I moved my .pch file; frankly this has nothing to do with xcode4. The location of the .pch seems to be relative to the project folder by default. so if your .pch is in a subfolder then the path should be changed to subfolder/myPrefix.pch or such.
    • I add files and they get marked red!
    • My files are still not found. Check what the path is relative to (open the ‘File Inspector’). I was migrating files and I noticed that they got marked as ‘relative to group’, and this caused files not to be found by the compiler. Heck, this is rather confusing.
  • Where is the ‘build’ button? I love running ‘just a build’ (instead of ‘build and run’), just to make sure my tests are doing OK. Apparently the toolbar can’t be customized anymore. Sigh… So yea, I got no f****g idea where this stuff is gone.
    => however you can build from the Product menu (Product > Build) or learn the shortcut (Cmd+B).
  • Where is the organizer?
    => Top right button in XCode window.
  • Where is repository/source control management?
    => in the organizer
  • How do I rename my project? It can be done in two ways (see below). Both methods will pop an interface where you can select matching entries to rename in project data. It is crude, but works. Unfortunately this doesn’t rename folders created by the project wizard. So MyProject/MyProject would be renamed to YourProject/MyProject (to keep tidy, it may be a good idea to rename your source and test folders to just ‘source’ and ‘test’ right after creating a new project)
    • In the project browser (click-wait-click onto the project icon/name), in the same way as you would rename a file in Finder.
    • In the attributes inspector (top right, edit project name) when the project node is selected.
  • How do I set NSZombieEnabled? Go to the scheme manager and edit environment variables for the matching target. If you can’t find it check this nice post from 42games (pics included).

    For a quick, yet more comprehensive tour of where the f***k’s everything in xc4, read pilky.me.

    Interface builder…

    IB is now integrated within XCode. It’s a bit weird, and also means that we can’t take advantage of a second display to work with IB and XCode simultaneously.

    • The attributes inspector can be opened using view > utilities > attributes inspector. It’s easy to toggle between inspectors (somehow renamed ‘utilities’) (file inspector, attribute inspectors etc…).
    • Likewise outlets etc… are also in the utilities panel.
    • The document window/nib browser has been replaced by a kind of left hand toolbar when opening a nib file. By default this toolbar would show something like unlabeled icons for the file owner, first responder and main view. There’s a tiny triangle at the bottom left that will reveal a hierarchic view that looks like the old nib browser.

    Workspaces

    • Create a new workspace: go to File > New > New Workspace. Easy.
    • Add a project to your workspace: drag the project file in your workspace/project browser. Drop towards the far left of the project browser (otherwise it will drop inside an existing project).

    Workspaces don’t do away with having to setup static libraries as a better way to share code across projects; however workspaces ‘look like they might be nice’. If you’re experience code sharing issues, workspaces may be the best reason to upgrade (to XCode 4, that is).

    What can’t I close the ‘extra tabbed editor’?

    Go to View > Editor and select Standard.

    The good, the bad, the ugly (and ((self=[super init])))

    This has always been OK; better than OK in fact, it’s an OC idiom:

    if( self=[super init] ){ … }

    Now it’s not. It triggers a warning. Well…

    • if(self=[super init]) is sucky. Instead of having well formed constructors we have this magic incantation that doesn’t even make it rain.
    • if((self=[super init])) is suckier. It’s ugly.

    So I did the suckiest thing. I switched my compiler version to LLVM GCC 4.2(*), which appears to be my so called ‘system default’, and unchecked the missing braces and parentheses warnings. I’m sure you think it’s a bad idea to disable warnings. So I went back to XCode 3.2 momentarily, to find that the warning’s always been unchecked. WTF, there’s more than 100k iOS devs out there, and here we are, wondering why our projects are forcibly ‘upgraded’ the betterest-most-pedantically-improved-style.

    (*) I just did it. You can find equivalent solutions whatever compiler version you set.

    What do I do with this ‘Missing File’ *.xcscheme is missing from working copy warning?

    It appears that when deleting/renaming schemes, the schemes may not be mark-deleted from source control. However XCode keeps track of our working copy, so it will soon be complaining that the file is missing from the working copy.

    Use your favorite source control utility to remove the file from the repo; the warning will disappear.

    Itunes’s messed up

    • upgrading iTunes didn’t work for me.
    • I reinstalled iTunes as described in this post on callingallgeeks.org. This cleared up the errors that were appearing in iTunes.

    C++ Migration Quirks

    I had hardly managed to download and install this little mammoth of an IDE when a colleague turned up, trying to migrate existing C++ projects to XCode4. Here are the main issues we encountered:

    MainWindow.xib not found. The project we looked at didn’t actually used a nib file or a main window (not very surprising with a migrated-from-C/C++-game-type-y-project). It somehow hooked a custom ‘main controller’ object using UIApplicationMain(…). However, the main window was listed in the project’s info.plist.

    Note that this error is commonly seen, even with projects that actually use a MainWindow.xib; if XCode 4 doesn’t see your nib/xibs anymore, check the simple solution suggested on the NSLog(); blog.

    => We deleted the MainWindow entry in the plist file (not just removed the name, actually removed the entry). If you list a MainWindow in your plist file, but actually start the app in a different way, XCode 3.x will just ignore the main window (most likely, fail silently). XCode 4.x will ‘fail fast’ (in other words, crash your app).

    “Bad codegen, pointer diff linker error…”. This is a linkage conflict that will typically happen when linking against several libraries built within the same project. The somehow likely reason this happens is XCode4 changed it’s default policy for handling external library symbols that do not declare access restrictions. So before these symbols didn’t get exported, but now they do, and the same, intended-to-be-internal-by-default-symbol is duplicated across two libraries or more.

    =>  Edit build settings for each target (the libraries we’re building and linking against): change the ‘Symbols Hidden By Default’ setting to true (as suggested in this stack overflow item). Now that I’m looking at one of my existing projects in XCode 3.x, I seem to find that ‘Symbols hidden by default’ is already checked).

    Linkage error (files not found)

    By default, XCode 4.x does not use the same build output directories as XCode3.x. Here we just updated (erased) absolute paths we found under ‘path to search for libraries’ or such.


    After a short break in Paris, I’m finding my game physics module where I left it: unfinished. I’m afraid this post isn’t all too informative, but I’ve renewed my commitment to keeping this blog a developer’s diary…

    PhysicalModel, for all it’s worth…

    I tried to have a look at how PhysicalModel could be implemented. The idea behind PhysicalModel was to have a protocol giving access to physical bodies and/or colliders. This uses a well known pattern: instead of adding the items we want to process to a list or set, we have a protocol specifying how the items are being accessed (a kind of iterator). But frankly I doubt whether the pattern is relevant here. For the sake of efficiency we’d probably allocate an old style array of pointers and iterate that instead, because it’s much faster. For the sake of simplicity, we’d just use an NSArray.

    What partakes the physical model?

    How do I initialize and maintain the content of PhysicalModel? Nothing explicitly specifies the content of PhysicalModel. We have candidates, but none of these actually describes the model the way I want it to be:

    • I have the cast (the list of actors). To keep things simple i’d like every actor to be modeled as a cylinder.
    • Then we have the terrain. I’d like every platform to be modeled as a special physical body with detailed processing (on a per face basis)
    • Finally, there are a number of elements present in the scenegraph that I would model as obstacles. For these, cylinder/spherical bounds may be enough.

    Provisionally, I decided to rebuild the model at the beginning of each chapter. The physical model might need additional maintenance – for example, if actors are added/removed while playing a chapter – but it seems like a decent start. I have a utility class in charge of (re)building the model, looking like this:

    @class AntistarCast,WalkableScene,PhysicalModel;

    @interface AntistarPhysicalSystemBuilder : NSObject {

    }

    +(void)buildUsingCast:(AntistarCast*)cast

    terrain:(WalkableScene*)terrain

    target:(PhysicalModel*)model;

    @end

    All we have to do to build the model is iterate the terrain/cast and generate physical bodies for matching elements.

    Simplifying the model

    I had Collider (something other objects can collide with) and PhysicalTarget (can be affected by collisions) protocols. I got rid of that and only kept PhysicalBody. As a result, processing is simplified – each PhysicalBody instance is tested against all other instances for overlaps.

    Whether we use separate interfaces or not, we can still reduce overheads - only moving objects need to be tested for collisions. So maybe the distinction between colliders and targets isn’t very useful at this point.

    Back to the happy days when I started enjoying my own, home-made dev tool (Antegram for Java), I stopped using a doclet generator. I could bring up any API I’d created without hiding whatever I was currently working on. XCode simply isn’t designed to allow you to do that; Eclipse, for all the bells and whistles, isn’t much better.

    In summary, for all I care auto-generated documentation is often little more than a way to browse APIs quickly when auto-completion doesn’t do the trick. I might end up writing a little utility to rip headers and signatures and put together something that fits that purpose better than a professional doc tool. In the meantime, I had a quick check on what we can already use.

    I came across Doxygen – not for the first time. Even Apple seems to recommend it (check this link) and there is an in-depth tutorial at Duck Rowing

    Two unpretentious doc generators you might want to check are nudoc and appledoc. Appledoc seems to be actively developed (v2.0 out January 2011)

    Our code is rarely as neat as we’d like it to be. And sometimes we’d like to make it do something, and we’re not sure how. Depending on… …a lot of things, there are two ways around the problem:

    1. Go with the code. Work out the problem bottom up and wire up everything as best as we can.
    2. Bend (and break) the code. Work out the problem top down, lay out a neat solution and (re)wire up everything else according to how we think is best.

    The main argument for going with the code is that it won’t break anything. Honest, it’s true. I’ve seen it done with extreme care and it works. But… It doesn’t make it easier to make the next change, and the next change, and the next change.

    Working top down will break the code, and should be done with care too. Sometimes breaking and repairing code is better than just going along with it. But just because the code hasn’t been written to solve the particular, new problem we’re looking at needn’t mean it’s bad code.

    A Story

    It was an ordinary day. A colleague had been working for a couple of months on a client side bridging component. We wanted the same functionality on the server side and I just thought it would be neat to share the code. So I suggested we do just that and he told me the component couldn’t be extracted from the client. I said it could, and he asked: how?

    Separation is rarely down to our software’s effective logic. For practical purposes, anything can be separated from anything else. So I just said:

    “Use the Sword of Faith”

    A couple of days later, the bridging component was all neatly… modularized. The code was cleaner and more readable (not my opinion – I didn’t even look). Unsurprisingly (and however unfortunate) the guy in charge of our server refused to use this code, and moved on to write their own. Whatever project this related to was postponed, and we moved on…

    The Evangelist

    For all the medieval hype surrounding it, the sword of faith is a well named design tool. Ideally it should be as sharp as a Katana, and operated with surgical precision (that and lightning fast coding skill, right?). Why a sword, then. Well there are other tools you might consider working with when extending and fixing up your code:

    • The mace. You can maim and mangle large sections of your code in the name of a good cause, leaving behind you many bugs for others (or more likely, yourself) to fix later.
    • Biological weapons. You can add a couple of lines of code here and there to get your new feature to work. This code won’t make sense in context and will likely contribute the overall sense of rot and decay emanating from your codebase.
    • The Hydrogen bomb. You can delete whole classes, even packages. At this point extending our software isn’t a problem. The problem is we’ll have to write the code all over again.

    In contrast, there are several techniques founding our belief into the sword of faith – namely, that code can be improved locally and that local improvements over time can significantly reduce our overall sense of helplessness looking at (what looks less like) the ambient mess.

    1. Define a ‘good solution’ for the problem at hand. Inasmuch as possible, the solution should hold good considered in isolation.
    2. Retrofit the ideal solution onto existing code, pass (existing code fits the solution) or break (existing code must be modified)
    3. Rewrite/Refactor as little and as much code as necessary.
    4. Be comprehensive, not exhaustive. If you’re unsure whether something needs/to be changed or fixed, you (or a compiler, or a unit test, or a tester…) will find out later. Trying to be exhaustive may result in changing too much code, getting a migraine, breaking more code and losing hair.

    In similar situations, many programmers will either offer to ‘entirely refactor (meaning, rewrite) the code’ or ‘just make it work’ (aka muddle through). These attitudes underly dubious beliefs, explicit and implicit.

    • The explicit belief that Order and Chaos cannot coexist, (let alone interact) within our codebase.
    • The implicit (and somewhat Luciferian) belief that this time we’ll get everything right.

    Don’t buy into this s**t. Use the sword.

    The Brothel

    Back to my code, here is what I wanted to do today. I am rewriting the ‘go back to main menu’ feature in Antistar. Yes, I could muddle through, but I won’t. Here goes.

    1. Destroying the game session is (almost) all we (should need) to do.

    I have a class named GameSession. This class is instantiated by a command (GameStart) and is meant to contain the game session (everything that goes on while playing) as opposed to the game container (the menus and other bits and pieces that frame the gaming experience).

    So I’m guessing deallocating the game session object is a good step towards going home.

    While many objects reference the session, most (all) of these are back-references from aggregates. Say we just called [session release], would [session dealloc] be called? Sadly no. It took a couple of calls to release to get dealloc to kick in. Not being the local reference counting expert, I use a little trick to get me out of trouble in these situations. We can set a breakpoint in an object’s [ retain] method, overriding it as thus:

    -(id)retain{

    return [super retain]; // set a breakpoint here

    }

    I find it convenient, although it is crude. I don’t keep this code after I find what I’m looking for.

    2. Everything must go

    It isn’t enough that dealloc be called onto the game session object. We want the whole hierarchy of objects owned by the session to ‘collapse’. I don’t have a clean implementation of [GameSession dealloc], so I’m guessing now is a good time.

    The idea is simple. All objects owned by the game session should get deallocated, unless proven otherwise — recursively.

    So I spent about three hours writing miscellaneous implementations of [dealloc] (I’ll explain later why I don’t do this upfront). Amusingly, after I finished I found the code crashing exactly as it had three hours before:

    1. The display link dispatches to my EAGLView
    2. My overlay view ‘ticks’
    3. Talkback display attempts using a zombie instance of the… …game session.

    So why is my EAGLView not being destroyed?

    1. Retained as a child of the main window.
    2. Retained by display link using EAGLView’s startAnimation method.
    3. Retained (and most likely, released again later) by a couple of system level thingies.

    Let’s ignore (3) for now. So practically this says we should remove the 3D view from the main window and unregister the display link callback. While it may seem obvious, it is altogether pleasant and reassuring to find about it this way, right?

    There we go:

    • EAGLView provides a (void)stopAnimation method (this is code provided by the big guns).
    • We have removeFromSuperView, or whatever it’s called.

    After adding this code to my MainMenuAction, I had a slightly more worrying occurrence as an auto-release pool attempted to deallocate the view a second time. This reminded me a couple of useful points:

    • When using NSZombieEnabled, we can find out the type of the zombie being accessed by checking the console, if anywhere.
    • self.myRetainedProperty = foo; will retain myRetainedProperty. myRetainedProperty = foo will not.

    After fixing this up, I could observe the following behavior when pressing the menu button:

    • The screen goes blank
    • The overlay view (ui controls) is still visible. Not much of a surprise. For better (and especially for worse), I use a UI view from a nib file for my controls. As it is, this view exists independently from the game session. It isn’t clean, but it isn’t really useful to ever get rid of it either. Notwithstanding I can press the menu button over again, causing an exception and demonstrating that, if we’re keeping a view after the game session has been discarded, we need to do some cleanup.
    • The game menu isn’t showing. Not a surprise either. The game menu shouldn’t be part of the view hierarchy while we’re playing, so I guess we’ll have to put it back.

    3. The final touch?

    I made a trivial interface, GameSessionListener:

    @protocol GameSessionListener <NSObject>

    -(void)gameSessionEnded;

    @end

    This lets me pass an instance of the game container to the game session, so after the game is over the container can put up the menu again.

    While this works, starting and exiting over and over causes bugs on the game menu. It looks like the view hierarchy interacts in unpredictable ways, as eventually the menu screen goes blank.

    But hey, that’s what the sword is for, right? :)

    Needless to say I went back to my code a few minutes later. UIViews don’t just go blank, do they? and that view had to interact with something. So I looked up whatever views (not many) are somehow shared between the game container and the game session. Then I found the view root  (a kind of custom thing, not the absolute view hierarchy root) was being over-released.

    What have we gained?

    In the previous version of Antistar, the game exit/re-entry process is fairly robust. Meanwhile, it involves a lot of cookery for no special reason other than me shying away from just saying ‘let’s tear down everything’. In theory, tearing everything down should be easy. In practice, if it’s not then we probably have an unsolved problem that’s not good being left unsolved.

    The ‘cookery’ occasioned hard to fix bugs. Not tearing everything down means having dirty objects lingering, leading to functional bugs. I haven’t run the new code through instruments and I’m bound to find leaks. Good point here. Leaks, unlike functional bugs, can be detected automatically.

    Not tearing everything down also defeats one of the useful applications of a so called game container. Running not just one, but several games under the same hat.

    So I started with a clear goal and solved the problem as I intended. I wanted to clear the game session by deallocating it, and this is what it does. What I did not intend to get over and done with today (yesterday, rather) is memory management. Yes, I feel I have a head start on this, but that wasn’t quite the issue here and I’ll look into it another time.

    Epilogue

    1. I didn’t go around analyzing this and that, eventually deciding that I should rewrite the whole whatchamacallit (don’t use the hydrogen bomb)
    2. I haven’t hacked up a quick patch (no biological weapons)
    3. I added code that’s useful, concise and clear and contributes functionality to my app (use the sword)
    4. I haven’t fixed or otherwise ‘improved’ anything that didn’t need fixing (don’t use the mace)
    5. I spent about 7 hours on this f***ing thing (have faith).

    A good place to start is Wikipedia’s Comparison of SVN clients. I skimmed through the list and retained a few solutions (my selection is arbitrary)

    • OS X native front ends: Cornerstone, SCPlugin (finder integration), svnX, Versions, ZigVersion
    • Java front ends: sdSVN, SmartSVN, Subversive, sventon, Syncro SVN
    • Other front ends: RapidSVN

    I was rather used to TortoiseSVN. Tortoise integrates well with the windows desktop although the SVN version isn’t flawless (been quite a learning curve to understand some of what it does, and how, and why…). Never mind, tortoise isn’t available on MacOS.

    Since I started developing on OS X, I used svnX. It’s free, but it’s nothing like Tortoise. XCode integrates SVN services and it’s OK to do simple operations, but it doesn’t substitute a comprehensive SVN front end.

    I’m testing SmartSVN right now. It feels great compared to svnX so far. However I’m kind of missing a nice desktop integration so before I drop the buck ($79, oh my goodness) I guess SCPlugin is next on my list.

    How XCode manages my files…

    Working with XCode doesn’t make it intuitive to keep the actual code base neat. What really happens is like this:

    1. You create files and add them to your project.
    2. You organize your files using groups. Groups are nice in a way. The downside, however, is that without care all files end up in the same folder.
    3. You put aside files you don’t want anymore (well, yea… happens to everybody, right)
    4. The files aren’t ‘project files’ anymore, but they’re still in your project folder and still in SVN.
    5. XCode’s SVN integration keeps track of these files like anything else. So we have these ghost files in the repo and in the project director(ies), and we don’t really know where they’re coming from, what they’re doing here and if we want to keep them or not.

    I feel annoyed with this situation – it’s not terribly annoying if we were only working with XCode, and that is exactly why it is annoying. I end up with scores of files that I don’t need, making checkouts heavier. I’m also having a hard time running other tools against my codebase. All the while everything looks perfectly neat inside XCode. And to perfect a rather diminishing portrait, the XCode proj. files aren’t anything easy like neat, humanly readable XML. More like porridge.

    But surely that is nothing to bear with. Objective-C doesn’t even support packages anyway.

    2011 will see Anime 3D SFX hard at work as we’re still developing the Antistar sequels and the JME conversion, to say nothing about future plans (why, we’re busy enough doing what we do and doing it now).

    While Antistar: Rising rallied hard fans, they are often prompt to note that they belong to an enlightened minority. Ay, a good game’s a good gift, so we decided to share Antistar with a wider audience, the 31st of December 2010 and the 1st of January 2011.

    Heuristically (if ever coincidentally), connoisseur iPhone review site iFanzine listed Antistar in it’s 2010 roundup. A select club where our heroine in pajamas coexists with Spiderman, Marblenauts and Lara Croft.

    Devil’s in the details still

    So what are we working on? Well… lots of technical stuff is going through. Notably, evil stuff muxing user experience and artwork. For example, I never wanted to make the ground flat and square, although it could *simplify* walking around and path-finding. So instead I wrote methods for path-finding on meshes, and following contours, so the controls will feel nicer and we actually gain artistic freedom, instead of stepping back.

    Another example is the blue kitten. Players (beta testers even) noted that the blue kitten doesn’t follow the player everywhere. It isn’t necessary to have the kitten around beyond chapter 3, but it’s nice. So because I don’t want the kitten to teleport auto-magically, I implemented path-finding to defeat moving platforms too.

    I wasn’t all satisfied with our custom 3D engine, or the game framework for all that matters. I thought all this lacked flexibility, and it turns out that the design of this game demands flexibility – no wonder considering this title is meant to push our codebase forward, versus relying on existing functionality.

    Quite a bit of work is going into avoidance / simple attack behavior too. And yes, again, all of this could be extremely simplified. But I don’t really want to do that. Why then, do these “small features” really add gameplay, isn’t it just a little bit of un-necessary polish?

    Don’t think so. First, I already explained that artwork gets tied easily to draconian constraints regarding the shape of the terrain. But there’s something that’s a lot more important going on here. If a game world doesn’t implement minimally robust physical and geometric constraints, there won’t be a way that this game world can develop rich system dynamics grounded into physicality. Truly, from this angle it doesn’t matter just now, or for the coming update.

    Well, just the beginning, is what it is.

    With a fine brush

    While a couple of pros are blessing the main character with their fairy hands, working on modeling and animation, I actually started redesigning and re-creating parts of the environment. I have a lot more flexibility on this side since I implemented the level editor. For now, I find the added element of freedom almost threatening. But somehow I’m getting fond of what used to be ‘just a design for a game’ and I feel willing to spend time ‘doing it over again’. I don’t want this to be just a bunch of platforms, move on and forget. So I guess even Klinnburg will look somewhat different in the next release. Later parts of the story will give us chance to unravel more of it’s mysteries too.

    Stepping stones in the myst

    Controlling a storyline doesn’t necessarily mean knowing everything in advance. I know fairly well what’s meant to happen in Antistar, up to Chapter XVI and beyond(!). I know it so well that I might change my mind about it. The same goes for game-play. It’s so easy to sketch ideas and settle on a plan, only to find out that we don’t like it anymore.

    So I guess the next Antistar release, however overdue, will be a surprise for our players… …and for us.