| advertise add site services publishers database health videos | ![]() | about toolbar stats live show health store more stuff JOIN/LOGIN |
Objective 28-5: Diabetic Eye Disease [HV2010 Eye Diseases] healthyvision2010.org | 5th World Congress of Paediatric Cardiology and Cardiac Surgery - Toward... pccs2009.com | MediCompass®| Healthier Populations Through Objective, Actionable Data imetrikus.com | Health News Review: Objective Ratings of Health and Medical Journalism healthnewsreview.org |
Objective-C is a reflective, object-oriented programming language, which adds Smalltalk-style messaging to the C programming language. Today it is used primarily on Apple's Mac OS X and iPhone OS: two environments based on, although not compliant with, the OpenStep standard.[1] Objective-C is the primary language used for Apple's Cocoa API, and it was originally used as the main language on NeXT's NeXTSTEP OS. Generic Objective-C programs which do not make use of these libraries can also be compiled for any system supported by gcc, which includes an Objective-C compiler.
[edit] HistoryIn the early 1980s, common software engineering practice was based on structured programming. The goal was to help break large programs into smaller parts, but as projects grew in size, more procedures had to be written leading to complex control structures and a low level of code reuse. Object-oriented programming emerged as a potential solution to the size problem, especially with the advent of Smalltalk. Smalltalk had already addressed many of the engineering issues related to object-oriented languages, and some of the most complex systems in the world were Smalltalk environments.[citation needed] However, Smalltalk used a virtual machine. The virtual machine interpreted an object memory called an image, containing all development tools. The Smalltalk image was very large and tended to require huge amounts of memory for the time. The virtual machine also ran very slowly, partly due to the lack of useful hardware VM/container support. 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. Cox had become interested in the problems of true reusability in software design and programming. He realized that a language like Smalltalk would be invaluable in building development environments for system developers at ITT. Cox began by modifying the C compiler to add some of the capabilities of Smalltalk. He soon had a working implementation of an object-oriented extension to the C language, which he called "OOPC" for Object-Oriented Programming in C. Meanwhile, Love was hired by Schlumberger Research in 1982 and had the opportunity to acquire the first commercial copy of Smalltalk-80, which further influenced development of their brainchild. 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. Specifically, they needed to support objects in a flexible manner, come supplied with a usable set of libraries, and allow for the code (and any resources needed by the code) to be bundled into a single cross-platform format. Love and Cox eventually formed a new venture, Productivity Products International (PPI), to commercialize their product, which coupled an Objective-C compiler with class libraries. In 1986, Cox published the main description of Objective-C in its original form in the book Object-Oriented Programming, An Evolutionary Approach. Although he was careful to point out that there is more to the problem of reusability than just the language, Objective-C often found itself compared feature for feature with other languages. [edit] Popularization through NeXTAfter Steve Jobs left Apple, he started the company NeXT. In 1988, 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. Although the NeXT workstations failed to make a great impact in the marketplace, the tools were widely lauded in the industry. This led NeXT to drop hardware production and focus on software tools, selling NeXTstep (and OpenStep) as a platform for custom programming. The GNU project started work on its free clone of NeXTStep, named GNUstep, based on the OpenStep standard. Dennis Glatting wrote the first gnu-objc runtime in 1992. The GNU Objective-C runtime, which has been in use since 1993, is the one developed by Kresten Krab Thorup when he was a university student in Denmark. Kresten also worked at NeXT from 1993 to 1996. After acquiring NeXT in 1996, Apple Inc. used OpenStep in its new operating system, Mac OS X. This included Objective-C and NeXT's Objective-C based developer tool, Project Builder (later replaced by Xcode), as well as its interface design tool, Interface Builder. Most of Apple's present-day Cocoa API is based on OpenStep interface objects, and is the most significant Objective-C environment being used for active development. [edit] SyntaxObjective-C is a thin layer on top of C, and moreover is a strict superset of C. It is possible to compile any C program with an Objective-C compiler, and to freely include C code within an Objective-C class. Objective-C derives its object syntax from Smalltalk. All of the syntax for non-object-oriented operations (including primitive variables, preprocessing, expressions, function declarations, and function calls) is identical to that of C, while the syntax for object-oriented features is an implementation of Smalltalk-style messaging. [edit] MessagesThe Objective-C model of object-oriented programming is based on message passing to object instances. In Objective-C one does not call a method; one sends a message. This is unlike the Simula-style programming model used by C++. The difference between these two concepts is in how the code referenced by the method or message name is executed. In a Simula-style language, the method name is in most cases bound to a section of code in the target class by the compiler. In Smalltalk and Objective-C, the target of a message is resolved at runtime. The receiving object itself has the task of interpreting the message. A consequence of this is that the message passing system has no type checking. The object to which the message is directed (referred to as the receiver) is not inherently guaranteed to respond to a message, and if it does not respond it simply ignores the message by returning a null pointer. Sending the message method to the object pointed to by the pointer obj would require the following code in C++: obj->method(parameter); which in Objective-C is written as follows: [obj method: parameter]; Both styles of programming have their strengths and weaknesses. Simula-style OOP allows multiple inheritance and faster execution by using compile-time binding whenever possible, but it does not support dynamic binding by default. It also forces all methods to have a corresponding implementation unless they are virtual (an implementation is still required for the method to be called). Smalltalk-style OOP allows messages to go unimplemented. For example, a message may be sent to a collection of objects, to which only some will be expected to respond, without fear of producing runtime errors. (The Cocoa platform takes advantage of this, as all objects in a Cocoa application are sent the awakeFromNib: message as the application launches. Objects may respond by executing any initialisation required at launch). Message passing also does not require that an object be defined at compile time. (See the dynamic typing section below for more advantages of dynamic (late) binding). It should be noted, however, that due to the overhead of interpreting the messages, an initial Objective-C message takes three times as long as a C++ virtual method call. Subsequent calls are IMP cached and 50% faster than the C++ virtual method call.[2] [edit] Interfaces and implementationsObjective-C requires that the interface and implementation of a class be in separately declared code blocks. By convention, the interface is put in a header file and the implementation in a code file. The header files, normally suffixed .h, are similar to C header files while the implementation (method) files, normally suffixed .m, can be very similar to C code files. [edit] InterfaceThe interface of a class is usually defined in a header file. A common convention is to name the header file after the name of the class. The interface for class Ball would thus be found in the file Ball.h. An interface declaration takes the form: @interface classname : superclassname { // instance variables } +classMethod1; +(return_type)classMethod2; +(return_type)classMethod3:(param1_type)parameter_varName; -(return_type)instanceMethod1:(param1_type)param1_varName :(param2_type)param2_varName; -(return_type)instanceMethod2WithParameter:(param1_type)param1_varName andOtherParameter:(param2_type)param2_varName; @end In the above, plus signs denote class methods and minus signs denote instance methods. Class methods have no access to instance variables. The code above is roughly equivalent to the following C++ interface: class classname : superclassname { public: // instance variables // Class (static) functions static void* classMethod1(); static return_type classMethod2(); static return_type classMethod3(param1_type parameter_varName); // Instance (member) functions return_type instanceMethod1(param1_type param1_varName, param2_type param2_varName); return_type instanceMethod2WithParameter(param1_type param1_varName, param2_type param2_varName=default); }; Note that instanceMethod2WithParameter demonstrates Objective C's named parameter capability for which there is no direct equivalent in C/C++. Return types can be any standard C type, a pointer to a generic Objective-C object, or a pointer to a specific type of object such as NSArray *, NSImage *, or NSString *. The default return type is the generic Objective-C type id. Method arguments begin with a colon followed by the expected argument type in parentheses and the argument name. In some cases (e.g. when writing system APIs) it is useful to add descriptive text before each parameter. -(void) setRangeStart:(int)start End:(int)end; -(void) importDocumentWithName:(NSString *)name withSpecifiedPreferences:(Preferences *)prefs beforePage:(int)insertPage; [edit] ImplementationThe interface only declares the class interface and not the methods themselves: the actual code is written in the implementation file. Implementation (method) files normally have the file extension .m. @implementation classname +classMethod { // implementation } -instanceMethod { // implementation } @end Methods are written using their interface declarations. Comparing Objective-C and C: -(int)method:(int)i { return [self square_root: i]; } int function(int i) { return square_root(i); } The syntax allows pseudo-naming of arguments. -(int)changeColorToRed:(float)red green:(float)green blue:(float)blue [myColor changeColorToRed:5.0 green:2.0 blue:6.0]; Internal representations of a method vary between different implementations of Objective-C. If myColor is of the class Color, internally, instance method -changeColorToRed:green:blue: might be labeled _i_Color_changeColorToRed_green_blue. The i is to refer to an instance method, with the class and then method names appended, colons translated to underscores. As the order of parameters is part of the method name, it cannot be changed to suit coding style or expression as in true named parameters. However, internal names of the function are rarely used directly. Generally, messages are converted to function calls defined in the Objective-C runtime library. 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. [edit] InstantiationOnce an Objective-C class is written, it can be instantiated. This is done by first allocating the memory for a new object and then by initializing it. An object isn't fully functional until both steps have been completed. These steps are typically accomplished with a single line of code: MyObject * o = [[MyObject alloc] init]; The alloc call allocates enough memory to hold all the instance variables for an object, and the init call can be overridden to set instance variables to specific values on creation. The init method is often written as follows: -(id) init { if ( self = [super init] ) { ivar1 = value1; ivar2 = value2; . . . } return self; } [edit] ProtocolsObjective-C was extended at NeXT to introduce the concept of multiple inheritance of specification, but not implementation, through the introduction of protocols. This is a pattern achievable either as an abstract multiply-inherited base class in C++, or as an "interface" (as in Java and C#). Objective-C makes use of ad-hoc protocols called informal protocols and compiler enforced protocols called formal protocols. An informal protocol is a list of methods which a class can opt to implement. It is specified in the documentation, since it has no presence in the language. Informal protocols often include optional methods, where implementing the method can change the behavior of a class. For example, a text field class might have a delegate which should implement an informal protocol with an optional autocomplete method. The text field discovers whether the delegate implements that method (via reflection), and, if so, calls it to support autocomplete. A formal protocol is similar to an interface in Java or C#. It is a list of methods which any class can declare itself to implement. Versions of Objective-C before 2.0 required that a class must implement all methods in a protocol it declares itself as adopting; the compiler will emit an error if the class does not implement every method of its declared protocols. Objective-C 2.0 added support for marking certain methods in a protocol optional, and the compiler will not enforce implementation of optional methods. The Objective-C concept of protocols is different from the Java or C# concept of interfaces in that a class may implement a protocol without being declared to implement that protocol. The difference is not detectable from outside code. Formal protocols cannot provide any implementations, they simply assure callers that classes which conform to the protocol will provide implementations. 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. The syntax @protocol Locking - (void)lock; - (void)unlock; @end denotes that there is the abstract idea of locking. 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. Another example use of abstract specification is describing the desired behaviors of plug-ins without constraining what the implementation hierarchy should be. [edit] Dynamic typingObjective-C, like Smalltalk, can use dynamic typing: an object can be sent a message that is not specified in its interface. This can allow for increased flexibility, as it allows an object to "capture" a message and send the message to a different object who can respond to the message appropriately, or likewise send the message on again. This behavior is known as message forwarding or delegation (see below). Alternatively, an error handler can be used in case the message cannot be forwarded. If an object does not forward a message, respond to it, or handle an error, the message is silently discarded; this is true even if messages are sent to nil (the null object pointer). Static typing information may also optionally be added to variables. This information is then checked at compile time. In the following three statements, increasingly specific type information is provided. The statements are equivalent at runtime, but the additional information allows the compiler to warn the programmer if the passed argument does not match the type specified. - setMyValue:(id) foo; In the above statement, the object may be of any class. - setMyValue:(id <aProtocol>) foo; In the above statement, the object may still be an instance of any class but the class must conform to the aProtocol protocol. - setMyValue:(NSNumber*) foo; In the above statement, foo must be a member of the NSNumber class. Dynamic typing can be a powerful feature. When implementing container classes using statically-typed languages without generics (like Java prior to version 5), the programmer is forced to write a container class for a generic type of object, and then cast back and forth between the abstract generic type and the real type. Casting, however, breaks the discipline of static typing. For instance, putting in an Integer and read out a String will produce a runtime error. This problem is addressed in, for example, Java 5 and C# with generic programming, but then container classes must be homogeneous in type. This need not be the case with dynamic typing. [edit] ForwardingObjective-C permits the sending of a message to an object that may not respond. Rather than responding or simply dropping the message, an object can forward the message to an object which can respond. Forwarding can be used to simplify implementation of certain design patterns, such as the Observer pattern or the Proxy pattern. The Objective-C runtime specifies a pair of methods in Object
- (retval_t) forward:(SEL) sel :(arglist_t) args; // with GCC - (id) forward:(SEL) sel :(marg_list) args; // with NeXT/Apple systems
- (retval_t) performv:(SEL) sel :(arglist_t) args; // with GCC - (id) performv:(SEL) sel :(marg_list) args; // with NeXT/Apple systems An object wishing to implement forwarding needs only to override the forwarding method to define the forwarding behavior. The action methods performv:: need not be overridden as this method merely performs action based on the selector and arguments. [edit] ExampleHere is an example of a program which demonstrates the basics of forwarding.
#import <objc/Object.h> @interface Forwarder : Object { id recipient; //The object we want to forward the message to. } //Accessor methods - (id) recipient; - (id) setRecipient:(id) _recipient; @end
#import "Forwarder.h" @implementation Forwarder - (retval_t) forward: (SEL) sel : (arglist_t) args { /* * Check whether the recipient actually responds to the message. * This may or may not be desirable, for example, if a recipient * in turn does not respond to the message, it might do forwarding * itself. */ if([recipient respondsTo:sel]) return [recipient performv: sel : args]; else return [self error:"Recipient does not respond"]; } - (id) setRecipient: (id) _recipient { recipient = _recipient; return self; } - (id) recipient { return recipient; } @end
#import <objc/Object.h> // A simple Recipient object. @interface Recipient : Object - (id) hello; @end
#import "Recipient.h" @implementation Recipient - (id) hello { printf("Recipient says hello!\n"); return self; } @end
#import "Forwarder.h" #import "Recipient.h" int main(void) { Forwarder *forwarder = [Forwarder new]; Recipient *recipient = [Recipient new]; [forwarder setRecipient:recipient]; //Set the recipient. /* * Observe forwarder does not respond to a hello message! It will * be forwarded. All unrecognized methods will be forwarded to * the recipient * (if the recipient responds to them, as written in the Forwarder) */ [forwarder hello]; return 0; } [edit] NotesWhen compiled using gcc, the compiler reports: $ gcc -x objective-c -Wno-import Forwarder.m Recipient.m main.m -lobjc main.m: In function `main': main.m:12: warning: `Forwarder' does not respond to `hello' $ The compiler is reporting the point made earlier, that Forwarder does not respond to hello messages. In this circumstance, it is safe to ignore the warning since forwarding was implemented. Running the program produces this output: $ ./a.out Recipient says hello! [edit] CategoriesThe maintainability of large code bases was one of the main concerns during the design of Objective C. Experience from the structured programming world had shown that one of the main ways to improve code was to break it down into smaller pieces. Objective-C borrowed and extended the concept of Categories to help with this process from Smalltalk implementations (e.g., see [3]). A category collects method implementations into separate files. The programmer can place groups of related methods into a category to make them more readable. For instance, one could create a "SpellChecking" category "on" the String object, collecting all of the methods related to spell checking into a single place. Furthermore, the methods within a category are added to a class at runtime. Thus, 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 example, if a system does not contain a spell checker in its String implementation, it could be added without modifying the String source code. Methods within categories become indistinguishable from the methods in a class when the program is run. A category has full access to all of the instance variables within the class, including private variables. Categories provide an elegant solution to the fragile base class problem for methods. If a category declares a method with the same method signature as an existing method in a class, the category’s method is adopted. Thus categories can not only add methods to a class, but also replace existing methods. This feature can be used to fix bugs in other classes by rewriting their methods, or to cause a global change to a class’ behavior within a program. If two categories have methods with the same method signature, it is undefined which category’s method is adopted. Other languages have attempted to add this feature in a variety of ways. TOM took the Objective-C system a step further and allowed for the addition of variables as well. Other languages have instead used prototype oriented solutions, the most notable being Self. The C# and Visual Basic.NET languages implement similar functionality in the form of Extension Methods and partial classes. [edit] Example usage of categoriesThis example builds up an Integer class, by defining first a basic class with only accessor methods implemented, and adding two categories, Arithmetic and Display, which extend the basic class. While categories can access the base class’ private data members, it is often good practice to access these private data members through the accessor methods, which helps keep categories more independent from the base class. This is one typical usage of categories—the other is to use categories to add or replace certain methods in the base class (however it is not regarded as good practice to use categories for subclass overriding, also known as monkey patching).
#import <objc/Object.h> @interface Integer : Object { int integer; } - (int) integer; - (id) integer: (int) _integer; @end
#import "Integer.h" @implementation Integer - (int) integer { return integer; } - (id) integer: (int) _integer { integer = _integer; return self; } @end
#import "Integer.h" @interface Integer (Arithmetic) - (id) add: (Integer *) addend; - (id) sub: (Integer *) subtrahend; @end
#import "Arithmetic.h" @implementation Integer (Arithmetic) - (id) add: (Integer *) addend { return [self integer: [self integer] + [addend integer]]; } - (id) sub: (Integer *) subtrahend { return [self integer: [self integer] - [subtrahend integer]]; } @end
#import "Integer.h" @interface Integer (Display) - (id) showstars; - (id) showint; @end
#import "Display.h" @implementation Integer (Display) - (id) showstars { int i, x = [self integer]; for(i=0; i < x; i++) printf("*"); printf("\n"); return self; } - (id) showint { printf("%d\n", [self integer]); return self; } @end
#import "Integer.h" #import "Arithmetic.h" #import "Display.h" int main(void) { Integer *num1 = [Integer new], *num2 = [Integer new]; int x; printf("Enter an integer: "); scanf("%d", &x); [num1 integer:x]; [num1 showstars]; printf("Enter an integer: "); scanf("%d", &x); [num2 integer:x]; [num2 showstars]; [num1 add:num2]; [num1 showint]; return 0; } [edit] NotesCompilation is performed, for example, by gcc -x objective-c main.m Integer.m Arithmetic.m Display.m -lobjc One can experiment by omitting the #import "Arithmetic.h" and [num1 add:num2] lines and omit Arithmetic.m in compilation. The program will still run. This means that it is possible to "mix-and-match" added categories if necessary – if one does not need to have some capability provided in a category, one can simply not compile it in. [edit] PosingObjective-C permits a class to wholly replace another class within a program. The replacing class is said to "pose as" the target class. Note: Class posing was declared deprecated with Mac OS X v10.5 and unavailable in the 64-bit runtime. For the versions still supporting posing, all messages sent to the target class are instead received by the posing class. There are several restrictions:
Posing, similarly to categories, allows global augmentation of existing classes. Posing permits two features absent from categories:
For example, @interface CustomNSApplication : NSApplication @end @implementation CustomNSApplication - (void) setMainMenu: (NSMenu*) menu { // do something with menu } @end class_poseAs ([CustomNSApplication class], [NSApplication class]); This intercepts every invocation of setMainMenu to NSApplication. [edit] | |||||||||||||||||||||||||||||||||||||||||
| Wikibooks has a book on the topic of |
| |||||||||||||||||
| ↑ top of page ↑ | about thumbshots |