Objective-C , the language of iPhone development, uses OOP (Object Oriented Programming). Objective-C is a C compatible language with dynamic object-oriented extensions. Because the language is an extension of C, developers can adapt existing C programs to use Objective-C frameworks without losing any original development work.
Methods = An operation that associates an object with data to use or affect that data.
Instance Variables = the data that is affected by a method.
Important:
- In Objective-C, an object’s instance variables are internal to the object; generally.
- You get access to an object’s state only through the object’s methods (note: you can specify whether subclasses or other objects can access instance variables directly by using scope directives.)
- An object sees only the methods that were designed for it; it can’t mistakenly perform methods intended for other types of objects. Just as a C function protects its local variables, hiding them from the rest of the program.
- An object hides both its instance variables and its method implementations.
id
This is the general type for any kind of object regardless of class. (It can be used for both instances of a class and class objects themselves.) id is defined as pointer to an object data structure:
typedef struct objc_object {
Class isa;
} *id;
"Dynamic Typing"
The id type is completely nonrestrictive. By itself, it yields no information about an object, except that it is an object.
But objects aren’t all the same. A Rectangle won’t have the same methods or instance variables as an object that represents a bit-mapped image. At some point, a program needs to find more specific information about the objects it contains—what the object’s instance variables are, what methods it can perform, and so on. Since the id type designator can’t supply this 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 kind of object it is. Every Rectangle object would be able to tell the runtime system that it is a Rectangle. Every Circle can say that it is a Circle.
- Objects with the same behavior (methods) and the same kinds of data (instance variables) are members of the same class.
- Objects are dynamically typed at runtime.
Whenever it needs to, the runtime system can find the exact class that an object belongs to, just by asking the object. Dynamic typing in Objective-C serves as the foundation for what is called dynamic binding.
Theisavariable also enables objects to perform introspection—to find out about themselves (or other objects). The compiler records information about class definitions in data structures for the runtime system to use. The functions of the runtime system useisa, to find this information at runtime. Using the runtime system, you can, for example, determine whether an object implements a particular method, or discover the name of its superclass.
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.
"Classes"
-In Objective-C, you define objects by defining their class.
- The class definition is a prototype for a kind of object; it declares the instance variables that become part of every member of the class, and it defines a set of methods that all objects in the class can use.
- The compiler creates just one accessible object for each class, a class object that knows how to build new objects belonging to the class. (For this reason it’s traditionally called a “factory object.”) The class object is the compiled version of the class; the objects it builds are instances of the class.
-The objects that do the main work of your program are instances created by the class object at runtime.
-All instances of a class have the same set of methods, and they all have a set of instance variables cut from the same mold. Each object gets its own instance variables, but the methods are shared.
By convention, class names begin with an uppercase letter (such as “Rectangle”); the names of instances typically begin with a lowercase letter (such as “myRectangle”).
Inheritance
- Class definitions are additive; each new class that you define is based on another class from which it inherits methods and instance variables. The new class simply adds to or modifies what it inherits.
- It doesn’t need to duplicate inherited code.
Inheritance links all classes together in a hierarchical tree with a single class at its root. When writing code that is based upon the Foundation framework, that root class is typically NSObject. Every class (except a root class) has a superclass one step nearer the root, and any class (including a root class) can be the superclass for any number ofsubclasses one step farther from the root.
the variables that make the object a Rectangle are added to the ones that make it a Shape, and the ones that make it a Shape are added to the ones that make it a Graphic, and so on.
Rectangle Instance Variables:
Class isa; - declared in NSObject
NSPoint origin; - declared in Shape
Pattern linePattern; - declared in Shape
float width; - declared in Rectangle
float height; - declared in Rectangle
BOOL filled; - declared in Rectangle
NSColor *color; - declared in Rectangle
Any new class you define in your program can make use of the code written for all the classes above it in the hierarchy.
Overriding One Method With Another
There’s one useful exception to inheritance: When you define a new class, you can implement a new method with the same name as one defined in a class farther up the hierarchy. The new method overrides the original; instances of the new class perform it rather than the original, and subclasses of the new class inherit it rather than the original.
Abstract Classes
Some classes are designed only or primarily so that other classes can inherit from them. These abstract classes group methods and instance variables that can be used by a number of different subclasses into a common definition. The abstract class is typically incomplete by itself, but contains useful code that reduces the implementation burden of its subclasses. (Because abstract classes must have subclasses to be useful, they’re sometimes also called abstract superclasses.)
Unlike some other languages, Objective-C does not have syntax to mark classes as abstract, nor does it prevent you from creating an instance of an abstract class.
TheNSObjectclass is the canonical example of an abstract class in Cocoa. You never use instances of theNSObjectclass in an application—it wouldn’t be good for anything; it would be a generic object with the ability to do nothing in particular.
The NSView class, on the other hand, provides an example of an abstract class instances of which you might occasionally use directly.
Abstract classes often contain code that helps define the structure of an application. When you create subclasses of these classes, instances of your new classes fit effortlessly into the application structure and work automatically with other objects.
Messages to self and super
Objective-C provides two terms that can be used within a method definition to refer to the object that performs the method—selfandsuper
Here,selfandsuperboth refer to the object receiving arepositionmessage, whatever object that may happen to be. The two terms are quite different, however.selfis one of the hidden arguments that the messaging routine passes to every method; it’s a local variable that can be used freely within a method implementation, just as the names of instance variables can be.superis a term that substitutes forselfonly as the receiver in a message expression. As receivers, the two terms differ principally in how they affect the messaging process:
-
selfsearches for the method implementation in the usual manner, starting in the dispatch table of the receiving object’s class. In the example above, it would begin with the class of the object receiving the reposition message. -
superstarts the search for the method implementation in a very different place. It begins in the superclass of the class that defines the method wheresuperappears. In the example above, it would begin with the superclass of the class where reposition is defined.
Whereversuperreceives a message, the compiler substitutes another messaging routine for theobjc_msgSendfunction. The substitute routine looks directly to the superclass of the defining class—that is, to the superclass of the class sending the message tosuper—rather than to the class of the object receiving the message.
- (id)init
{
if (self = [super init]) {...}}Redefining Selfsuperis simply a flag to the compiler telling it where to begin searching for the method to perform; it’s used only as the receiver of a message. Butselfis a variable name that can be used in any number of ways, even assigned a new value. There’s a tendency to do just that in definitions of class methods.Class methods are often concerned not with the class object,but with instances of the class. For example, many class methodscombine allocation and initialization of an instance, often settingup instance variable values at the same time. In such a method, it mightbe tempting to send messages to the newly allocated instance and to call theinstanceself, just as in an instance method. But that would be an error.selfandsuperboth refer to the receiving object—the object that gets a messagetelling it to perform the method. Inside an instance method,selfrefers to the instance; but inside a class method,selfrefers to the classobject. This is an example of what not to do:+ (Rectangle *)rectangleOfColor:(NSColor *) color{self = [[Rectangle alloc] init]; // BAD[self setColor:color];return [self autorelease];}In fact, rather than sending theallocmessage to the class in a class method,it’s often better to sendalloctoself. This way, if the class is subclassed,and therectangleOfColor:message is received by a subclass, the instance returnedwill be the same type as the subclass (for example, thearraymethod ofNSArrayisinherited byNSMutableArray).+ (id)rectangleOfColor:(NSColor *)color{id newInstance = [[self alloc] init]; // EXCELLENT[newInstance setColor:color];return [newInstance autorelease];}Static Typing
You can use a class name in place ofidto designate an object’s type:
Rectangle *myRectangle;An object can be statically typed to its own class or to any class that it inherits from. For example, since inheritance makes a Rectangle a kind of Graphic, a Rectangle instance could be statically typed to the Graphic class:
Class Objects
A class definition contains various kinds of information, much of it about instances of the class:This information is compiled and recorded in data structures made available to the runtime system. The compiler creates just one object, a class object, to represent the class. The class object has access to all the information about the class, which means mainly information about what instances of the class are like. It’s able to produce new instances according to the plan put forward in the class definition. Although a class object keeps the prototype of a class instance, it’s not an instance itself. It has no instance variables of its own and it can’t perform methods intended for instances of the class. However, a class definition can include methods intended specifically for the class object—class methods as opposed to instance methods. A class object inherits class methods from the classes above it in the hierarchy, just as instances inherit instance methods. In source code, the class object is represented by the class name. In the following example, the Rectangle class returns the class version number using a method inherited from the
- The name of the class and its superclass
- A template describing a set of instance variables
- The declarations of method names and their return and argument types
- The method implementations
NSObjectclass: Class objects are thus full-fledged objects that can be dynamically typed, receive messages, and inherit methods from other classes. They’re special only in that they’re created by the compiler, lack data structures (instance variables) of their own other than those built from the class definition, and are the agents for producing instances at runtime.
id myRectangle; myRectangle = [Rectangle alloc];
int MCLSGlobalVariable; @implementation MyClass // implementation continues
myInstance.value = 10;printf("myInstance value: %d", myInstance.value);