This document provides an overview of Objective-C and discusses several key concepts:
1. It begins with instructions for setting up the Objective-C development environment on Linux, Mac OS X, and Windows systems.
2. A "Hello World" example program is presented to demonstrate the basic structure of an Objective-C application and how to print output.
3. Object-oriented concepts like classes, inheritance, and polymorphism are explained through examples showing how to define classes with interfaces and implementations, create class instances, and call methods.
4. Additional Objective-C features are demonstrated like method parameters, constructors, access privileges, class methods, and exceptions handling.
1. 24/11/10 21:11Objective-C Beginner's Guide
Página 1 de 34http://www.otierney.net/objective-c.html
Translations: English | Chinese | Korean
Outline
Getting Started
Downloading this tutorial
Setting up the environment
Preamble
Making hello world
Creating Classes
@interface
@implementation
Piecing it together
The Details...
Multiple Parameters
Constructors
Access Privledges
Class level access
Exceptions
Inheritance, Polymorphism, and other OOP features
The id type
Inheritance
Dynamic types
Categories
Posing
Protocols
Memory Management
Retain and Release
Dealloc
Autorelease Pool
Foundation Framework Classes
NSArray
NSDictionary
Pros and Cons
More Information
Getting Started
Downloading this tutorial
All the source code for this beginners guide including makefiles is available by
downloading objc.tar.gz. Many of the examples in this tutorial were written by Steve
Kochan in the book Programming in Objective-C. If you want more detailed
information and examples, feel free to check out his book. The examples on this site
were used with his permission, so please don't copy them.
Setting up the environment
Linux/FreeBSD: Install GNUStep
In order to build GNUstep applications one must first execute the GNUstep.sh
file in /usr/GNUstep/System/Makefiles/GNUstep.sh. This path depends on your
2. 24/11/10 21:11Objective-C Beginner's Guide
Página 2 de 34http://www.otierney.net/objective-c.html
system. Some put it in /usr, some /usr/lib, some /usr/local. If your shell is a
csh/tcsh based shell, you'll want to execute GNUStep.csh instead. It's
recommended that you put this script in your .bashrc or .cshrc.
Mac OS X: Install XCode
Windows NT 5.X: Install cygwin or mingw and then install GNUStep
Preamble
This tutorial assumes you have some basic C knowledge, including C data types, what
a function is, what a return value is, knowledge of pointers and basic memory
management in C. If you haven't gotten this far, I highly suggest you pick up K and
R's book, The C Programming Language. This is the book on C written by the writers
of C.
Objective-C, being a C derivative, inherits all of C's features. There are a few
exceptions but they don't really deviate from what C offers as a language.
nil: In C/C++ you're probably used to NULL. In Objective-C it is nil. The difference is
you can pass messages to nil (such as [nil message];) and this is perfectly legal. You
cannot however do this with NULL.
BOOL: C doesn't have an official boolean type, and in reality neither does Objective-
C. It's however built into the Foundation classes (Namely from importing
NSObject.h). nil is also included in this header file. BOOL in Objective-C has two
modes, YES and NO rather than TRUE and FALSE.
#import vs #include: As you will notice in the hello world example, #import was used.
#import is supported by the gcc compiler, however it is deprecated in favor of
#include. #import is basically the same thing as #ifndef #define #endif at the top and
bottom of every .h file you make. I find this to be retarded, as many other
programmers will most likely agree. For all purposes, just use #import. It's less hassle,
and if gcc ever does remove it chances are enough Objective-C developers exist to
either keep it from getting removed or getting added back in. As an aside, Apple
officially uses #import in all their code so if this ever did happen, you can be certain
that Apple would conviently ship a forked version of gcc to add this back in.
The word method and message are used interchangably in Objective-C, although
messages have special properties. A message can be dynamically forwarded to another
object. Calling a message on an object in Objective-C doesn't mean that the object
implements that message, just that it knows how to respond to it somehow via directly
implementing it or forwarding the message to an object that does know how to.
Making hello world
hello.m
#import <stdio.h>
int main( int argc, const char *argv[] ) {
printf( "hello worldn" );
return 0;
}
output
hello world
You use #import instead of #include in Objective-C
The default file extention for Objective-C is .m
7. 24/11/10 21:11Objective-C Beginner's Guide
Página 7 de 34http://www.otierney.net/objective-c.html
[frac3 print];
printf( "n" );
// free memory
[frac release];
[frac2 release];
[frac3 release];
return 0;
}
output
The fraction is: 1/3
Fraction 2 is: 1/5
Fraction 3 is: 3/10
@interface declaration is identical to a regular function
@implementation shows a new keyword: super
Similar to Java, Objective-C only has one parent class.
Accessing it's super constructor is done through [super init] and this is required
for proper inheritance.
This returns an instance which you assign to another new keyword, self. Self is
similar to this in Java and C++.
if ( self ) is the same as if ( self != nil ) to make sure that the super constructor
successfully returned a new object. nil is Objective-C's form of NULL from C/C++.
This is gotten from including NSObject.
After you've initialized the varialbes, you return yourself with return self;
The deafult constructor is -(id) init;
Constructors in Objective-C are technically just "init" methods, they aren't a special
construct like they are in C++ and Java.
Access Privledges
The default access is @protected
Java implements this with public/private/protected modifiers infront of methods and
variables. Objective-C's approach is much more similar to C++'s for instance variables
Access.h
#import <Foundation/NSObject.h>
@interface Access: NSObject {
@public
int publicVar;
@private
int privateVar;
int privateVar2;
@protected
int protectedVar;
}
@end
Access.m
#import "Access.h"
@implementation Access
@end
main.m
8. 24/11/10 21:11Objective-C Beginner's Guide
Página 8 de 34http://www.otierney.net/objective-c.html
#import "Access.h"
#import <stdio.h>
int main( int argc, const char *argv[] ) {
Access *a = [[Access alloc] init];
// works
a->publicVar = 5;
printf( "public var: %in", a->publicVar );
// doesn't compile
//a->privateVar = 10;
//printf( "private var: %in", a->privateVar );
[a release];
return 0;
}
output
public var: 5
As you an see, instead of private: [list of vars] public: [list of vars] like in C++, it's just
@private, @protected, etc.
Class level access
Often it's nice to have class level variables and functions, for instance when keeping
track of the # of times an object has been instanciated.
ClassA.h
#import <Foundation/NSObject.h>
static int count;
@interface ClassA: NSObject
+(int) initCount;
+(void) initialize;
@end
ClassA.m
#import "ClassA.h"
@implementation ClassA
-(id) init {
self = [super init];
count++;
return self;
}
+(int) initCount {
return count;
}
+(void) initialize {
count = 0;
}
@end
main.m
#import "ClassA.h"
20. 24/11/10 21:11Objective-C Beginner's Guide
Página 20 de 34http://www.otierney.net/objective-c.html
denominator: denominator * [f denominator]];
}
@end
main.m
#import <stdio.h>
#import "Fraction.h"
#import "FractionMath.h"
int main( int argc, const char *argv[] ) {
// create a new instance
Fraction *frac1 = [[Fraction alloc] initWithNumerator: 1 denominator: 3];
Fraction *frac2 = [[Fraction alloc] initWithNumerator: 2 denominator: 5];
Fraction *frac3 = [frac1 mul: frac2];
// print it
[frac1 print];
printf( " * " );
[frac2 print];
printf( " = " );
[frac3 print];
printf( "n" );
// free memory
[frac1 release];
[frac2 release];
[frac3 release];
return 0;
}
output
1/3 * 2/5 = 2/15
The magic here is the two @implementation and @interface lines: @interface Fraction
(Math) and @implementation Fraction (Math).
There can only be one category with the same name. Additional cateogies may be
added on with different but unqiue names.
Categories can't add instance variables.
Categories are useful for creating private methods. Since Objective-C has no notion of
private/protected/public methods like java does, one has to create categories that hide
such functionality. The way this is done is by moving the private methods from your
class's header (.h) file to the implementation file (.m). The following is a very brief
example of what I mean.
MyClass.h
#import <Foundation/NSObject.h>
@interface MyClass: NSObject
-(void) publicMethod;
@end
MyClass.m
#import "MyClass.h"
#import <stdio.h>
@implementation MyClass
-(void) publicMethod {
printf( "public methodn" );
}
24. 24/11/10 21:11Objective-C Beginner's Guide
Página 24 de 34http://www.otierney.net/objective-c.html
-(Complex*) initWithReal: (double) r andImaginary: (double) i;
-(void) setReal: (double) r;
-(void) setImaginary: (double) i;
-(void) setReal: (double) r andImaginary: (double) i;
-(double) real;
-(double) imaginary;
@end
Complex.m
#import "Complex.h"
#import <stdio.h>
@implementation Complex
-(Complex*) initWithReal: (double) r andImaginary: (double) i {
self = [super init];
if ( self ) {
[self setReal: r andImaginary: i];
}
return self;
}
-(void) setReal: (double) r {
real = r;
}
-(void) setImaginary: (double) i {
imaginary = i;
}
-(void) setReal: (double) r andImaginary: (double) i {
real = r;
imaginary = i;
}
-(double) real {
return real;
}
-(double) imaginary {
return imaginary;
}
-(void) print {
printf( "%_f + %_fi", real, imaginary );
}
@end
main.m
#import <stdio.h>
#import "Fraction.h"
#import "Complex.h"
int main( int argc, const char *argv[] ) {
// create a new instance
Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10];
Complex *comp = [[Complex alloc] initWithReal: 5 andImaginary: 15];
id <Printing> printable;
id <NSCopying, Printing> copyPrintable;
// print it
printable = frac;
printf( "The fraction is: " );
25. 24/11/10 21:11Objective-C Beginner's Guide
Página 25 de 34http://www.otierney.net/objective-c.html
[printable print];
printf( "n" );
// print complex
printable = comp;
printf( "The complex number is: " );
[printable print];
printf( "n" );
// this compiles because Fraction comforms to both Printing and NSCopyable
copyPrintable = frac;
// this doesn't compile because Complex only conforms to Printing
//copyPrintable = comp;
// test conformance
// true
if ( [frac conformsToProtocol: @protocol( NSCopying )] == YES ) {
printf( "Fraction conforms to NSCopyingn" );
}
// false
if ( [comp conformsToProtocol: @protocol( NSCopying )] == YES ) {
printf( "Complex conforms to NSCopyingn" );
}
// free memory
[frac release];
[comp release];
return 0;
}
output
The fraction is: 3/10
The complex number is: 5.000000 + 15.000000i
Fraction conforms to NSCopying
The protocol specification is quite simple. it is basically @protocol ProtocolName
(methods you must implement) @end.
To conform to a protocol, you put the protocols you're conforming to in <>'s, and
comma separate them. Example: @interface SomeClass <Protocol1, Protocol2,
Protocol3>
The methods that the protocol requires to be implemented are not required to be in the
list of methods for the header file. As you can see, Complex.h doesn't have a
definition for -(void) print, but it still implements it since it conforms to the protocol.
One unique aspect of Objective-C's interface system is how you specify types. Rather
than specifying it like Java or C++ as: Printing *someVar = ( Printing * ) frac; for
example, you use the id type with a restricted protocol: id <Printing> var = frac; This
allows you to dynamically specify a type that requires multiple protocols, all with one
variable. Such as: id <Printing, NSCopying> var = frac;
Much like using @selector for testing an object's inheritance, you can use @protocol
to test for conformance of interfaces. [object conformsToProtocol: @protocol(
SomeProtocol )] returns a BOOL if the object conforms to that protocol. This works
the same for classes as well: [SomeClass conformsToProtocol: @protocol(
SomeProtocol )].
Memory Management
34. 24/11/10 21:11Objective-C Beginner's Guide
Página 34 de 34http://www.otierney.net/objective-c.html
[pool release];
return 0;
}
output
----static dictionary
1 => one
2 => two
3 => three
----mutable dictionary
bob@dole.com => Bob
tom@jones.com => Tom
Pros and Cons
Pros
Cateogies
Posing
Dynamic typing
Pointer counting
Flexible message passing
Not an overly complex extention to C
Can interface with C++ via Objective-C++
Cons
No namespaces
No operator overloading (this is often considered a Pro though, but operator
overloading used properly can reduce code clutter)
Still some cruft in language, although no more than C++
More Information
Programming in Objective-C 2.0 (2nd Edition)
Programming in Objective-C
Learning Cocoa with Objective-C
Cocoa Programming for Mac OS X
Object-Oriented Programming and the Objective-C Language
GNUstep mini tutorials
Last modified: April 13, 2004.