Adventures in Objective-C – Part 1

I’ve been trying to get my head around Objective-C and Mac/iPhone programming for the last month or so. At this point, I think I’ve got most of the major concepts down.

As an Object Oriented (OO) language, it bears a certain familial resemblance to Java, which I typically program in these days.

While I’m not going to say that Java is a “better” language, I do feel that parts of Objective-C are a capricious conglomeration of logic-unfriendly syntax.

It’s the implementation of these things that’s irritating. Obviously there’s a certain amount of familiarity and personal preference, but over this series of articles, I’ll highlight a few. I’ll start with a simple syntax example.

Generally in OO programming, you break things into programatic “objects”, which define the properties of an object and the actions that such an object could do.

In Java speak, these are properties and methods, in Objective-C they are properties and selectors. In Java you “call” a method, in Objective-C you “message” a selector. Same thing, different terminology. Clear as mud? Good, then let’s continue.

Typically, properties on an object are protected behind accessor method, such as “getXXXX” and “setXXXX” where XXXX is the property name. Sometimes these are called “getters and setters” – that’s in Java, of course, Objective-C calls them “accessors” and “mutators”. Objective-C also uses a slightly different convention. Mutators are still “setXXXX” but accessors are just “XXXX”, which can result in a little ambiguity as to whether you’re looking at the actual property variable or the accessor selector.

Java uses “dot-syntax” to refer to an object’s methods, so far example, if you have an object called “newton” and it has a method called “dropApple()”, you would access it like this:

newton.dropApple();

Objective-C uses square bracket syntax, so the same thing would be:

[newton dropApple];

…and if each one took a single parameter, they would look like this:

newton.dropApple(velocity);

vs

[newton dropApple:velocity];

It gets a little muddier when we move to two parameters.

In the example above, I’ve passed a variable called “velocity” which we’ll say is of object type “Speed”. Let’s add a second object type of “Height”, with an instance variable called “headHigh”

We would DECLARE the java method like this:

void dropApple(Speed incomingSpeed, Height incomingHeight) {

…. do stuff

}

and call it like this

newton.dropApple(velocity, headHigh);

Objective-C would be declared like this:

(void)dropApple:(Speed *)incomingSpeed dropHeight:(Height *)incomingHeight {

…. do stuff

}

and called like this:

[newton dropApple:velocity incomingHeight:headHigh];

Here’s my first irritant, Objective-C selectors use named parameters – which I like better than Java, but only on the second and subsequent parameters. The first is identified by the name of the selector. It’s just a mixed-bag inconsistency. I hate inconsistencies in my programming languages.

This same system also helps cause Objective-C messages to tend to be very long.

Java and Objective-C also share another trait, that being if a message/call returns an object, you can then, in turn message/call that object immediately without passing it through an unnecessary intermediary object variable.

Let’s say we’re somewhere inside an object that is running active code – like a program. I can always reference back to myself with the special keyword “self”, so if my program has a property of type Person, and a Person object has a property of type “phoneNumber” and a PhoneNumber has a method that returns a formatted representation of the number, we can get to that formatted string in java like this:

self.getPerson().getPhone().format();

Self being an object with a getPerson() accessor that returns a Person, which in turn has a getPhone() accessor which returns a Phone, which in turn has a format() method to return a pretty string. It’s not uncommon to see these things strung together 4 and 5 levels deep inside Java code, and it’s a bit difficult to read, but convenient, and sometimes a lot better than assigning each step to a new variable, like this:

Person aPerson = self.getPerson();

Phone aPhone = aPerson.getPhone();

String aString = aPhone.format();

How does Objective-C handle this? Like this:

[[[self person] phone] format];

Simpler, right? Yes and No. It’s irritating. Why? Because you have to know, in advance, how many layers deep you are going so that you can put the right number of square brackets on the left. If not, you have to come back later and add them, which really “breaks the stride” of typing. It may be less letters to type, but it takes longer to type.

Ah, but along comes Objective-C 2.0 with a “solution” to this: Dot-Syntax!

Oh, but it isn’t the same as Java’s dot-syntax. Objective-C’s dot-syntax only applies to properties, not selectors. (Actually, properties are selectors, you’re not seeing the actual variable, but these are special) That means you can do this:

self.person;

or

self.person.phone;

but not

self.person.phone.format;

instead it would be:

[self.person.phone format];

Why is this a problem? You don’t always know if something is a “property” or “selector”, and since the IDE (XCode in this case) helps fill this stuff in from it’s calculated list of available options, it promotes a certain natural “coding laziness” by letting the IDE do the work of remembering names for you.

So you start typing “self.pe…” and about that time it suggests “self.person”, so you hit the arrow and continue typing “.ph…” and it breaks in again and suggests .”phone” so you hit the arrow to accept and then you start “.format” and nothing happens, then you realize, “oh, it’s not a property”, so you go back and delete the period. That’s bad typing technique. And, then, of course, you have to go back to the beginning of the clause to add a “[” and the end of the line to add “]”

