Groking Objective-C for Modern Day Programmers

Here’s what I think trips up solid programmers about the Objective-C language.

One of the nice things about Apple’s OS X for the Macintosh is that they include a free copy of Xcode, a very sweet graphical development environment allowing developers to make Cocoa applications using Objective-C.

The problem is, jumping straight into the Cocoa framework, even with tutorials, can be a daunting task if you’re not comfortable with Objective-C.

Yes, there are a number of books out there, but today I stumbled across, quite by accident, a fairly decent tutorial on Objective-C.

That got me thinking. In a world where we can easily pick up C++, C#, Java, Python, and Ruby… what is it about Objective-C that makes it hard to follow? Here’s what I think the major stumbling blocks are:

Notation Preconceptions Clouding C as the True Origin
In the classic examples, we think in terms of an object with methods and members, often using a dot-like syntax. As such, we tend to want to force fit Objective-C’s way of doing thing into some preconceived mold, and when the syntax doesn’t express that, things fall apart.

The Solution: Back off. Drop all the way back to C. Consider Objective-C nothing more than a well written pre-processor to useful object like extensions to the C programming language. Sure your implementation may very well be a compiler, but don’t think in those terms.

You’ve Got Classes Wrong
You’re used to thinking that a class is a data type. Don’t, think of it as a thing. In fact, Objective-C only needs to know a variable is a class, it doesn’t need to know which one or what it exposes. Classes are things whose primary role is to produce instances.

It’s Supposed To Feel Like Macro Magic
When you’re working on the guts of a class, you’ve got a lot of blocks that start with @class, @interface, @end, …. If it feels like something’s acting as a pre-processor and is converting that stuff into data structures and functions, it is. You’re not going to see pretty syntax that feels integrated into the language.

Hard Crunchy Outside, Soft Gooey Inside
A class exposes an interface, this is how the outside world sees and interacts with your class. Specifically, its your methods. And they’re all public. Get over it. Test. Only your members can be protected or private.

Remember, there are class-things and instance-things.

Declarations and Definitions
With C, there’s declarations that define the type and are often used for forward references; additionally, there are definitions where the memory is actually allocated and a value assigned.

Objective-C objects work similar. There’s an @interface / @end block that describes the object, its members, and its methods. And there’s an @implementation / @end block that actually contains the real code.

void * and id
A pointer in C, indicated by a *, points at a data type. If the pointer is given a void type, the compiler does no type checking. You know this. The id type holds a object, regardless what type it is.

Messages are not Methods
Any object can be sent any message. An object maps a message to a method. However, if there’s no mapping available, it can be handed to a general handler for the object — which can be clever and analyze the message.

Extended classes… and instances.
The mapping between message and method can be extended; you can think of it as subclassing. However, it’s possible to extend an instance. Meaning, a class might not respond to a message, while instance A does and instance B doesn’t.

Categories
Because messages are bound late to an object, and the magic is done with data structures rather than types, it’s possible to create a collection of methods and add them to a class, even pre-existing ones you don’t have source code for.

Protocols
A protocol neither exposes an interface, nor does it provide an implementation. It is simply a named collection of method signatures which is attached to classes. Because any message can be sent to any object instance (or class), it is helpful to be able to “ask” if certain messages will be honored; that’s what protocols are for.

It’s Not Named Parameters
The syntax of a method may look odd, primarily because parameters appear to have additional text:
-(void) rotate:(String *)shape clockwise:(float)degrees;

In many modern languages, a signature can be overloaded. However, go back to the trick “What Would Macros Do?” In this case, any text that appears in front of a parameter is not a named parameter, but part of the method name. The above method would be the logical equivalent of void rotate_clockwise( String *shape, float degrees ) in raw C.

Constructors / Destructors
In today’s languages, performing a new allocates memory and initialized the object. Objective-C splits these into two discrete operations; this allows you to allocate memory from different heaps, as well as deferring expensive initializations – no bogus empty constructors here.

Note, you are also responsible for calling the superclass’s init, before doing your own init. If you have a method to deallocate the object, when done you need to call the superclass’s deallocation routine.

C requires you to take on more responsibility and pay attention to order; Objective-C classes require the same amount of vigilance.

