tisdag 2 juni 2009

Objective-C... yet another programming language?

Just recently installed XCode on my mac in order to develop applications for my iPhone. The first thing I realized was that I needed to learn yet another programming language. Just another syntax, or does Objective-C actually bring something new?

It turns out Objective-C (which is a language derived from C, similar to C++, but still very different) has one feature I haven't seen before. First of, instead of calling a method on an object, your send a message to it. It's almost the same, but also requires you to pass along named parameters (which means more code to write, but easier to read). The new and cool feature appears when you want to send a message to an object, which should return a value, when the object turns out to be nil.

MyClass* myObject = nil;
if ([myObject getValue] == 0.0) {
// myObject getValue retuned 0, OR myObject is nil

So when executing this code, as opposed to how normal programming languages handles it, it doesn't crash. It simply returns 0.0 if the expected return type is a number, or nil if the expected return type is a pointer to an object. This also works for functions returning nothing (i.e. void), sending a void returning message to a nil object will simpy do nothing.

In for example C# you always have to do null checks all over the code, in order to verify your object isn't nil.

I'm not sure I like it or not, but if you learn to think "pure Objective-C" then perhaps this can be used as an advantage! I'm looking forward to learning Objective-C further, and to adapt these new concepts!

I'll let you know when I've published my first iPhone app :)

1 kommentar:

Olof Bjarnason sa...

Haha that's quite unorthodox. Have to rethink that when the clock is not this close to midnight :)