Angelo DiNardi

Doin' shit on the web since 1995.

Objective-C messages, checkboxes and booleans

24 January 2008

So in the past week or two I’ve started a new project using Objective-C and Cocoa for OS X. If you want a good set of frustrations, here it is. Honestly.

It is hard, I mean really hard, to break out of the C++ style programming mindset. It really is automatic that when I think I need to call “doSomething” on “magicObject” to type: magicObject.doSometing(blah). Instead I now need to type: [magicObject doSomething:blah]. It isn’t hard or overly complex – it is simply different. It isn’t how years of C++ style programming have trained my brain. And they’re not function calls, they’re messages. You send a message to an object and hope to God it does something meaningful with it.

And then there’s booleans. For whatever reason they strayed from TRUE and FALSE and opted for YES and NO. I can agree that most of the time thinking of things in YES and NO can make more sense – but it is once again hard to break habits. Of course figuring out that it is YES/NO was a pain enough. I should really find a few more good guides before continuing (and then I’ll need the patience to actually read them…).

And finally a checkbox in a Cocoa table view component. Nothing really complex about it by itself but once you layer on the fact that the checkbox itself uses NSOnState/NSOffState constants which map to integers. But the table view gives you an id (dynamically typed) object when something changes. I was consistently crashing my app when I attempted to use this value as just an integer. Reading whatever documentation I could led me nowhere. I finally found some random items on the internet that finally led me to try: if ([anObject intValue] == NSOnState) { Well that works. How the hell should I know to ask the parameter anObject for intValue. Honestly – if there’s a document somewhere in the Apple Developer docs that would have hinted at that I’d like to know – that way I know what to look for next time.

Returning the value for the checkbox when the table view asks for it was equally frustrating. I figured I’d just return NSOnState/NSOffState. Haha! No. You need to return an object so I had to figure out what it wanted and how to cast it. Finally: value = [NSNumber numberWithInt:NSOnState]; Not exactly what I figured. Creating an NSNumber object and seeding it with NSOnState.

As with any new language and technology there’s a lot of things that people used to it assume and outsiders struggle to figure out. I’m hoping to overcome the struggling soon. Until then, expect a few more posts outlining my struggles.