Extra Data Types
Objective-C provides some helper data types, but some of them are tied quite strongly to the messaging framework.

Found: The Best iPhone Development Book So Far

Want to write your own iPhone applications but Objective-C, XCode, Interface Builder, and the steep learning curve of Cocoa getting in the way? Have I found the book for you.

Warning: long and geeky post follows — iPhone wanna-be developers, read on!

Beginning iPhone Development - Exploring the iPhone SDKI’ve found it, finally, the best iPhone development book so far! Read on to see why.

Fairly recently, I decided to turn my attention to native iPhone application development, but I found the arena a little sparse when it comes to what I’d call good documentation.

For some perspective, I’m a software developer of 20+ years with background in Unix and Windows; I’m very well versed in C, C++, C#, and Java, among a good number of other higher-level languages, having produced a number of enterprise applications.

You’d think that picking up Objective-C and the Cocoa Touch frameworks would be a fairly simple task. However, the moment you step foot into the pool, you’re get a cold shock at how much you don’t know and it can feel daunting enough to want to retract back to familiar territory.

Don’t give up. It is easy.

Looking forward into the unknown presents a much more gloomy impression than when you’ve taken a few steps and looked back to see just how far you’ve come and in such a short period of time.

Here’s what’s happening: The Apple Frameworks represent a large and mature collection of some impressive code. The closest experience I’ve felt to it, and this is admittedly a horrible analogy, is Ruby on Rails.

With Rails, there’s so much going on by convention that you have to sling very little code to get impressive things to happen. This makes it hard to understand: there is no code to trace.

Same way with the Apple Foundation classes that are based on NeXTSTEP — a lot is handled for you, and often in new ways you might not have thought about because of limitations of other platforms, so that very little code is required to do something quite impressive. The problem is figuring out what that code is you’re supposed to write, and more importantly how’d you know to go about doing that in the first place. Hint: knowing the Foundation Framework is important to understanding the Cocoa Touch Framework.

This leaves one in the lurch that the sample code appears rather sparse, and the framework documentation overwhelming, with little guidance on how all the pieces fit together into a simple, cohesive whole. The problem is all too common.

My biggest gripe with many frameworks, especially Java and it’s auto-generated documentation, is that all you’re really presented with is a list of method signatures with very little discussion about what they do, purpose and limits to the input values, discussions of side effects, the importance of call order, and so forth. With other languages, you’re lucky if you can find the header file to include or the library file to link against. It’s all just expected that you somehow know this, and that doesn’t work when you’re learning a framework, though it’s fine if you just need a reference.

Apple’s online documentation is certainly comprehensive, but the reality is you’re going to be watching videos and reading tons of documentation, picking up crumbs of useful bits as you go. The cohesive moment of comprehension will come, but it will be a long and slow ride. You want something faster.

If you’re learning Objective-C at the same time, the ride is extra bumpy, because not only are there just a few language extensions sitting on top of C, but the ObjC library is actually doing some clever work that you want to know about, and this has additional implications because there’s a lot of convention going on as well. Further obscuring things is the fact that, due to historical reasons, the terminology you are most likely already familiar with doesn’t map nicely. A nice look under the hood solves this. Objective-C isn’t just some new keywords, it’s new application behavior.

What’s Wrong With Other iPhone Books At The Moment
As of early 2009, you’re going to find few iPhone books out there. Most of what exists is for the hacked version of the iPhone, and while that may even sound useful, the tearing apart of the SDK is rough and incomplete, not to mention the implementation to call is painful. This just isn’t applicable to the real world constraints of native mode development.

Think you can get by with a slightly out of date copy of a Cocoa book? Think again. The UIKit framework is just different enough that your approach needs to be slightly different. Tight, efficient, resource management becomes very important.

Also, unless you already know and understand Interface Builder, it can be a hard time following along when your book doesn’t match your software version. Apple keeps modifying Interface Builder, making it better, but the changes can come across as so dramatic, interface-wise, that to the new comer it looks like a totally different application each revision. Once you “get it” the sweeping changes are cognitively transparent. The iPhone SDK includes, you guessed it, a new XCode and Interface Builder.

