Objective-C Is Still C (Not Java!)

October 30, 2011 — 10 Comments
Do you have your C book?

Do you have your K&R book?

October 2011 saw the passing of giants:

Simplicity. Power.

  • Steve Jobs. You work with his toys everyday.
  • Dennis Ritchie, inventor of the C programming language, co-inventor of Unix. You work with his stuff everyday (but we forget that).
  • John McCarthy, inventor of Lisp. We use the descendants of his invention every day (without realizing it).

By his vested Interweb powers, Tim O’Reilly has declared that October 30 be Dennis Ritchie Day. In his honor, I wanted to write something that’s been bothering me about the way people are learning Objective-C:

Objective-C is still C !

As a programmer, your most fundamental tools are the programming languages you use. If you don’t know the tool, you simply won’t be able to express things with both simplicity and power. And while I’m glad for the sudden interest in Objective-C, I’m troubled that so many people treat it like some kind of bastardized Java. They jump straight into messaging syntax and Foundation classes, while bypassing the powerhouse that’s available to them.

That powerhouse is the C language.

Unlike other offshoots of C, Objective-C is C. In fact, it’s a strict superset of C. This means that anything you can do in C, you can also do in Objective-C. Or to flip that around, if there are pieces of C you’re not familiar with, you’re missing out on a tool that powers… well, nearly everything.

A concrete example

Let’s look at a concrete example: Say you have a UITableViewController. Table cells are often very similar. Let’s say the only difference between cells is

Amount of code executed to set up this data structure: Zero.

  • the text displayed
  • the selector to invoke when tapped

“That’s an opportunity to reduce all this code into something data-driven,” you say. Well done! …Oh, but the approach many might choose is to put this information into NSDictionaries, in an NSArray. And you have to encode the selectors as NSValues. And you have to do all this at some known time like -viewDidLoad.

NSArray *cellInfo = [NSArray arrayWithObjects:
    [NSDictionary dictionaryWithObjectsAndKeys:
        @"Cell 1", @"text",
        [NSValue valueWithPointer:@selector(foo)], @"selector",
        nil],
    [NSDictionary dictionaryWithObjectsAndKeys:
        @"Cell 2", @"text",
        [NSValue valueWithPointer:@selector(bar)], @"selector",
        nil],
    nil];

Whoa there cowboy, let me save you some trouble. C to the rescue! First, define a struct to hold information about each cell:

typedef struct {
    NSString *text;
    SEL selector;
} MyCell;

Now define a static array of that type.

static MyCell cellInfo[] = {
    { @"Cell 1", @selector(foo) },
    { @"Cell 2", @selector(bar) },
};

Amount of code executed to set up this data structure: Zero. Zip. Nada.

Now think about how these different data structures will be read in -tableView:didSelectRowAtIndexPath:. Assume we’ve already set NSUInteger row = [indexPath row];

  • The Foundation version passes the row to -objectAtIndex: to get a dictionary. That’s one method call. It passes @”selector” to -objectForKey: on the dictionary, to get an NSValue. That’s another method call. Finally it calls -pointerValue on the NSValue to retrieve the selector. That’s a third method call. Or…
  • The straight C version retrieves the selector with cellInfo[row].selector. That’s just a memory address calculation.

Simplicity.

Power.

Get the book

If you’re an old-timer, dust off the old K&R, in honor of Dennis Ritchie. Amazing, for such a short book.

But if you program Objective-C and don’t own a copy of The C Programming Language, do yourself a favor: Buy one today. (Remember to expense it.) You’ll step into a time machine and go back to 1978. It may not be fresh, but it sure is relevant. Go through the exercises. Remember:

Simplicity.

Power.

Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, I only recommend products or services I use personally and believe will add value to my readers. I am disclosing this in accordance with the Federal Trade Commission’s 16 CFR, Part 255: “Guides Concerning the Use of Endorsements and Testimonials in Advertising.”

If you enjoyed this article, get email updates (it's free).

Email Address:

10 responses to Objective-C Is Still C (Not Java!)

  1. Hi Jon,
    Very nice post. Like especially the examples that you provided. Thank you!
    Have a good evening,
    -Herman

  2. Hahah, nice post. I’ll have to order my copy today ;)
    I think you are right Jon, it is easy to forget that you have all of C available to you. I know I have approached Objective-C with the mindset that you mentioned… “straight to the messaging syntax and Foundation classes”. I think that this is in large due to seeing parts of the API that are extremely elegant and straightforward to use, and I’ve just accepted that what I need to accomplish would/should be done in an Objective-C way. However, your example has caused me to pause and realize that there is much more to learn than I thought… which is cool. It isn’t bastardized Java, you have more available to you than you may first realize.
    Thanks for the post and take care,
    Cory

    • Of course, I’m not putting down the Foundation classes, or the beautiful elegance of the Objective-C messaging runtime. It’s really a matter of the right tool for the right job. “If you’re holding a hammer, everything looks like a nail.”

  3. Most people I know use subclassed NSManagedObjects in conjunction with core data rather than a dictionary. If the project doesn’t require Core Data, yours is a beautiful & elegant solution.

    • Thanks, CJ. I may be odd, but I have yet to delve into Core Data. (I haven’t yet worked on a problem for which it is the solution. Odd, I know.)

  4. Putting Objective-C Pointers into a struct is verboten in ARC.

  5. @selector is not compile time constant, it can not go into static struct initialization

Leave a Reply

*

Text formatting is available via select HTML.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> 

Have you Subscribed yet? Don't miss a post!