iOS Cool Stuff – Immutability by default

This is the first entry in the iOS Cool Stuff series. As the opposite of the iOS Pain Points series, it will talk about some of the nifty parts of iOS development – the kind of stuff I wish I had in the .NET world.

One very cool feature of Objective-C is that data structures tend to be immutable by default. Your standard array data structure, NSArray, is immutable. If you want a mutable version, you have to specifically ask for NSMutableArray. This is the way things should be.

In .NET, immutability is a bit harder to come by. Sure, strings are immutable, but what about collections? Sure, you can use the ReadOnlyCollection<T> wrappers, or expose an IEnumerable property, but neither of these options is as slick as simply having built-in immutability.

iOS Pain Points – No strongly-typed collections

This is the first entry in the iOS Pain Points series. This series will detail some of the downsides and pitfalls of iOS development, and will include various aspects of Objective-C, Cocoa, and XCode.

Today’s iOS Pain Point is the lack of strongly typed or generic collections. .NET developers eat, sleep, and breathe generic collections, and this is something I found lacking when working with iOS.

Purists may¬†argue that due to Objective-C’s dynamic nature, there is no need for strong typing, but the reality is that it can prevent bugs. Consider the following code:

NSArray* names = [[NSArray alloc] initWithObjects:
                      @"Bob", @"Fred", @"James", "@Mike", @"Kyle", @"Steve", Nil];

It compiles, but crashes when you run it. And this is not a contrived example; it’s a bug I ran in to while first starting with Objective-C. Granted, improved syntax coloring in XCode could make this bug immediately obvious, but it’s still a bug that never should’ve existed.

If that’s too easy and obvious for you, consider this code snippet:

-(void) FireBullet
    Bullet* bullet = [[Bullet alloc] init];
    bullet.position = [self calculateBulletPosition];
    [bullets addObject:bullets];

-(void) Update
    for(Bullet* bullet in bullets)
        [bullet updatePosition];

This compiles fine too, but again, it crashes with an ‘Unrecognized selector’. And although it’s a trivial error that is easy to fix, it is, as before, an error that never should’ve existed in the first place.


Welcome to my blog!

This blog will chronicle my journey into the world of iOS development. My goal is to release one new application per month, and blog about the trials and tribulations of the process. I suspect that this may not be possible some months, either due to technical difficulties, lack of time, or lack of ideas… but one app per month is the target.