Jun 23 2008
Objective-C: Defining a Class
Note: This post is the start of an on-going series for developers who are interested in learning to write applications for the iPhone. The entire series can be found here: iPhone Developer .
One of the first topics to cover when learning to develop native iPhone applications is how to code in Objective-C. Apple offers the Objective C Reference , a good resource, however, the best way to learn is by writing code. I took to Xcode to write a few simple examples, you’ll find the code below. At the end of this post I also include a link to download the Xcode project I was working with.
There are two aspects to a class, the interface and the implementation, both of which I recommend you store in separate files (although this is not a requirement).
The interface looks as follows:
@interface NameOfClass : NameOfSuperclass
{
instance variables here...
}
class methods
instance methods
@end
The interface for my example:
// ===========================
// = Interface for SomeClass =
// ===========================
#import
@interface SomeClass : NSObject
{
NSString *str;
NSDate *date;
int x;
}
// Getters
-(int) x;
-(NSString *) str;
-(NSDate *) date;
// Setters
-(void )setX:(int) input;
-(void) setStr:(NSString *)input;
-(void) setDate:(NSDate *)input;
// Other
-(void) printInstanceVars;
-(void) dealloc;
@end
A good coding practice is to save the implementation definition in a file with a name that matches the class name, with an extension of .h (for exampe: SomeClass.h).
This class is inherited from NSObject, the uber object. The class has three instance variables, two that point to other objects, one that references an integer variable. Take note of the getter methods: in Objective-C there is typically no ‘get’ in the front of the method name (in Java this might look like getX or getStr). Second, it should be obvious, that an instance variable can have the same name as a method, as it generally does with a getter. The ‘-’ in the front of the definition, signifies that the method is an instance method. We use a ‘+’ to define a class method (more on class methods in a future post).
One important thing to point out is the format used when declaring methods. For example, setStr() is defined as -(void)setStr: (NSString *) input ; This is translated to, the method setStr is an instance method (given the ‘-’) that returns a void type. The method takes one argument, that is a pointer to an NSString object, the name assigned to the parameter is ‘input’. The reason for the name will become more apparent when you see the implementation of the method below.
The format for the implementation of a class looks as follows:
@implementation NameOfClass : NameOfSuperclass
{
instance variables here...
}
class methods
instance methods
@end
Here is how the implementation for the above class looks:
#import "SomeClass.h"
#import <stdio.h>
// ================================
// = Implementation for SomeClass =
// ================================
@implementation SomeClass
// =================
// = Getter methods =
// =================
- (int) x
{
return x;
}
- (NSString *) str
{
return str;
}
- (NSDate *) date
{
return date;
}
// =================
// = Setter Methods =
// =================
- (void) setX:(int)input
{
x = input;
}
- (void) setStr:(NSString *)input
{
[input retain];
[str release];
str = input;
}
- (void) setDate:(NSDate *)input
{
[input retain];
[date release];
date = input;
}
// ================================
// = Print the instance vars =
// ================================
-(void) printInstanceVars
{
// Use the getter method of the ’self’ object to print object instance variables
// NSLog(@"\n x: %d\n str: %@\n date: %@\n", [self x], [self str], [self date]);
// The class can directly access the instance variables (versus calling message as above)
NSLog(@"\n x: %d\n str: %@\n date: %@\n", x, str, date);
}
// ====================================
// = Dealloc all object instance vars =
// ====================================
-(void) dealloc
{
// No release needed of the integer instance variable ‘x’
[str release];
[date release];
[super dealloc];
}
@end
Other than learning the syntax of Objective-C, if you are familiar with OO development, most of this should be pretty clear.
A couple of things to point out:
- The preferred file name for the implementation is the class name with a .m extension, in this example: SomeClass.m
- Notice how this file imports "SomeClass.h" to read the class definition. If you are familiar with C, this is analgous to the #include directive. The benefit of #import is that the compiler will do the work for you to verify that the include file is only read once. If you’ve done any amount of coding in C, you’ll appreciate this convenience, if not, you won’t understand how nice a feature this is.
- Within an instance method, all instance variables are within scope. For example, notice how the getter and setter methods refer to the instance variables.
- Notice in printInstanceVars() method that there are two means to access the instance variables. You can use the ’self’ object an send a message to the getter method (more on objects and messages in the next post), or you can directly access the instance variables.
- If instance variables are pointers to objects, as are ’str’ and ‘date’, it’s your responsibility as the developer to free the memory for those objects. The dealloc method is where you do this work. More on that to come…
To complete the example, the code that follows declares an instance of the SomeClass object, and uses the setter/getter methods to print the instance variables to the console.
#import <Foundation/Foundation.h>
#import "SomeClass.h"
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SomeClass *ptr = [[SomeClass alloc] init];
[ptr setX:99];
[ptr printInstanceVars];
[ptr setStr:@"Testing"];
[ptr printInstanceVars];
[ptr setDate:[NSDate date]];
[ptr printInstanceVars];
[ptr release];
[pool drain];
return 0;
}
A few comments on the above code:
- Notice this file imports the SomeClass.h interface file.
- Like working with C, main() is the function that gets everything started.
- ‘ptr’ is a reference to an object of the SomeClass class.
- Calling instance methods of an object follows this form: [object message:parameters]
A screenshot of the output from within Xcode of this example is below:

I recommend you download the Xcode project and give it a go.
Let’s go with that for today. In the next post I’ll talk further about this simple example, including instantiation of classes, sending messages to methods and freeing memory of the instance variables.
Tips by RSS
Tips by Email
