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.
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"
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?
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.
- Fortunately the Apple documentation is high quality for the Foundation and Cocoa APIs, and has a large amount of tasks much like the MSDN documentation. Here’s an example.
- Most of the above has come from reading Stephen G. Kochan’s Programming in Objective-C 2.0 book (affliate link). I recommend it, however I haven’t really read any others.
- Naming convention information.
- There is a huge wealth of information on the web - a good tutorial can be found here, and here.
- Information about synthesised properties can be found on the Apple developer site and here.