Saturday, May 25, 2013

Objective-C Classes and Objects

Objective-C classes are the same as classes in any other object-oriented programming
language. A class encapsulates both state (properties) and behavior (methods), and forms an
object-oriented program’s basic building blocks. An object-oriented application functions by
objects sending messages between each other. For instance, in a typical Java command-line
application, you begin the program by calling a static method called main in a class. This
main method instantiates one or more objects, and the application’s remaining functionality
consists of messages between those objects instantiated in the main method, as well as any
objects they might in turn instantiate.

Class Interface and Implementation

Objective-C separates a class into an interface and an implementation. An interface declares
instance variables and methods. It is a standard C header file and doesn’t provide any method
definitions. The implementation contains the method definitions for the class. It is a file with
its own .m extension rather than a .c extension.

Method Declaration and Definition

You declare a class’ methods and instance variables in its interface. You define a class’ methods
and instance variables in its implementation. Declaring a method means you tell the compiler
that a class will have a method, with a certain signature, but you don’t provide the actual code
for the method. For instance, consider the following method declaration.

-(void) sayHello: (NSString*) name;

The declaration tells the compiler to expect a method called sayHello that returns nothing
(void) and takes an NSString as an argument. The declaration says nothing about the method’s
content.

You provide the compiler with a method’s implementation by defining the method. Defining
a method means you provide a method declaration’s actual behavior, or its implementation.
For instance, the sayHello method in Listing 3-3 provides the sayHello method declaration’s
behavior.

Listing 3-3 A simple Objective-C method implementation

-(void) sayHello: (NSString*) name {
  NSMutableString *message = [[NSMutableString alloc]
        initWithString:@"Hello there "];
  [message appendString:name];
  NSLog(message);
  [message release];
}

No comments:

Post a Comment