DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE
DESHMUKHI (VI), POCHAMPALLY (M), NALGONDA (DT), ANDHRA PRADESH, PIN – 508284.

OBJECTIVE C

SUBMITTED BY S.UPENDHAR (07891A0565)

UNDER THE GUIDANCE OF MR. G.YEDUKONDALU ASST.PROFESSOR

S.UPENDHAR 07891A0565 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE
DESHMUKHI (VI), POCHAMPALLY (M), NALGONDA (DT), ANDHRA PRADESH, PIN – 508284.

CERTIFICATE

This is to certify that the Technical Seminar titled “OBJECTIVE C” is a bona fide work of MR.S.UPENDHAR (07891A0565) carried out under our guidance and supervision, for the award of Bachelor of Technology Degree in Computer Science and Engineering by Jawaharlal Nehru Technological University, Hyderabad. The contents of this report have not been submitted to any University / Institute for the award of any other Degree / Diploma.

Signature Mr. N.Sreekanth Head of the Department Computer Science and Engineering

Signature Mr.G.Yedukondalu Guide

Page 2 of 34

S.UPENDHAR 07891A0565

ACKNOWLEDGEMENT At the outset, I thank the Lord Almighty for the grace, strength and hope to make my endeavor a success.

I also express my gratitude to Mr. N.Sreekanth, Head of the Department and Mr. G.Yedukondalu, Technical Seminar Guide for providing me with adequate facilities, ways and means by which I was able to complete this seminar. I express my sincere gratitude to him for his constant support and valuable suggestions without which the successful completion of this seminar would not have been possible.

I thank my Technical Seminar guide for his boundless cooperation and helps extended for this seminar. I express my immense pleasure and thankfulness to all the staff of the Department of Computer Science and Engineering, VITS for their cooperation and support.

Last but not the least, I thank all others, and especially my classmates and my family members who in one way or another helped me in the successful completion of this work.

S.Upendhar (07891A0565)

Page 3 of 34

1 HISTORY………………………………………………….27 3.3 INSTANTIATION……………………………….2 INTERFACE AND IMPLEMENTATION….2 INTERFACES AND IMPLEMENTATION………….8 #import……………………………………………………29 4.07 2. OVERVIEW…………………………………………………….09 2.31 7. C++ VS.06 2. OTHER FEATURES OF OBJECTIVE C…………………….19 3.20 3..3 PROTOCOLS……………………………………………22 3. OBJECTIVE C……………………………………….08 2. CONCLUSION………………………………………………….2 IMPLEMENTATION……………………………..25 3.2..2 OBJECT ORIENTED PROGRAMMING……………..7 POSING………………………………………………….2..13 3.... NEED FOR OBJECTIVE C……………………………………29 5.1 POPULARIZATION THROUGH NeXT…………..16 3.2.2.26 3.06 2..NO 1.1 INTERFACE………………………………………17 3.S.07 2.5 FORWARDING…………………………………………. CHAPTER NAME PG... CHARACTERSTICS OF OBJECTIVE C……………………14 3.30 6.24 3. INTRODUCTION………………………………………………05 2....4 DYNAMIC TYPING…………………………………….3 OBJECTIVE C………………………………………….UPENDHAR 07891A0565 TABLE OF CONTENTS SL..2.1.1 MESSAGES………………………………………………15 3..1 DATA AND OPERATIONS……………………..32 Page 4 of 34 .6 CATAGORIES…………………………………………...NO.

faster to develop. It adds a small number of constructs to the C language and defines a handful of conventions for effectively interacting with the runtime system. Its additions to C are mostly based on Smalltalk. Objective-C is designed to give C full object-oriented programming capabilities. REFERENCES………………………………………………….33 1. and easier to understand. object-oriented programming language that adds Smalltalk-style messaging to the C programming language. and to do so in a simple and straightforward way.UPENDHAR 07891A0565 8. Most object-oriented development environments consist of several parts: • An object-oriented programming language A library of objects A suite of development tools A runtime environment • • • Objective-C is a reflective.S. The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. INTRODUCTION An object-oriented approach to application development makes programs more intuitive to design. one of the first object-oriented programming languages. more amenable to modification. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. Page 5 of 34 .