I know, I know. “Gripe, gripe, gripe, gripe”

Next time (probably) “Why there isn’t a consistent method for delegates, actions and ad hoc delegates”

15 thoughts on “Adventures in Objective-C – Part 1”

  1. Whilst I haven’t your experience with Java, I have learned it first and so it’s also my point of reference in coming to C and Objective-C.

    At first the syntax difference with both C and Java threw me (I always used this in Java but it has to be self in Objective-C, the square brackets, the + and -, the nil, the YES/NO) but there are some things I really like, and messages and selectors are one of them. This is mostly because I think categories are cool, and informal protocols much more flexible than interfaces (and I like how you can implement the equivalent of an interface by making a formal protocol). Dividing the business of “calling a method” into its components makes sense to me.

    On the other hand, some of the (mostly version 2.0) stuff does seem irritatingly inconsistent. For example, the dot notation. It wouldn’t be so bad if I wasn’t used to it in Java, but to have something so similar yet unexpectedly different is quite off-putting. Especially when getters, as you say, are named the same as ivars, but the setters aren’t and yet the only way to differentiate them in the dot notation is the context. Also, though properties are a neat way of simplifying the definition of getters and setters, it does seem to make it all a bit more opaque.

    Incidentally, I learned getters and setters as accessors and mutators for some reason, only to find them collectively referred to as accessors later on. I guess this is one thing that everyone does differently…

    I’ve got used to the square brackets now. I like the way there are class and instance methods (rather than the static business in Java) and that classes are objects. And I don’t find myself slower, partly because I never got to be that fast at Java and partly because I find Xcode to be quite helpful in a number of ways including helping me be a lazy coder! I also like interface builder generally, so overall I’m preferring it to Java so far.

    Of course, I haven’t actually done anything but exercises with it yet, so the real test will be in the application.

  2. Whilst I haven’t your experience with Java, I have learned it first and so it’s also my point of reference in coming to C and Objective-C.

    At first the syntax difference with both C and Java threw me (I always used this in Java but it has to be self in Objective-C, the square brackets, the + and -, the nil, the YES/NO) but there are some things I really like, and messages and selectors are one of them. This is mostly because I think categories are cool, and informal protocols much more flexible than interfaces (and I like how you can implement the equivalent of an interface by making a formal protocol). Dividing the business of “calling a method” into its components makes sense to me.

    On the other hand, some of the (mostly version 2.0) stuff does seem irritatingly inconsistent. For example, the dot notation. It wouldn’t be so bad if I wasn’t used to it in Java, but to have something so similar yet unexpectedly different is quite off-putting. Especially when getters, as you say, are named the same as ivars, but the setters aren’t and yet the only way to differentiate them in the dot notation is the context. Also, though properties are a neat way of simplifying the definition of getters and setters, it does seem to make it all a bit more opaque.

    Incidentally, I learned getters and setters as accessors and mutators for some reason, only to find them collectively referred to as accessors later on. I guess this is one thing that everyone does differently…

    I’ve got used to the square brackets now. I like the way there are class and instance methods (rather than the static business in Java) and that classes are objects. And I don’t find myself slower, partly because I never got to be that fast at Java and partly because I find Xcode to be quite helpful in a number of ways including helping me be a lazy coder! I also like interface builder generally, so overall I’m preferring it to Java so far.

    Of course, I haven’t actually done anything but exercises with it yet, so the real test will be in the application.

  3. I’m doing little more than “exercises” myself at the moment, but I’ve got a simplistic (but not so simplistic it doesn’t have challenges) target iPhone program I’m working on.

    It’s got tab controllers, navigation controllers, data entry, custom modeled objects… and so far, I’ve only completed about 50% of it, and, more tellingly, I’ve restarted it from scratch about 3 times. πŸ™‚

    So, I’m far from familiar with Objective-C, and more than willing to admit I’m biased, through familiarity, towards Java’s syntax.

    Helpful as Xcode is with syntax assist, I’m going to give the node to Eclipse, for putting more information at your fingertips. That’s also playing a factor in my ease (or stumbling around) in picking up Objective-C.

    That reminds me, I should talk a bit about Stanford U’s iPhone class. Time for a post.

  4. I’m doing little more than “exercises” myself at the moment, but I’ve got a simplistic (but not so simplistic it doesn’t have challenges) target iPhone program I’m working on.

    It’s got tab controllers, navigation controllers, data entry, custom modeled objects… and so far, I’ve only completed about 50% of it, and, more tellingly, I’ve restarted it from scratch about 3 times. πŸ™‚

    So, I’m far from familiar with Objective-C, and more than willing to admit I’m biased, through familiarity, towards Java’s syntax.

    Helpful as Xcode is with syntax assist, I’m going to give the node to Eclipse, for putting more information at your fingertips. That’s also playing a factor in my ease (or stumbling around) in picking up Objective-C.

    That reminds me, I should talk a bit about Stanford U’s iPhone class. Time for a post.

  5. The other thing that I’ve found to be a big difference is the lack of modifiers for Objective-C. You can miss a method out of the interface, but it can still be accessed by anything that knows, or guesses, at its name. And KVC can go deeper still, getting at your ivars directly. Whilst this may be very useful in practice, it seems to break encapsulation, and I’d have imagined it would ultimately cause more problems… It seems odd.

    I’m following Stanford U’s class, though I’m only just beginning assignment 3. Look forward to that post.

  6. The other thing that I’ve found to be a big difference is the lack of modifiers for Objective-C. You can miss a method out of the interface, but it can still be accessed by anything that knows, or guesses, at its name. And KVC can go deeper still, getting at your ivars directly. Whilst this may be very useful in practice, it seems to break encapsulation, and I’d have imagined it would ultimately cause more problems… It seems odd.

    I’m following Stanford U’s class, though I’m only just beginning assignment 3. Look forward to that post.

  7. I’m not sure about the implementation of KVC’s, but I suspect they’re much like @property generated getters and setters – they probably generate an unseen method that’s called, so it may be that it is doing the proper encapsulation “under the hood” as it were.

    Seems like (and my study of Cocoa on the Mac is hazy) that KVC isn’t implemented (or at least not in the same fashion) for CocoaTouch.

    If I recall correctly, under an NSSlider, you could assign a binding between the value property of the slider to an ivar on the controller class and get direct updates between one to the other.

    A UISlider, on the other hand along with the other UIControls (unless I’m missing something) doesn’t allow you to bind between properties of the control and properties on the controller. It only allows you to bind the control object itself to an ivar representation of the same control class property on the controller.

    Subtle difference, I suppose…

    It seems like I read somewhere that the xib files are actually being used to instantiate the property classes in the controller that are designated IBOutlets, so it’s not so much a binding between two objects, but actually using an alternate mechanism to instantiate the object. (Or perhaps it just sets the pointer to the same address?)

  8. I’m not sure about the implementation of KVC’s, but I suspect they’re much like @property generated getters and setters – they probably generate an unseen method that’s called, so it may be that it is doing the proper encapsulation “under the hood” as it were.

    Seems like (and my study of Cocoa on the Mac is hazy) that KVC isn’t implemented (or at least not in the same fashion) for CocoaTouch.

    If I recall correctly, under an NSSlider, you could assign a binding between the value property of the slider to an ivar on the controller class and get direct updates between one to the other.

    A UISlider, on the other hand along with the other UIControls (unless I’m missing something) doesn’t allow you to bind between properties of the control and properties on the controller. It only allows you to bind the control object itself to an ivar representation of the same control class property on the controller.

    Subtle difference, I suppose…

    It seems like I read somewhere that the xib files are actually being used to instantiate the property classes in the controller that are designated IBOutlets, so it’s not so much a binding between two objects, but actually using an alternate mechanism to instantiate the object. (Or perhaps it just sets the pointer to the same address?)

  9. Before that comment comes back to haunt me I ought to delete it. πŸ™‚

    Totally missed on that one. The small amount of work I’ve previously done in Cocoa Objective-C was entirely with KVB – Key-Value Binding – and I’d not touched KVC/KVO.

    Just got around to watching the Stanford video that covered that topic and, while I completely missed the distinction between KVC/KVO and KVB, I was at least right that KVB does not exist in Cocoa Touch.

    Through reflection in Java you can manage KVC. Not sure about KVO – never had any call to use it. I’ve never had much use for KVC in Java, except when being handed unknown-typed objects. I guess to remains to be seen when it will be handy in Objective-C.

  10. Before that comment comes back to haunt me I ought to delete it. πŸ™‚

    Totally missed on that one. The small amount of work I’ve previously done in Cocoa Objective-C was entirely with KVB – Key-Value Binding – and I’d not touched KVC/KVO.

    Just got around to watching the Stanford video that covered that topic and, while I completely missed the distinction between KVC/KVO and KVB, I was at least right that KVB does not exist in Cocoa Touch.

    Through reflection in Java you can manage KVC. Not sure about KVO – never had any call to use it. I’ve never had much use for KVC in Java, except when being handed unknown-typed objects. I guess to remains to be seen when it will be handy in Objective-C.

  11. superb article.. brings out my emotions too. Coming from a C background, when I tried to get beyond the helloWorld in Obj-C by adding a function that needed two parameter, I remained in the mud of “named parameters” in function arguments for one week before I could properly get my head wrapped around (the insanity?) the convention. And two months later, it still befuddles me from time to time while debugging. Sigh!!

  12. superb article.. brings out my emotions too. Coming from a C background, when I tried to get beyond the helloWorld in Obj-C by adding a function that needed two parameter, I remained in the mud of “named parameters” in function arguments for one week before I could properly get my head wrapped around (the insanity?) the convention. And two months later, it still befuddles me from time to time while debugging. Sigh!!

  13. Terrific article. I have just started Objective C and so glad I found this article. The bit about accessors and mutators really helped me out- thanks!

Comments are closed.