What few modern iPhone books there are out there jump straight into a technical feast of SDK details, leaving the reader with a learning curve that’s as vertical as a brick wall.

What’s needed is a book that introduces only what you need to know, when you need to know it, explaining tips and tricks along the way, delving into the philosophies of why things are the way they are, what the developers were thinking, how the frameworks are structured, what the conventions are, and when those conventions aren’t followed. And, instead of showing you the end solution all refactored into a neat package, take the long way, when needed, to introduce you to what’s going on and then evolve into the optimal solution.

I’ve Found Such A Book!
The book, by Apress, is called Beginning iPhone Development – Exploring the iPhone SDK by Dave Mark and Jeff LaMarche. This book is about the fundamental concepts you need to understand in order to make the frameworks do their magic.

Its tutorials are very well constructed, easy to follow, and are specifically designed to teach the framework in such a way as you understand what’s going on and learn to fish for yourself.

This is in stark contrast to substandard books that merely cover a framework’s capabilities with cut’n’paste examples that have little bearing to real applications. This alone gives is five out of five stars by my standards.

My only complaint is a minor nit that there are a small handful of typos, and unfortunately, they happen in the code examples. However, they’re glaring, and you won’t get tripped up by them. (For example, on page 85, the tutorial is about UIImage. And, UIImage appears four times in a six line sample. The first one, however, says “jmUIImage” and the indentation is off. It looks like a macro expansion, a note, or the mangled initials of one of the authors. The code won’t compile with it, and it’s obvious from context what it should be.) To me, this is forgivable. Especially since it’s rare.

Tagging 1430216263I want to show you something.

I have a habit of tagging my books when I find an exceptional piece of information that I haven’t found elsewhere. I give a book high marks if it earns somewhere between three to seven tags, as the majority of my collection never gets any tags. Tagging, for me, is not note taking — it’s rare event.

I think the picture speaks for itself.

For Example…
So, at this point, I present for my own edification and future reference, some of that tagged content. Who knows, maybe something you see here might just get you traction on the learning curve.

– In Objective-C, colons are a legal character of the method identifier, they are not syntactic sugar.
– Even though a number of macros translate to nothing, void, zero, or null under the hood, their presence provides important hinting for data types and method calls.
– The NIB’s File’s Owner is a place holder for the class that loaded the NIB file.
– The NIB’s First Responder is the object the user is currently interacting with.
– The application icon is a 57×57 .png file, see Info.plist’s Icon File.
– The iPhone specially optimizes .png files so this is the best format.
– Reset the iPhone Simulator by deleting its directory from ~/Library/Application Support
– You want to use @property (retain, nonatomic) as often as possible.
– Interface Builder uses your defined accessors to properties, which use retain; that means you do need to deallocate Interface Builder objects, even if you didn’t instantiate them.
– There are four control states on a control, often you want UIControlStateNormal.
– Learn to use retain/release, there is no garbage collecting on the iPhone.
– It’s better to init/release than using factory methods; factories use autorelease pools, and while this will work, it often keeps resources around longer than you intend — avoid autorelease pools.
– Hog too many resources, whether CPU or memory, and the phone will reboot.
– Everything from UIApplication on down will fire messages to Delegate objects at certain well-defined times, you need to learn what these times are and what messages are sent; it’s not just subclass avoidance.
– You can Option-Click on a class or interface name in XCode and go right to the documentation.
– You can press ESC to cause auto complete to happen immediately.
– Command-equal_sign will size a control to fit.
– When you’ve got a lot of control hierarchies going on, use the View Mode button to see them as a list.
– Scaling an image takes computational overhead, avoid if you can.
– Set the Alpha slider to 1.0 in order to optimize the drawing sequence, it skips looking at the underlying background and factoring it in — it applies to the image drawn.
– Also set the Opaque checkbox in order to optimize the drawing sequence, it skips drawing the underlying background for the parts where the image is transparent.
– The Tag control allows you to assign a numerical identifier to controls to locate them later.
– You need to handle the Did End on Exit event in order to make the keyboard go away.
– You may also need a huge, invisible, custom button as well to make the keyboard go away.
– In XCode, use Option-Command-up_arrow to toggle between a header and its source file.
– In the Interface Builder, move the cursor over a view and hold down Option to see how many pixels there are between the item and its superview.
– Option-dragging a control in Interface Builder makes a copy.
– Nifty buttons are actually stretchable images, and Apple has buried a ton of them free for your use in the UICatalog sample code on their site.
– There are three different ways to handle layouts when rotation happens: autosize, reposition, and view swapping.
– The rotation callback passes you the orientation the phone came from, you need to use other means to get the current orientation.
– If you want to use Core Graphics, for things like view transitions, you need to link the framework into your application.
– Some frameworks, like Core Graphics, have one version for the iPhone hardware and one version for the iPhone Simulator.
– If you use the correct parameters, XCode’s build process can play games with the path and always target the right framework (use Relative to Current SDK, and do not select Copy items).
– Right-click the Resources folder and use Add / Existing Frameworks… to do this process in a safe way.
– If a view isn’t shown, it’s superview is nil.