which coupled an Page 6 of 34 . In order to demonstrate that real progress could be made. Cox showed that making interchangeable software components really needed only a few practical changes to existing tools. which he called "OOPC" for Object-Oriented Programming in C.UPENDHAR 07891A0565 Today. Love and Cox eventually formed a new venture. Productivity Products International (PPI). and it was originally the main language on NeXT's NeXTSTEP OS.1 HISTORY Objective-C was created primarily by Brad Cox and Tom Love in the early 1980s at their company Stepstone. Both had been introduced to Smalltalk while at ITT Corporation’s Programming Technology Center in 1981. come supplied with a usable set of libraries. Objective-C is the primary language used for Apple's Cocoa API. Cox began by modifying the C compiler to add some of the capabilities of Smalltalk. to commercialize their product. which further influenced the development of their brainchild. though not compliant with it. Cox was intrigued by problems of true reusability in software design and programming. OVERVIEW 2. and allow for the code (and any resources needed by the code) to be bundled into a single cross-platform format. He realized that a language like Smalltalk would be invaluable in building development environments for system developers at ITT. 2. they needed to support objects in a flexible manner. it is used primarily on Apple's Mac OS X and iOS: two environments based on the OpenStep standard. Love was hired by Schlumberger Research in 1982 and had the opportunity to acquire the first commercial copy of Smalltalk-80.S. He soon had a working implementation of an object-oriented extension to the C language. Specifically.

Most of Apple's present-day Cocoa API is based on OpenStep interface objects. The GNU Objective-C runtime. Although he was careful to point out that there is more to the problem of reusability than just the language. Page 7 of 34 . While the NeXT workstations failed to make a great impact in the marketplace. which has been in use since 1993.1. This led NeXT to drop hardware production and focus on software tools. In 1988. named GNUstep. Apple Computer used OpenStep in its new operating system.1 Popularization through NeXT After Steve Jobs left Apple Inc.UPENDHAR 07891A0565 Objective-C compiler with class libraries. 2. an Evolutionary Approach. the tools were widely lauded in the industry. The GNU project started work on its free clone of NeXTStep. and is the most significant Objective-C environment being used for active development. Cox published the main description of Objective-C in its original form in the book Object-Oriented Programming. Objective-C often found it compared feature for feature with other languages. This included Objective-C and NeXT's Objective-C based developer tool. Interface Builder. is the one developed by Kresten Krab Thorup when he was a university student in Denmark. based on the OpenStep standard. he started the company NeXT. NeXT licensed Objective-C from StepStone (the owner of the Objective-C trademark) and released its own Objective-C compiler and libraries on which the NeXTstep user interface and interface builder were based. Project Builder (later replaced by Xcode)..S. In 1986. selling NeXTstep (and OpenStep) as a platform for custom programming. After acquiring NeXT in 1996. Dennis Glatting wrote the first GNU Objective-C runtime in 1992. Mac OS X. as well as its interface design tool. Thorup also worked at NeXT from 1993 to 1996.

that’s about all there is to it. grounded in the way computers work.2. This division is. of course. With a procedural programming language like C. At some point.1 Data and Operations Programming languages have traditionally divided the world into two parts—data and operations on data. Object orientation provides an abstraction of the data on which you operate. moreover. 2. The procedures and functions that operate on data have no lasting state of their own. Like the equally pervasive distinctions between matter and energy and between nouns and verbs. expose patterns and frameworks. but it won’t divide the world any differently. they’re useful only in their ability to affect data. we must abstract underlying structure away from surface details and discover the fundamental relations at work. Abstractions reveal causes and effects. it provides a concrete grouping between the data and the operations you can perform with the data—in effect giving the data behavior. Functions and data structures are the basic elements of design. we’re constantly faced with myriad facts and impressions that we must make sense of. so it’s not one that you can easily ignore or push aside. it forms the background against which we work. Data is static and immutable.2 OBJECT ORIENTED PROGRAMMING As humans. all programmers—even object-oriented programmers—must lay out the data structures that their programs will use and define the functions that will act on the data. except as the operations may change it. To do so. and separate what’s important from what’s not. The language may offer various kinds of support for organizing data and functions.UPENDHAR 07891A0565 2. Page 8 of 34 .S.

