Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Id Id: Note That A Variable and A Method Can Have The Same Name

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

object identifiers are a distinct data type: 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; All objects thus have an isa variable that tells them of what class they are an instance.

[receiver message]

[myRectangle display];

The method name in a message serves to select a method implementation. For this reason, method names in messages are often referred to as selectors. BOOL isFilled; isFilled = [myRectangle isFilled];

[myRectangle setPrimaryColor:[otherRect primaryColor]]; [myRectangle setOriginX: 30.0 y: 50.0]; // This is a good example of multiple Arguments

Note that a variable and a method can have the same name myInstance.value = 10; printf("myInstance value: %d", myInstance.value); The dot syntax is purely syntactic sugarit is transformed by the compiler into invocation of accessor methods (so you are not actually accessing an instance variable directly). The code example above is exactly equivalent to the following: [myInstance setValue:10]; printf("myInstance value: %d", [myInstance value]);

graphic.text = @"Hello"; @"Hello" is a constant NSString object


[graphic setBounds:NSMakeRect(10.0, 10.0, 20.0, 120.0)];

graphic.bounds = NSMakeRect(10.0, 10.0, 20.0, 120.0);

Classes
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 its 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).
Class objects also inherit from the classes above them in the hierarchy. But because they dont have instance variables (only instances do), they inherit only methods.

NSObject is a root class, and so doesnt have a superclass. It defines the basic framework for Objective-C objects and object interactions. It imparts to the classes and instances of classes that inherit from it the ability to behave as objects and cooperate with the runtime system. Although a subclass can override inherited methods, it cant override inherited instance variables. Since an object has memory allocated for every instance variable it inherits, you cant override an inherited variable by declaring a new one with the same name. If you try, the compiler will complain Objective-C does not have syntax to mark classes as abstract, nor does it prevent you from creating an instance of an abstract class (abstract superclasses) A class definition is a specification for a kind of object. The class, in effect, defines a data type. A class name can appear in source code wherever a type specifier is permitted in C for example, as an argument to the sizeof operator: int i = sizeof(Rectangle);

Static Typing

Rectangle *myRectangle; 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 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: if ( [anObject isMemberOfClass:someClass] ) ... 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): if ( [anObject isKindOfClass:someClass] ) Class Object
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. Its able to produce new instances according to the plan put forward in the class definition.

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 NSObject class: int versionNumber = [Rectangle version]; 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: id aClass = [anObject class]; id rectClass = [Rectangle class];

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: Class aClass = [anObject class]; Class rectClass = [Rectangle class]; All class objects are of type Class. Using this type name for a class is equivalent to using the class name to statically type an instance. Class objects are thus full-fledged objects that can be dynamically typed, receive messages, and inherit methods from other classes. Theyre special only in that theyre 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

Class Interface:
@interface ClassName : ItsSuperclass { instance variable declarations } method declarations @end

(void)setRadius:(float)aRadius; - (void)setWidth:(float)width height:(float)height; The names of methods that can be used by class objects, class methods, are preceded by a plus sign: + alloc; The methods that instances of a class can use, instance methods, are marked with a minus sign: - (void)display;

The interface file must be included in any source module that depends on the class interfacethat includes any module that creates an instance of the class, sends a

message to invoke a method declared for the class, or mentions an instance variable declared in the class. The interface is usually included with the #import directive:
#import "Rectangle.h"

This directive is identical to #include except that it makes sure that the same file is never , included more than once. Its therefore preferred

Note that if there is a precompa precompiled headerthat supports the superclass, you may prefer to import the precomp instead
If the interface mentions classes not in this hierarchy, it must import them explicitly or declare them with the @class directive:
@class Rectangle, Circle;

This directive simply informs the compiler that Rectangle and Circle are class names. It doesnt import their interface files

The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name @interface Worker : NSObject { char *name; @private int age; char *evaluation; @protected id job; float wage; @public id boss; } By default, all unmarked instance variables (like name above) are @protected.

Self and Super

- negotiate { ... return [super negotiate]; } Initializing super class before subclass - (id)init { if (self = [super init]) { ... } }
steps to create an object using Objective-C.
id anObject = [[Rectangle al loc ] in i t ] ;

memory for new objects is allocated using class methods defined in the NSObject class. NSObject defines two principal methods for this purpose, alloc and allocWithZone The alloc and allocWithZone: methods initialize a newly allocated objects isa instance variable so that it points to the objects class (the class object). All other instance variables are set to 0. Every class that declares instance variables must provide an init... method to initialize them. The NSObject class declares the isa variable and defines an init method. However, since isa is initialized when memory for an object is allocated, all NSObjects init method does is return self. NSObject declares the method mainly to establish the naming convention described earlier Handling Initialization Failure If theres a chance that the init... method might return nil, then you should check the return value before proceeding:

id anObject = [ [SomeClass al l oc ] in i t ] ; i f ( anObject ) [anObject someOtherMessage] ; else

...

Read the design patterns chapter in Cocoa Fundamentals Guide, Delegation Model View Controller Target-Action Delegation is a pattern where one object may send messages to another object Model objects represent data such as SpaceShips and Rockets in a game, ToDo items and Contacts in a productivity application, or Circles and Squares in a drawing application. In this application, the dta is going to be very simplejust a string View objects know how to display data and may allow the user to edit the data. In this application you need a main view to contain several other viewsa text field to capture information from the user, a second text field to display text based on the users input, and a button to let the user tell us that the secondary text should be updated. Controller objects mediate between models and views. In this application, the controller object will take the data from the input text field, store it in a string, and update a secod text field appropriately. The update will be initiated as a result of an action sent by the button.

Target-Action
The target-action mechanism enables a control objectthat is, an object such as a button or sliderin response to a user event (such as a click or a tap) to send a message (the action) to another object (the target) that can interpret the message and handle it as an application-specific instruction. In this application, when its tapped, a button tells the controller to update its model and view based on the users input. If you name your project something else, then the application delegate class will be called YourProjectNameAppDelegate The template project you created already sets up the basic application environment. It creates an application object, connects to the window server, establishes the run loop, and so on. Most of the work is done by the UIAppl i ca t i onMain The main function in main.m calls the UIApplicationMain function:
int retVal = UIAppl i ca t i onMain(argc, argv, ni l , ni l ) ;

When the application object has completed its setup, it sends its delegate an applicationDidFinishLaunching: message. Rather than configuring the user interface itself, the delegate typically creates a view controller object (a special controller responsible for managing

a viewthis adheres to the model-view-controller design pattern as described in Model-View-Controller (page 10)). The delegate asks the view controller for its view (which the view controller creates on demand) and adds that as a subview of the window.

You might also like