…there’s plenty more, but you get the idea. The book is jammed with all kinds of useful things to someone who is new to iPhone development. This presentation of material makes the learning curve very approachable.

And, once over that hurdle, all those other books that I said were problematic suddenly make a whole lot of sense.

This book is the best first step I’ve seen in the journey to writing iPhone applications. Period.

Walt gives “Beginning iPhone Development” two thumbs up, five stars our of five starts, and a head nod of appreciation to the authors. Well done, guys. Well done.

An Outsider’s View of Programming Documentation

Curious to how a non-technical person internalizes introductory technical material? I was.

Size Of Void StarAs a programmer, who works with programmers, writing programs that are primarily targeted for programmers, I find that I’m blessed with the ability to drop into a pseudo-language to communicate complex ideas concisely with my peers.

Occasionally, when I come up for air to deal with the rest of the world, I have to revert back to English. For me, the context switch is effortless, and occasionally I find myself using programmatic terms, like ‘context-switch’, in standard sentences.

The problem is, for a technical person, we don’t grasp what it’s like not to deal with technical information on a constant basis and then be abruptly exposed to it. Today I got to find out, and it was insightful. No wonder so may people fear their computers.

This morning, I was reviewing some basic documentation on Objective-C. Here’s the section (skim it):

Sending Messages to nil
In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:

  • If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.
  • If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.
  • If the method returns anything other than the aforementioned value types the return value of a
    message sent to nil is undefined.

My wife came over to see what I was reading.

Curious to know what a non-programmer’s take on this would be, I asked her to read it to me, interjecting her comments along the way. It went like this:

“Sending Messages to nil” (she paused for a moment, internally analyzing what she’d just gotten into)

“In Objective-C, it is valid to send a message to nil—” (pause) “it simply has no effect at runtime.” This sunk in for a second. “Well it it has no effect, when the heck are you sending it messages for?” She resumed composure.

“There are several patterns in Cocoa that take advantage of this fact.” Confusion set it. “Several patterns? You need more than one to have no effect?

“The value returned from a message to nil may also be valid: …” Her eyes combed the list.

“If the method returns an object, any pointer type, any integer scalar…” She hung on that word, and when I sat quietly, she continued. “…of size less than or equal to size of void star…” This was too much, “What?! Black holes can be different sizes?

Frustrated, “a float, a double, a long ” (…pregnant pause…) “double, or a long long,…” She stopped again. “A ‘long long’? You’re making this up.” She checked my face to see to see if I was pulling a fast one.

She continued, “… then a message sent to nil returns 0.” By this point it the sentence had no meaning.

“If the method returns a struct,” apparently she liked that, adding, “Oh boy! A struct”, but it was unclear if she was teasing me now.

Resuming, “as defined by the Mac OS X ABI Function Call Guide” (which again meant nothing) “to be returned in registers.” I saw a furrowed brow drop, internally wondering what cash registers had to do with any of this.

“…then a message sent to nil returns 0.0 for every…” and she stopped herself.

What?!? Zero-point-zero is different than zero? What the f***!?!” At that point she burst into an embarrassed laughter at just how mind boggling her internal monologue had gotten and refused to continue.

I had never looked at documentation from an outsider’s perspective before, it really did seem like techno-babble in that …context.