Posted on Monday June 22, 2009

Objective C by example for a C# developer

This is a small set of code snippets that may assist as a quick reference when switching between C# and Objective-C concepts. It’s all beginner level and I’ve skipped some major concepts that a book will explain, as well as any C related tasks.

Thanks to Bill Bumgarner from Apple for his corrections and feedback. In particular alloc and init, autorelease, abstract classes and the constructor sections have been changed.

Update 2
Since I wrote this article I’ve shifted from battling with objective-c to using Monotouch. I’m now maintaining this page of snippets for Monotouch.

Object creation

The import keyword

There’s two ways of importing, just as with C/C++. The one you want to care about most of the time is in quotes. The angled brackets approach forces the preprocessor to look for the file in the system header directory.

#import <Foundation/Foundation.h>
#import "MyClass.h"

Naming conventions

Objective-C is much like Java and uses Pascal case for classes, and camel case for methods and properties. The link at the bottom page gives more information.

Reflection equivalent, or typeof/is

As far as I’m aware objective-c has no equivalent to reflection in the framework. However for type checking there are many features built in.

Foundation.h, Cocoa, UIKit and AppKit

Regardless of your application, you will almost always include Foundation.h as an import. This is the base library of classes like NSObject, NSString and so on, much like mscorlib.dll in .NET.

Cocoa is used for Cocoa applications on OS X, however on the iPhone/iTouch this is Cocoa Touch library. AppKit is part of the desktop/netbook Cocoa library, however this is replaced by UIKit on the Touch platform. Confused yet?

Classes, encapsulation

Below shows most features you’ll need to know about, with comments describing what is going on. I’ve arranged it in 2 separate files - the header and implementation file. It’s possible to define a class and implementation in the same file however the standard is to have the interface in a header (.h) file, and the implementation in the source (.m) file.

Exception handling

String example


Collections: Dictionary

Date formatting