Objective-C is a highly dynamic, message-based object-oriented language. Consisting of a small number of additions to ANSI C, Objective-C is characterized by its deferral of many decisions until runtime, supporting its key features of dynamic dispatch, dynamic typing, and dynamic loading. These features support many of the design patterns Cocoa uses, including delegation, notification, and Model-View-Controller (MVC). Because it is an extension of C, existing C code and libraries, including those based on C++,[1] can work with Cocoa-based applications without losing any of the effort that went into their original development.
This chapter is an overview of Objective-C’s most frequently used features. If you need more detail about these features or want to see the full language specification, read through Apple’s document, The Objective-C Programming Language, which is installed as part of the Developer Tools in /Developer/Documentation/Cocoa/ObjectiveC.
The base unit of activity in all object-oriented languages is the
object—
an
entity that associates data with operations that can be performed on
that data. Objective-C provides a distinct data type,
id
, defined as a pointer
to an object’s data that allows you to work with
objects. An object may be declared in code as follows:
id anObject;
For all object-oriented constructs of Objective-C, including method
return values, id
replaces the default C
int
as the default return data type.
The id
type is completely nonrestrictive. It says
very little about an object, indicating only that it is an entity in
the system that can respond to messages and be queried for its
behavior. This type of behavior, known as dynamic
typing
, allows the system to find the class to
which the object belongs and resolve messages into method calls.
Objective-C also supports static
typing
, in which you declare a variable using
a pointer to its class type instead of id
, for
example:
NSObject *object;
This declaration will turn on some degree of compile time checking to
generate warnings when a type mismatch is made, as well as when you
use methods not implemented by a class. Static typing can also
clarify your intentions to other developers who have access to your
source code. However, unlike other languages’ use of
the term, static typing in Objective-C is used only at compile time.
At runtime, all objects are treated as type id
to
preserve dynamism in the system.
[1] For more information on using C++ with Objective-C, see the Objective-C++ documentation contained in /Developer/Documentation/ReleaseNotes/Objective-C++.html.