Retired Document
Important: This document describes an older version of Objective-C and has not been updated to the current version. Developers learning Objective-C should instead refer to Programming with Objective-C.
Objects, Classes, and Messaging
This chapter describes the fundamentals of objects, classes, and messaging as used and implemented by the Objective-C language. It also introduces the Objective-C runtime.
The Runtime System. To understand more about the functionality it offers, though, see Objective-C Runtime Programming Guide.
Objects
As the name implies, object-oriented programs are built around objects. An object associates data with the particular operations that can use or affect that data. Objective-C provides a data type to identify an object variable without specifying a particular class of the object.
Object Basics
An object associates data with the particular operations that can use or affect that data. In Objective-C, these operations are known as the object’s methods; the data they affect are its instance variables (in other environments they may be referred to as ivars or member variables). In essence, an object bundles a data structure (instance variables) and a group of procedures (methods) into a self-contained programming unit.). For others to find out something about an object, there has to be a method to supply the information. For example, a rectangle would have methods that reveal its size and.
id
In Objective-C, object identifiers are of a distinct data type:
id. This type is the general type for any kind of object regardless of class and can be used for instances of a class and for class objects themselves.:
Every object thus has an
isa variable that tells it of what class it is an instance. Since the
Class type is itself defined as a pointer:
the
isa variable is frequently referred to as the “
isa pointer.”
Dynamic Typing
The
id type is completely nonrestrictive. By itself, it yields no information about an object, except that it is an object. At some point, a program typically needs to find more specific information about the objects it contains. Since the
id type designator can’t supply this specific information to the compiler, each object has to be able to supply it at runtime.
The
isa instance variable identifies the object’s class—what—to.
It’s also possible to give the compiler information about the class of an object by statically typing it in source code using the class name. Classes are particular kinds of objects, and the class name can serve as a type name. See Class Types and Enabling Static Behavior..
Manual reference counting is described in Advanced Memory Management Programming Guide.
Garbage collection, where you pass responsibility for determining the lifetime of objects to an automatic “collector.”
Garbage collection is described in Garbage Collection Programming Guide. (Not available for iOS—you cannot access this document through the iOS Dev Center.)
Object Messaging
This section explains the syntax of sending messages, including how you can nest message expressions. It also discusses the scope or “visibility” of an object’s instance variables, and the concepts of polymorphism and dynamic binding.
Message Syntax parameters that are passed to it. When a message is sent, the runtime system selects the appropriate method from the receiver’s repertoire and invokes it.
For example, this message tells the
myRectangle object to perform its
display method, which causes the rectangle to display itself::
For methods with multiple parameters, Objective-C's method names are interleaved with the parameters such that the method’s name naturally describes the parameters expected by the method. The imaginary message below tells the
myRectangle object to set its origin to the coordinates (30.0, 50.0):.
In principle, a
Rectangle class could instead implement a
setOrigin:: method with no label for the second parameter, which would be invoked as follows:
While syntactically legal,
setOrigin:: does not interleave the method name with the parameters. Thus, the second parameter is effectively unlabeled and it is difficult for a reader of this code to determine the kind or purpose of the method’s parameters.
Methods that take a variable number of parameters are also possible, though they:
Like standard C functions, methods can return values. The following example sets the variable
isFilled to
YES if
myRectangle also provides a dot (
.) operator that offers a compact and convenient syntax for invoking an object’s accessor methods. The dot operator is often used in conjunction with the declared properties feature (see Declared Properties) and is described in Dot Syntax.
Sending Messages to nil
In Objective-C, it is valid to send a message to
nil—it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to
nil may also be valid:
If the method returns an object, then a message sent to
nilreturns
0(
nil). For example:
If the
spouseobject here is
nil, then
motheris sent to
niland the method returns
nil.
If the method returns any pointer type, any integer scalar of size less than or equal to
sizeof(void*), a
float, a
double, a
long double, or a
long long, then a message sent to
nilreturns
0.
If the method returns a
struct, as defined by the OS X ABI Function Call Guide to be returned in registers, then a message sent to
nilreturns
0.0for every field in the
struct. Other
structdata types will not be filled with zeros.
If the method returns anything other than the aforementioned value types, the return value of a message sent to
nilis undefined.
The following code fragment illustrates a valid use of sending a message to
nil.
The Receiver’s Instance Variables
A method has automatic access to the receiving object’s instance variables. You don’t need to pass them to the method as parameters. For example, the
primaryColor method illustrated above takes no parameters, yet it can find the primary color for
otherRect and return it. Every method assumes the receiver and its instance variables, without having to declare them as parameters.
This convention simplifies Objective-C source code. It also supports the way object-oriented programmers think about objects and messages. Messages are sent to receivers much as letters are delivered to your home. Message parameters earlier are used for just this purpose.
See Defining a Class for more information on referring to instance variables.
Polymorphism
As the earlier examples illustrate, messages in Objective-C appear in the same syntactic positions as function calls in standard C. But, because methods “belong to” an object, messages don’t behave in the same way that function calls do.
In particular, an object can be operated on by only those methods that were defined for it. It can’t.
Dynamic Binding
A crucial difference between function calls and messages is that a function and its parameters are joined together in the compiled code, but a message and a receiving object aren receiver’s implementation of a method matching the name, “calls” the method, and passes it a pointer to the receiver’s doesn’t have to be concerned with them; it doesn’t even have to enumerate the possibilities. An application’s objects can each respond in its own way to
copy messages.
Objective-C takes dynamic binding one step further and allows even the message that’s sent (the method selector) to be a variable determined at runtime. This mechanism is discussed in the section Messaging in Objective-C Runtime Programming Guide.
Dynamic Method Resolution
You can provide implementations of class and instance methods at runtime using dynamic method resolution. See Dynamic Method Resolution in Objective-C Runtime Programming Guide for more details.
Dot Syntax
Objective-C provides a dot (
.) operator that offers an alternative to square bracket notation (
[]) to invoke accessor methods. Dot syntax uses the same pattern that accessing C structure elements uses:
When used with objects, however, dot syntax acts as “syntactic sugar”—it is transformed by the compiler into an invocation of an accessor method. Dot syntax does not directly get or set an instance variable. The code example above is exactly equivalent to the following:
As a corollary, if you want to access an object’s own instance variable using accessor methods, you must explicitly call out
self, for example:
or the equivalent:
If you do not use
self., you access the instance variable directly. In the following example, the set accessor method for
age is not invoked:
If a
nil value is encountered during property traversal, the result is the same as sending the equivalent message to
nil. For example, the following pairs are all equivalent:
Classes—several
Class definitions are additive; each new class that you define is based on another class from.
isn’t only a square, it’s also a rectangle, a shape, a graphic, and an object of type. a
Rectangle class and where they may don’t have instance variables (only instances do), they inherit only methods... Because an object has memory allocated for every instance variable it inherits, you can’t override an inherited variable by declaring a new one with the same name. If you try, the compiler will complain.
Abstract Classes
Some—it wouldn:
Static Typing
You can use a class name in place of
id to designate an object’s type:
Because this way of declaring an object type gives the compiler information about the kind of object it is, it’s known as static typing. Just as
id is actually a pointer, objects are statically typed as pointers to a class. Objects are always typed by a pointer. Static typing makes the pointer explicit;
id hides it.
Static typing permits the compiler to do some type checking—for example, to warn if an object could receive runtime.
An object can be statically typed to its own class or to any class that it inherits from. For example, because inheritance makes a
Rectangle object a kind of
Graphic object (as shown in the example hierarchy in Figure 1-1), a
Rectangle instance can be statically typed to the
Graphic class:
Static typing to the superclass is possible here because a
Rectangle object is a
Graphic object. In addition, it’s more than that because it also has the instance variables and method capabilities of
Shape and
Rectangle objects, but it’s for more on static typing and its benefits.
Type Introspection
Instances can reveal their types at runtime. The
isMemberOfClass: method, defined in the
NSObject class, checks whether the receiver is an instance of a particular class:
The
isKindOfClass: method, also defined in the
NSObject class, checks more generally whether the receiver inherits from or is a member of a particular class (whether it has the class in its inheritance path):.
Class Objects
A. It’s able to produce new instances according to the plan put forward in the class definition.:
However, the class name stands for the class object only as the receiver in a message expression. Elsewhere, you need to ask an instance or the class to return the class
id. Both respond to a
class message:
As these examples show, class objects can, like all other objects, be typed
id. But class objects can also be more specifically typed to the
Class data type: runtime.
Creating Instances
A principal function of a class object is to create new instances. This code tells the
Rectangle class to create a new rectangle instance and assign it to the
myRectangle variable:”. AppKit, AppKit. All inherit from the generic
NSCell class.
haven’t—that is, with a class object. The
NSMatrix class also defines a
setCellClass: method that passes the class object for the kind of
NSCell object an
NSMatrix should use to fill empty slots:
The
NSMatrix). object’s state into static variables and use only class methods. This saves the step of allocating and initializing an instance. sequence.
To avoid performing initialization logic more than once, use the template in Listing 1-1 when implementing the
initialize method.
Listing 1-1 Implementation of the initialize method NSObject Class Reference.
Class Names in Source Code
In source code, class names can be used in only two very different contexts. These contexts reflect the dual role of a class as a data type and as an object:
The class name can be used as a type name for a kind of object. For example:
Here
anObjectis statically typed to be a pointer to a
Rectangleobject. The compiler expects it to have the data structure of a
Rectangleinstance and to have the instance methods defined and inherited by the
Rectangleclass. Static typing enables the compiler to do better type checking and makes source code more self-documenting. See Enabling Static Behavior for details.
Only instances can be statically typed; class objects can’t be, because they aren’t members of a class, but rather belong to the
Classdatamessage). This example passes the
Rectangleclass as a parameter in an
isKindOfClass:message:
It would have been illegal to simply use the name “Rectangle” as the parameter. The class name can only be a receiver.
If you don’t know the class name at compile time but have it as a string at runtime, you can use
NSClassFromStringto return the class object:
This function returns
nilif the string it’s passed is not a valid class name.
Class names exist in the same namespace as global variables and function names. A class and a global variable can’t have the same name. Class names are do this—see Key-Value Observing Programming Guide and Core Data Programming Guide respectively). In a dynamically-created subclass, the
class method is typically overridden such that the subclass masquerades as the class it replaces. When testing for class equality, you should therefore compare the values returned by the
class method rather than those returned by lower-level functions. Put in terms of API, the following inequalities pertain for dynamic subclasses:
You should therefore test two classes for equality as follows:
Copyright © 2013 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2013-04-23