In an object-oriented programming language.UPENDHAR 07891A0565 Object-oriented programming doesn’t so much dispute this view of the world as restructure it at a higher level. how warm its contents are) with behavior (the ability to dispense its contents at various flow rates. In that. such as a pocket watch or a piano. It should let you make our ideas concrete in the code we write. They can not only model components of real systems.2 Interface and Implementation To invent programs. It’s easy to see how a mechanical device. It’s the job of a programming language to help us to do this. too. It groups operations and data into modular units called objects and lets you combine objects into structured networks to form a complete program. But almost anything that’s designed to do a job does. embodies both state and behavior. to withstand high or low temperatures). It’s this resemblance to real things that gives objects much of their power and appeal. they’re not much different from ordinary physical objects. these devices are ways of grouping implementation details. Even simple things with no moving parts such as an ordinary bottle combine state (how full the bottle is.S. Surface details shouldn’t obscure the architecture of our program. at least to some extent.2. and giving them. Every object has both state (data) and behavior (operations on data). whether or not it’s open. objects and object interactions are the basic elements of design. The language should facilitate the process of invention and design by letting you encode abstractions that reveal the way things work. 2. we need to be able to capture abstractions and express them in the program design. but equally as well fulfill assigned roles as components in software systems. a common Page 9 of 34 . hiding them. All programming languages provide devices that help express abstractions. In essence. to be opened or closed.

we’d be concerned with what it’s composed of and how it works.S. as illustrated in Figure. as the implementers. We can look past the details and think solely in terms of the role that the unit plays at a higher level. but as what those elements taken together represent. so a complex arrangement of information can be built from simpler layers. much of the program can regard it as a single thing— not as a collection of elements. While some code must delve inside the structure and manipulate the fields separately. Looking at it from the outside.UPENDHAR 07891A0565 interface—much as a mechanical object separates its interface from its implementation. we’re concerned only with what it is and what it does. as the user. Figure -1 Interface and implementation Looking at such a unit from the inside. Both. hide elements of the implementation: • On the data side of the world. C structures group data elements into larger units that can then be handled as single entities. One structure can include others. The principal units of abstraction in the C language are structures and functions. in different ways. Page 10 of 34 .

• On the procedural side of the world. functions encapsulate behaviors that can be used repeatedly without being reimplemented. their names won’t conflict with identically named data elements outside the structure. Imagine. at the highest level. for example. unlike data elements. All the user needs is the function interface. functions aren’t partitioned into separate namespaces. Each function must have a unique name. Because functions can reference (call) other functions. Functions are reusable.UPENDHAR 07891A0565 In modern C. Data elements local to a function. Although the function may be reusable. In a procedural programming language. Once defined. not the source code. the highest units of abstraction still live on one side or the other of the data-versus-operations divide. The programs you design must always reflect. they can be called any number of times without again considering the implementation. but they maintain the distinction between data and operations on data. complex behaviors can be built from smaller pieces. C structures and functions are able to express significant abstractions. the fields of a structure live in their own namespace —that is. However. The most generally useful functions can be collected in libraries and reused in many different applications. are protected within their own namespace. the way the computer works. the enormous task of assigning a different name to every piece of data in a large program and of making sure new names don’t conflict with old ones. its name is not. Partitioning the program namespace is essential for keeping implementation details out of the interface.S. Page 11 of 34 . like the fields within a structure.

a unit that hides the interaction between a function and its data.UPENDHAR 07891A0565 Object-oriented programming languages don’t lose any of the virtues of structures and functions—they go a step further and add a unit capable of abstraction at a higher level. the interface to the functions has become much simpler. all that’s exported to users is a functional interface. The next step is to give this idea support in the programming language and completely hide the data structure so that it doesn’t even have to be passed between the functions. With these changes. and freeing its memory—is done through the functions. We want to make those functions easier to use by. So we supply a few additional functions to manage the data. It’s fair now to call this an object. Suppose. keeping it up to date. We’ve taken the first step toward creating an object. not on how the data is organized.S. The data becomes an internal implementation detail. With this step. users can think of them solely in terms of their behavior. for example. initializing it. the structure has become an opaque token that other programmers never need to look inside. getting information from it. modifying values within it. taking the structure out of the interface. as far as possible. All the work of manipulating the data structure—allocating memory for it. All the user does is call the functions and pass the structure to them. that we have a group of functions that act on a particular data structure. Because objects completely encapsulate their data (hide it). They can concentrate on what the functions do. Page 12 of 34 . Callers don’t need to know how they’re implemented (what data they use).

It may seem unfamiliar at first. but as you gain experience with object-oriented programming. Page 13 of 34 . controllers. for example. This progression from thinking about functions and data structures to thinking about object behaviors is the essence of learning object-oriented programming. So an object is more than a collection of random functions. Implementing such things as programming objects merely extends the analogy in a natural way. A programming language can be judged by the kinds of abstractions that it enables you to encode. tables. we’re forced at all times to be aware of the entire program at a low level of implementation. While we might still invent programs at a high level of abstraction. Everyday programming terminology is replete with analogies to realworld objects of various kinds—lists.UPENDHAR 07891A0565 The hidden data structure unites all the functions that share access to it. even managers. you find it’s a more natural way to think about things. the path from imagination to implementation can become quite tenuous—and more and more difficult as programs become bigger and more complicated. To use a function that belongs to an object. you first create the object (thus giving it its internal data structure). If. it’s a bundle of related behaviors that are supported by shared data. and then tell the object which function it should perform. rather than in terms of the individual functions.S. We shouldn’t be distracted by extraneous matters or forced to express ourself using a vocabulary that doesn’t match the reality we’re trying to capture. we must always tend to the business of keeping the right data matched with the right procedure. You begin to think in terms of what the object does. containers.

Objective-C does not respect public and private as does C++. higher level of abstraction.UPENDHAR 07891A0565 By providing another. object-oriented programming languages give us a larger vocabulary and a richer model to program in. When reading Objective-C code. Objective-C does not have a constructor or destructor. It knows about them. Page 14 of 34 .S. This is over-simplification. Instead it has init and free methods. the method and variable use different cases to differentiate them. The Objective-C class allows a method and a variable with the exact same name. Assuming you already know C and C++. 2. C++ uses static to specify a factory method. with embedded Smalltalk.to differentiate between factory and instance methods.3 OBJECTIVE C Objective-C is a blend of C and Smalltalk. In C++. which must be called explicitly. Objective-C uses + and . There is nothing in the Objective-C language that requires them to be called init and free. but doesn't really use them. they must be different. an easy way to understand the syntax is to know that [anObject aMethod] in ObjectiveC is the same as anObject->aMethod() in C++. In Listing 1. it's just a standard practice. but it is a useful rule for getting started. Most of it is straight C. then you know most of the syntax of Objective-C.

it simply raises an exception. A method is identified by a selector or SEL — a NULL-terminated string representing its name — and resolved to a C method pointer implementing it: an IMP. one sends a message. CHARACTERSTICS OF OBJECTIVE C Objective-C is a thin layer on top of C. and if it does not. expressions. it is possible to compile any C program with an Objective-C compiler. with the receiving object itself interpreting the message. In Objective-C one does not call a method. the method name is in most cases bound to a section of code in the target class by the compiler. Sending the message method to the object pointed to by the pointer obj would require the following code in C++: Page 15 of 34 . Objective-C derives its object syntax from Smalltalk. In Smalltalk and Objective-C. The object to which the message is directed — the receiver — is not guaranteed to respond to a message. This is unlike the Simula-style programming model used by C++. preprocessing. while the syntax for object-oriented features is an implementation of Smalltalkstyle messaging.UPENDHAR 07891A0565 3. the target of a message is resolved at runtime. 3. and to freely include C code within an Objective-C class.S. In a Simula-style language. All of the syntax for non-object-oriented operations (including primitive variables.1 Messages The Objective-C model of object-oriented programming is based on message passing to object instances. and function calls) are identical to that of C. and moreover is a strict superset of C. A consequence of this is that the message passing system has no type checking. function declarations. The difference between these two concepts is in how the code referenced by the method or message name is executed.

the virtual functions table in C++ can also be thought as a function pointers cache. When a virtual function call is compiled. That value can then be embedded directly into the machine code of the caller by the compiler. It also forces all methods to have a corresponding implementation unless they are virtual. Message passing also does not require that an object be defined at compile time. without fear of producing runtime errors. with the method resolved to its implementation at runtime. Only a direct non-virtual call to a function's address is faster. this is written as follows: [obj method: argument]. no other Page 16 of 34 . Due to the overhead of interpreting the messages. Both styles of programming have their strengths and weaknesses. a message may be sent to a collection of objects. In Objective-C.The fairness of that comparison is unclear. its index in the v-table (table of virtual functions) is known. Subsequent calls are IMP cached and are claimed to be 50% faster than the C++ virtual method call. For example. an initial Objective-C message takes three times as long as a C++ virtual method call. Moreover.UPENDHAR 07891A0565 obj->method(argument).S. to which only some will be expected to respond. Consequently. but it does not support dynamic binding by default. An implementation is still required for the method to be called in the derived object. however. Objectoriented programming in the Simula style allows multiple inheritances and faster execution by using compile-time binding whenever possible. meaning the method is a placeholder for methods with the same name to be defined in objects derived from the base object. as it disregards the time needed to decide whether a call is IMP-cached. Smalltalk-style programming allows messages to go unimplemented. This embedding is the optimal scenario.

UPENDHAR 07891A0565 indirect mechanism such as the caching mechanism. normally suffixed . 3. The header files. can be faster. Page 17 of 34 .h would contain the interface for the class Ball. A common convention is to name the header file after the name of the class.S. e.h.2 Interfaces and implementations Objective-C requires that the interface and implementation of a class be in separately declared code blocks. 3. are similar to C header files while the implementation (method) files. in Objective-C or otherwise. Ball.m. (return_type)instanceMethod1:(param1_type)param1_varName andOtherParameter:(param2_type)param2_varName. can be very similar to C code files. + (return_type)classMethod3:(param1_type)param1_varName.g.1 Interface The interface of a class is usually defined in a header file.2. An interface declaration takes the form: @interface classname : superclassname { // instance variables } + classMethod1. By convention. normally suffixed . + (return_type)classMethod2. developers place the interface in a header file and the implementation in a code file.

S. // Instance (member) functions return_type instanceMethod1(param1_type param1_varName. static return_type classMethod2(). which can only be called within a particular instance of the class. or methods that can be called without an instance of the class. return_type }. The code above is roughly equivalent to the following C++ interface: class classname : public superclassname { public: // instance variables // Class (static) functions static void * classMethod1(). param2_type param2_varName=default).UPENDHAR 07891A0565 - (return_type)instanceMethod2WithParameter: andOtherParameter: (param1_type)param1_varName (param2_type)param2_varName. instanceMethod2WithParameter(param1_type param1_varName. param2_type param2_varName). static return_type classMethod3(param1_type param1_varName). Page 18 of 34 . plus signs denote class methods. @end In the above. Class methods also have no access to instance variables. and minus signs denote instance methods.

Return types can be any standard C type. for which there is no direct equivalent in C/C++. In some cases (e. NSImage *. Method arguments begin with a colon followed by the expected argument type in parentheses and the argument name.2. or a pointer to a specific type of object such as NSArray *.UPENDHAR 07891A0565 Note that instanceMethod2WithParameter:andOtherParameter: demonstrates Objective-C's named parameter capability. a pointer to a generic ObjectiveC object. when writing system APIs) it is useful to add descriptive text before each parameter.(void)setRangeStart:(int)start end:(int)end.m. 3. The default return type is the generic Objective-C type id. @implementation classname + (return_type)classMethod { // implementation } .S.(return_type)instanceMethod { // implementation Page 19 of 34 . or NSString *. Implementation (method) files normally have the file extension . which originally signified "messages".2 Implementation The interface only declares the class interface and not the methods themselves: the actual code is written in the implementation file.g. (void)importDocumentWithName:(NSString *)name withSpecifiedPreferences:(Preferences *)prefs beforePage:(int)insertPage. .

instance -changeColorToRed:green:blue: _i_Color_changeColorToRed_green_blue. internal names of the function are rarely used directly. it cannot be changed to suit coding style or expression as with true named parameters. . The i is to refer to an instance method.UPENDHAR 07891A0565 } @end Methods are written using their interface declarations.0].(int)changeColorToRed:(float)red green:(float)green blue:(float)blue. As the order of parameters is part of the method name. } The syntax allows pseudo-naming of arguments. } int function (int i) { return square_root(i). Generally. with the class and then method names appended and colons changed to underscores. Comparing Objective-C and C: . However.0 green:2. messages are converted to function calls defined in the Objective-C Page 20 of 34 .0 blue:6. If myColor is of the class Color. Internal method representations of a method might vary be between internally different labeled implementations of Objective-C. [myColor changeColorToRed:5.(int)method:(int)i { return [self square_root:i].S.

This is done by first allocating the memory for a new object and then by initializing it. Instantiation with the default. and the init message performs the set-up of the instance upon creation.2. no-parameter initializer: MyObject *o = [[MyObject alloc] init].(id)init { if (self = [super init]) { Page 21 of 34 . The alloc message allocates enough memory to hold all the instance variables for an object. An object is not fully functional until both steps have been completed.UPENDHAR 07891A0565 runtime library. 3. It is not necessarily known at link time which method will be called because the class of the receiver (the object being sent the message) need not be known until runtime. it can be instantiated. These steps should be accomplished with a single line of code so that there is never an allocated object that hasn't undergone initialization.3 Instantiation Once an Objective-C class is written. Instantiation with a custom initializer: MyObject *o = [[MyObject alloc] initWithString:myString].S. The init method is often written as follows: . the "new" method can often be used in place of the alloc-init messages: MyObject *o = [MyObject new]. In the case where no custom initialization is being performed.

which is treated as the boolean value false. If there is an error in initialization the init method should perform any necessary cleanup and return nil to indicate that initialization failed. self = [super init] Assigns self (a pointer to the current object) to the result of sending the superclass an init message. } In the above example. This is the type of any object in Objective-C. It performs the following actions: 1. 3. A non-valid object pointer has the value nil. [super init] Sends the superclass an init message. notice the id return type. 2.UPENDHAR 07891A0565 // perform initialization of object here } return self.S. The construct "if (self = [super init])" is used in order to assure that the object is properly initialized by its superclass before the init method performs its initialization. Page 22 of 34 . if (self = [super init]) Checks if the returned object pointer is valid before performing any initialization.

The difference is not detectable from outside code. For example.0 required that a class must implement all methods in a protocol it declares itself as adopting. if so. the compiler will emit an error if the class does not implement every method from its declared protocols. but not implementation. since it has no presence in the language. The text field discovers whether the delegate implements that method (via reflection) and. a text field class might have a delegate that implements an informal protocol with an optional method for performing auto-completion of user-typed text. which. Informal protocols often include optional methods. and the compiler will not enforce implementation of optional methods. It is specified in the documentation. calls the delegate's method to support the auto-complete feature. Objective-C makes use of ad hoc protocols called informal protocols and compiler-enforced protocols called formal protocols. in that a class may implement a protocol without being declared to implement that protocol. An informal protocol is a list of methods that a class can opt to implement. if implemented. Versions of Objective-C before 2. Formal protocols cannot provide any implementations. The Objective-C concept of protocols is different from the Java or C# concept of interfaces.0 added support for marking certain methods in a protocol optional. they Page 23 of 34 . It is a list of methods that any class can declare itself to implement. This is a pattern achievable either as an abstract multiply-inherited base class in C++.3 Protocols Objective-C was extended at NeXT to introduce the concept of multiple inheritance of specification. can change the behavior of a class. through the introduction of protocols. A formal protocol is similar to an interface in Java or C#. Objective-C 2.S.UPENDHAR 07891A0565 3. or as an "interface" (as in Java and C#).

an error handler can be Page 24 of 34 .4 Dynamic typing Objective-C. In the NeXT/Apple library. protocols are frequently used by the Distributed Objects system to represent the capabilities of an object executing on a remote system.S.(void)unlock. By stating that the protocol is implemented in the class definition: @interface SomeClass : SomeSuperClass <Locking> @end instances of SomeClass claim that they will provide an implementation for the two instance methods using whatever means they choose. The syntax @protocol Locking .(void)lock. @end denotes that there is the abstract idea of locking. can use dynamic typing: an object can be sent a message that is not specified in its interface. This can allow for increased flexibility. like Smalltalk. . Another example use of abstract specification is describing the desired behaviors of plug-ins without constraining what the implementation hierarchy should be. 3. or likewise send the message on to another object.UPENDHAR 07891A0565 simply assure callers that classes that conform to the protocol will provide implementations. Alternatively. This behavior is known as message forwarding or delegation (see below). as it allows an object to "capture" a message and send the message to a different object that can respond to the message appropriately.

In the above statement. and then cast back and forth between the abstract generic type and the real type. If messages are sent to nil (the null object pointer). The statements are equivalent at runtime. This problem is addressed in. breaks the discipline of static typing. but the additional information allows the compiler to warn the programmer if the passed argument does not match the type specified.(void)setMyValue:(id)foo. for example. Static typing information may also optionally be added to variables. . If an object does not forward a message.S. In the following three statements. the programmer is forced to write a container class for a generic type of object. foo may be of any class. depending on compiler options. Page 25 of 34 . putting in an integer and reading out a string will produce a runtime error. . the message is silently discarded. foo must be an instance of the NSNumber class. or handle an error. When implementing container classes using statically-typed languages without generics (like Java prior to version 5). In the above statement. increasingly specific type information is provided.(void)setMyValue:(id<aProtocol>)foo. Dynamic typing can be a powerful feature. Java 5 and C# with generic programming. In the above statement. This information is then checked at compile time. For instance. . Casting. they will be silently ignored or raise a generic exception. however. respond to it. foo may still be an instance of any class.UPENDHAR 07891A0565 used in case the message cannot be forwarded.(void)setMyValue:(NSNumber *)foo. but the class must conform to the aProtocol protocol.

(retval_t)forward:(SEL)sel args:(arglist_t)args. as this method merely performs an action based on the selector and arguments.5 Forwarding Objective-C permits the sending of a message to an object that may not respond. Notice the SEL type.(id)forward:(SEL)sel args:(marg_list)args.(retval_t)performv:(SEL)sel args:(arglist_t)args. // with GCC . // with NeXT/Apple systems An object wishing to implement forwarding needs only to override the forwarding method with a new method to define the forwarding behavior. an object can forward the message to an object that can respond. This need not be the case with dynamic typing. Forwarding can be used to simplify implementation of certain design patterns. one of the main concerns was the maintainability of large code bases.UPENDHAR 07891A0565 but then container classes must be homogeneous in type.S. // with NeXT/Apple systems • action methods: . 3. • forwarding methods: . // with GCC . The Objective-C runtime specifies a pair of methods in Object. The action method performv:: need not be overridden. Experience from the structured Page 26 of 34 .(id)performv:(SEL)sel args:(marg_list)args. such as the Observer pattern or the Proxy pattern. which is the type of messages in Objective-C. 3. Rather than responding or simply dropping the message.6 Categories During the design of Objective-C.

This feature can be used to fix bugs in other classes by rewriting their methods. or to cause a global change to a class’s behavior within a program. but also replace existing methods. Methods within categories become indistinguishable from the methods in a class when the program is run.S. Furthermore. Other languages have attempted to add this feature in a variety of ways. including private variables. Thus. the methods within a category are added to a class at runtime. A category has full access to all of the instance variables within the class. it could be added without modifying the String source code. For example. A category collects method implementations into separate files. If two categories have methods with the same name (not to be confused with method signature). it is undefined which category’s method is adopted. the category’s method is adopted.UPENDHAR 07891A0565 programming world had shown that one of the main ways to improve code was to break it down into smaller pieces. The programmer can place groups of related methods into a category to make them more readable. Objective-C borrowed and extended the concept of categories from Smalltalk implementations to help with this process. one could create a "SpellChecking" category in the String object. collecting all of the methods related to spell checking into a single place. If a category declares a method with the same method signature as an existing method in a class. Thus categories can not only add methods to a class. if a system does not contain a spell checker in its String implementation. categories permit the programmer to add methods to an existing class without the need to recompile that class or even have access to its source code. For instance. TOM took the Objective-C system a step further and allowed for the addition of Page 27 of 34 .

UPENDHAR 07891A0565 variables as well.S. Posing. 3. all messages sent to the target class are instead received by the posing class. Posing permits two features absent from categories: • A posing class can call overridden methods through super. Page 28 of 34 . For the versions still supporting posing.NET languages implement similar functionality in the form of extension methods. • The posing class must not define any new instance variables that are absent from the target class (though it may define or override methods). with the most notable being Self. The C# and Visual Basic.7 Posing Objective-C permits a class to wholly replace another class within a program. Ruby and several other dynamic programming languages refer to the technique as "monkey patching". Other languages have used prototype oriented solutions instead. For example . allows global augmentation of existing classes. similarly with categories. • The target class may not have received any messages prior to the posing. The replacing class is said to "pose as" the target class. • A posing class can override methods defined in categories. thus incorporating the implementation of the target class. There are several restrictions: • A class may only pose as one of its direct or indirect superclasses.

NEED FOR OBJECTIVE C The Objective-C language was chosen for a variety of reasons. Second. existing C programs can be adapted to use the software frameworks without losing any of the work that went into their original development. 3.8 #import In the C language.S. we get all the benefits of C when working Page 29 of 34 .UPENDHAR 07891A0565 @interface CustomNSApplication : NSApplication @end @implementation CustomNSApplication . The kind of functionality that’s packaged in the Cocoa frameworks can only be delivered through objectoriented techniques. First and foremost. it’s an object-oriented language. Because Objective-C incorporates C. 4.(void) setMainMenu: (NSMenu*) menu { // do something with menu } @end class_poseAs ([CustomNSApplication class]. because Objective-C is an extension of standard ANSI C. Objective-C has the equivalent #import directive except each file is included only once per compilation unit. the #include pre-compile directive always causes a file's contents to be inserted into the source at that point. This intercepts every invocation of setMainMenu to NSApplication. [NSApplication class]).

often presents a steep learning curve to new recruits.S. with its self-conscious terminology and emphasis on abstract design. The compiler preserves a great deal of information about the objects themselves for use at runtime. Messages are not necessarily constrained by either the class of the receiver or even the method name. Dynamism gives Objective-C programs unusual flexibility and power. so a software framework can allow for user choices at runtime and permit developers freedom of expression in their design.) • Dynamism enables the construction of sophisticated development tools. An interface to the runtime system provides access to information about running applications. a style that can accommodate a simple architecture for interactive user interfaces. Compared to other object-oriented languages based on C. Object-oriented programming. and receiver are explained in due course in this document.UPENDHAR 07891A0565 within Objective-C. (Terminology such as dynamic binding. for example) and when to stick to procedural programming techniques (define a structure and some functions instead of a class). Objective-C is very dynamic. We can choose when to do something in an object-oriented way (define a new class. unambiguous. Decisions that otherwise might be made at compile time can be postponed until the program is running. and easy to learn. A well-organized language like ObjectiveC can make becoming a proficient object-oriented programmer that much less difficult. For example. so it’s possible to develop Page 30 of 34 . Objective-C is a fundamentally simple language. class. Its syntax is small. it yields two big benefits that are hard to get with other nominally object-oriented languages: • Objective-C supports an open style of dynamic binding. message. Moreover.

Objective-C objects tend to be large. it only means that the trend is for Objective-C objects to be large. This does not mean that there can't be small Objective-C objects and large C++ objects. intervene. 6. • Swizzling of the isa pointer allows for classes to change at runtime. where Objective-C objects tend to be more standalone. C++ VS. OBJECTIVE C: Think of Objective-C objects like a factory.UPENDHAR 07891A0565 tools that monitor. C++ objects also tend to come in groups. solutions to programming issues. and often easy. Swizzling is used today by Apple’s Foundation Framework to implement Key-Value Observing. OTHER FEATURES Objective-C's features often allow for flexible. Swizzling was also used in Enterprise Objects Framework to create database faults.S. standalone objects and C++ objects to be small and dependent on one another. C++ objects tend to be small and to the point. Typically used for debugging where freed objects are swizzled into zombie objects whose only purpose is to report an error when someone calls them. Page 31 of 34 . commonly called Archiving in Objective-C. • Delegating methods to other objects and remote invocation can be easily implemented using categories and message forwarding. can be done by overriding read and write methods. self contained. and do everything imaginable. • Serialization. and reveal the underlying structure and activity of Objective-C applications. and C++ objects like a home business. 5.

no matter how small.S.UPENDHAR 07891A0565 When programming in C++. or any other kind of checking imaginable. having less than 100 objects in an application lets me keep the entire structure of the program in my head. I find writing applications in Objective-C much easier and faster than writing the same applications in C++. I have seen programmers spend days trying to get the syntax Page 32 of 34 . In C++. and all interconnected. each and every concept. but C++ has solved some of these problems by using Namespaces. Another reason why Objective-C is faster to develop in is that it is a simpler language. In Objective-C. Having thousands of Objective-C objects is asking for trouble. C++. This can lead to name collisions. Even without Namespaces. if not thousands of classes. Objective-C objects should be able to stand on their own. Two classes can have the same name if they are private and never included by the same file. type checking. and object names are resolved at runtime. with its zero overhead for non-virtual classes. Despite many applications having been written in C++. only one name space. Objective-C has a lot of overhead for an object. It is not practical to have Objective-C classes for rects. encourages programmers to subclass ints. and C++ having many features over Objective-C. C++ can avoid name collisions by including only needed header files. Writing a little bit of code can give range checking. One of the biggest reasons for this is the number of objects found in an application. should get its own class. Applications typically have hundreds. and any other data structure. where each concept is its own object. rects. and there is no operator overloading. or other small data structures. There are no private objects. I am constantly looking for which object contains the functionality I'm looking for. ints. value checking. each one small.

Each time you want to include functionality from an object. Objective-C does not have as many areas where language lawyers thrive. you are likely required to include additional 10-20 objects. It is C with a small number of extensions. Objective-C is different from C++. The worst part of C++'s esoteric syntax is other programmers might not be able to understand some of the more complex C++ code. In Objective-C the dynamic type of an object determines whether it can receive a message.S. so if you need functionality. or occasionally a small number of related objects. The biggest reason for the faster developement time is the self-contained object. you only need to include that one object.UPENDHAR 07891A0565 of an esoteric C++ function just right. C++ is traditionally associated with the Simula 67 school of object-oriented programming where Objective-C has SmallTalk roots. the static type of an object determines whether it can receive a message. The Simula 67 format is more structured and allows problems to be detected earlier when a program is compiled. The Smalltalk approach delays it's typing until runtime and is touted as a more flexible alternative. on the other hand. Page 33 of 34 . CONCLUSION Objective-C is an object-oriented extension to the C language. Objective-C objects tend to be self-contained. In C++. tend to come in groups. C++ objects. 7. Although the differences can fade into shades of grey.

Dynamic Binding and Dynamic Loading. 8.html • • http://www.com/library/mac/#documentation/Cocoa/Conceptu al/OOP_ObjC/Articles/ooOOP.UPENDHAR 07891A0565 This flexibility extends the language into three separate areas: Dynamic Typing.13/13.03/CandObjectiveC Compared/ • https://www.indiana.apple.S.cs.html Page 34 of 34 .mactech.com/articles/mactech/Vol.wikipedia.org/wiki/Objective_c http://developer. REFERENCES • http://en.edu/classes/c304/ObjC.

Sign up to vote on this title
UsefulNot useful