Objective-C : Documentation : Syntax : Classes


Interface

Format:

#import "Superclass.h"

@interface ClassName : SuperClass < protocols >

{

variable declarations

}

method declarations

@end



Example:

#import "Thing.h" 

@interface Dog : Thing
{
   id name;
 }
 
- bark;
- bring:anObject to:aPlace;
- setNameTo:(char *)astring;

@end


Implementation

Format:

#import "ClassName.h"

@implementation ClassName

method definitions

@end


Example:

#import "Dog.h"

@implementation Dog 

- init
{
   [super init];
   name = [[String alloc] init];
   return self;
}

	
- free
{
   [name free];
   return [super free];
}

- bark
{
   printf("ruff!");
   return self;
}

- bring:anObject to:aPlace
{
   [self moveToPosition:[anObject position]];
   [self pickup:anObject];
   [self moveToPosition:aPlace];
   [self drop:anObject];
   return self;
}

- setNameTo:(char *)astring
{
   [name setStringValue:astring];
   return self;
}

@end


Creating Objects

An instance of a class(an object) is created by sending the Class an - alloc message.

The - alloc method allocates the memory for a new object and the value it returns is an id for the object created.(a pointer to the object).

For example:

Would set the variable aDog to the id of the instance of the Dog class returned by the [Dog alloc] message.

Initialization

After an object is allocated, it is normal to send it an - init message. The init method is used for any initialization that the object may have to do before being ready to be used. For example:

Using Objects

Once you've allocated and initialized an object, you're ready start using it. Example:

Freeing Objects

When you are finished using an object, it's memory can be freed using the - free method:

Methods

Declaration

Method declarations are contained in the interface file and

- ( [ return data type ] ) method-name :( [ argument data type ] ) [argument name ]...

Examples:

- bark; - bring:anObject to:aPlace; - setNameTo:(char *)astring; - (int)age;

Defaults

id is the default data type for return values and arguments. Otherwise the data type needs to be specificed in paratheses in front of the method name.

Inheriting Methods

UNFINISHED DIAGRAM

Method Overriding

A subclass can implement a method that has the same name as a method in one of it's superclasses.

UNFINISHED DIAGRAM

Messages to self and super

The names self and super have special meanings.
Within a object, the self refers to the object itself, and super refers to it's super class.

Examples:

- init
{
   [super init];
   name = [[String alloc] init];
   return self;
}

Polymorphism

Different classes can implement methods of the same name.

Example:

[dog fetch:stick];
[database fetch:record];

Static Typing