You are currently browsing the tag archive for the ‘Objective-C’ tag.

Objective-C can be quite verbose, especially when handling nested data – there is no simple associative array indexing of the kind found in PHP, Ruby etc.

ObjC : verbose : id value = [map objectForKey:@”key”];

Using atx functions : concise : id value = at(map, @”key”);

This comes in very handy for deeply nested json data trees, where you might want to index a multidimensional array or nested tree – vis :

id pop = at(at(at(stats, @”USA”), @”NewYork”), @”popn”);

Not quite as simple as pop = stats[“USA”][“NewYork”][“popn”]; but more readable than several objectForKey’s.  Note, I propagate the nulls up so if an item is not found at any level, it can be checked once at the top level without crashing the app.

The small suite of related functions can be found at google code here, under BSD licence – http://code.google.com/p/xathack/

enjoy.

Surprisingly for a lisp programmer I’m enjoying developing iPhone apps.  My clients Melbourne GigGuide app is doing well and I’m much happier after moving from XML to JSON format for my data feeds.

Verbose

Objective-C is simpler than C++ and closer to a scripting language in some ways.  The UIKit api itself is well designed, despite having verboseMethodNames.  This isn’t so much an RSI problem – the XCode editor does a nice job of guessing and auto-complete, while being non-intrusive – but its a lot of text to read which tends to obscure the idea behind the code.

Deeply nested JSON trees

Today I found myself chaining down a few levels of nested json objects, and decided I needed a much shorter syntax.

Many scripting languages have an associative array lookup syntax like someMap[“key”], and these can be chained.  In Obj-C, to access an NSDictionary you use objectForKey:@”key”.

at() Hack

I wanted something shorter so wrote this small hack  –

id at(id ob, NSString* k)
{
 if (ob && [ob isKindOfClass:[NSDictionary class]])
     return [ob objectForKey:k];
 return NULL;
}

Now I can index down several levels into a json tree easily, like this :

id obShops = at(at(at(json, @”Boutiques”), @”London”), @”EastEnd”);

Not as succinct as square brackets, but saves a lot of typing… enjoy