| Objective-C | |
|---|---|
| Paradigm | reflective, object oriented |
| Appeared in | 1986 |
| Designed by | Brad Cox and Tom Love |
| Developer | Apple Inc. |
| Typing discipline | duck, static, weak |
| Major implementations | gcc, Apple |
| Influenced by | Smalltalk, C |
| Influenced | TOM, Java |
Objective-C, often referred to as ObjC and sometimes as Objective C or Obj-C, is a reflective, object-oriented programming language which adds Smalltalk-style messaging to C. A programming paradigm is a fundamental style of Computer programming. In Computer science, reflection is the process by which a Computer program can observe and modify its own structure and behavior Object-oriented programming (OOP is a Programming paradigm that uses " objects " and their interactions to design applications and computer programs Brad Cox is a Computer scientist and PhD of Mathematical biology known mostly for his work in Software engineering (specifically Software A software developer is a person or organization concerned with facets of the software development process wider than design and coding a somewhat broader scope of Apple Inc, ( formerly Apple Computer Inc, is an American Multinational corporation with a focus on designing and manufacturing Consumer electronics In Computer science, a type system defines how a Programming language classifies values and expressions into '''types''', how it can In Computer programming, duck typing is a style of Dynamic typing in which an object's current set of methods and properties determines the valid In Computer science, a type system defines how a Programming language classifies values and expressions into '''types''', how it can In Computer science, weak typing (aka loose typing) is a property attributed to the Type systems of some Programming languages It is the opposite Implementation is the realization of an application or execution of a Plan, idea Model, Design, Specification, standard, Algorithm The GNU Compiler Collection (usually shortened to GCC) is a set of Compilers produced for various Programming languages by the GNU Project Apple Inc, ( formerly Apple Computer Inc, is an American Multinational corporation with a focus on designing and manufacturing Consumer electronics Smalltalk is an object-oriented, dynamically typed, reflective programming language. tags please moot on the talk page first! --> In Computing, C is a general-purpose cross-platform block structured TOM was an Object oriented Programming language developed in the 1990s that built upon the lessons learned from Objective-C. In Computer science, reflection is the process by which a Computer program can observe and modify its own structure and behavior Object-oriented programming (OOP is a Programming paradigm that uses " objects " and their interactions to design applications and computer programs A programming language is an Artificial language that can be used to write programs which control the behavior of a machine particularly a Computer. Smalltalk is an object-oriented, dynamically typed, reflective programming language. In Computer science, message passing is a form of communication used in Parallel computing, Object-oriented programming, and Interprocess communication tags please moot on the talk page first! --> In Computing, C is a general-purpose cross-platform block structured
Today it is used primarily on Mac OS X and GNUstep, two environments based on the OpenStep standard (although Mac OS X is OpenStep incompatible), and is the primary language used for the NeXTSTEP, OPENSTEP, and Cocoa application frameworks. Mac OS X (mæk oʊ ɛs tɛn is a line of computer Operating systems developed marketed and sold by Apple Inc, the latest of which is pre-loaded on all currently GNUstep is a Free software implementation of NeXT 's OpenStep Objective-C libraries (called frameworks) Widget toolkit OpenStep is an Object-oriented Application programming interface (API specification for an Object-oriented operating system that uses any modern Operating Nextstep was the original object-oriented, multitasking Operating system that NeXT Computer developed to run on its range of proprietary computers OpenStep is an Object-oriented Application programming interface (API specification for an Object-oriented operating system that uses any modern Operating Cocoa is Apple Inc 's native Object-oriented application program environment for the Mac OS X Operating system 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. The GNU Compiler Collection (usually shortened to GCC) is a set of Compilers produced for various Programming languages by the GNU Project
Contents |
In the early 1980s, common software engineering practice was based on structured programming. The 1980s was the decade spanning from January 1 1980 to December 31 1989. Software engineering is the application of a systematic disciplined quantifiable approach to the development operation and maintenance of Software. Structured programming can be seen as a subset or subdiscipline of Procedural programming, one of the major Programming paradigms It is most famous for removing or Structured programming was implemented in order to help "break down" programs into smaller parts, primarily to make them easier to work on as they grew increasingly large. However, as the problems being solved grew in size, structured programming became less useful as more and more procedures had to be written, leading to complex control structures and poor code reuse, but not spaghetti code, as some believe (modular coding was designed to eliminate that; it was not a panacea, though). Spaghetti code is a Pejorative term for Source code which has a complex and tangled Control structure, especially one using many GOTOs exceptions
Many saw object-oriented programming as a potential solution to the problem. Object-oriented programming (OOP is a Programming paradigm that uses " objects " and their interactions to design applications and computer programs In fact, Smalltalk had already addressed many of these engineering issues: some of the most complex systems in the world were Smalltalk environments. Smalltalk is an object-oriented, dynamically typed, reflective programming language. On the downside, Smalltalk used a virtual machine. In Computer science, a virtual machine (VM is a Software implementation of a machine (computer that executes programs like a real 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 and ran very slowly, partly due to the lack of useful hardware vm/container support. Computer data storage, often called storage or memory, refers to Computer components devices and recording media that retain digital
Objective-C was created primarily by Brad Cox and Tom Love in the early 1980s at their company Stepstone. Brad Cox is a Computer scientist and PhD of Mathematical biology known mostly for his work in Software engineering (specifically Software StepStone is the name of a worldwide total talent software company In the USA - Stepstone (originally Productivity Products International) was a software company Both had been introduced to Smalltalk while at ITT’s Programming Technology Center in 1981. ITT Corporation, is a global diversified manufacturing company with 2007 revenues of $9 Cox had become interested in the problems of true reusability in software design and programming. Software engineering is the application of a systematic disciplined quantifiable approach to the development operation and maintenance of Software. He realized that a language like Smalltalk would be invaluable in building powerful 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. Love, meanwhile, 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. Component-based software engineering (CBSE (also known as Component-Based Development (CBD or Software Componentry) is a branch of the Software engineering Specifically, they needed to support objects in a flexible manner, come supplied with a set of libraries which were usable, and allow for the code (and any resources needed by the code) to be bundled into a single cross-platform format.
Cox and Love eventually formed a new venture, Productivity Products International (PPI), to commercialize their product, which coupled an Objective-C compiler with powerful 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.
In 1988, NeXT, the next company started by Steve Jobs after Apple, licensed Objective-C from StepStone (the owner of the Objective-C trademark) and released their own Objective-C compiler and libraries on which the NeXTstep user interface and interface builder were based. Year 1988 ( MCMLXXXVIII) was a Leap year starting on Friday (link displays 1988 Gregorian calendar) NeXT Computer Inc (later NeXT Software Inc) was an American Computer company headquartered in Redwood City, California that Steven Paul Jobs (born February 24 1955 is the Co-founder, Chairman, and CEO of Apple Inc and former CEO of Pixar Animation Nextstep was the original object-oriented, multitasking Operating system that NeXT Computer developed to run on its range of proprietary computers Although the NeXT workstations failed to make much of an 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 their free clone of NeXTStep, named GNUstep, based on the OpenStep standard. GNUstep is a Free software implementation of NeXT 's OpenStep Objective-C libraries (called frameworks) Widget toolkit OpenStep is an Object-oriented Application programming interface (API specification for an Object-oriented operating system that uses any modern Operating Dennis Glatting wrote the first gnu-objc runtime in 1992, and Richard Stallman followed with a second one shortly after. In Computer science, runtime or run time describes the operation of a Computer program, the duration of its execution from beginning to termination Year 1992 ( MCMXCII) was a Leap year starting on Wednesday (link will display full 1992 Gregorian calendar) Richard Matthew Stallman (born March 16 1953 often abbreviated " rms " is an American software freedom activist 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. Year 1993 ( MCMXCIII) was a Common year starting on Friday (link will display full 1993 Gregorian calendar) Kresten also worked at NeXT for a while.
After acquiring NeXT in 1996, Apple used OpenStep in its new operating system, Mac OS X. Year 1996 ( MCMXCVI) was a Leap year starting on Monday (link will display full 1996 Gregorian calendar) Apple Inc, ( formerly Apple Computer Inc, is an American Multinational corporation with a focus on designing and manufacturing Consumer electronics Mac OS X (mæk oʊ ɛs tɛn is a line of computer Operating systems developed marketed and sold by Apple Inc, the latest of which is pre-loaded on all currently 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. Xcode is a suite of tools for developing software on Mac OS X, developed by Apple. Xcode is a suite of tools for developing software on Mac OS X, developed by Apple. Interface Builder is a Software development application for Apple's Mac OS X Operating system. 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. Cocoa is Apple Inc 's native Object-oriented application program environment for the Mac OS X Operating system
Objective-C is a very "thin" layer on top of C. Objective-C is a strict superset of C. That is, it is possible to compile any C program with an Objective-C compiler. Objective-C derives its syntax from both C and Smalltalk. Most of the syntax (including preprocessing, expressions, function declarations, and function calls) is inherited from C, while the syntax for object-oriented features was created to enable Smalltalk-style message passing.
The added syntax is for built-in support of object-oriented programming. Object-oriented programming (OOP is a Programming paradigm that uses " objects " and their interactions to design applications and computer programs The Objective-C model of object-oriented programming is based on sending messages to objects, similar to the model of Smalltalk. In Computer science, message passing is a form of communication used in Parallel computing, Object-oriented programming, and Interprocess communication Smalltalk is an object-oriented, dynamically typed, reflective programming language. This is unlike the Simula programming model, which is used by C++ among other programming languages. Simula is a name for two programming languages Simula I and Simula 67 developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl C++ (" C Plus Plus " ˌsiːˌplʌsˈplʌs is a general-purpose Programming language. This distinction is semantically important. The basic difference is that in Objective-C, one does not call a method; one sends a message.
An object called obj whose class has a method doSomething implemented is said to "respond" to the message doSomething. Sending a doSomething message to obj would require the following code in C++:
obj. doSomething();
In Objective-C, that same line would be written this way:
[obj doSomething];
This mechanism allows messages to be sent to an object even if the object is not able to respond to them. This differs from statically typed languages such as C++ and Java in which all method calls to objects must be predefined. In Computer science, a type system defines how a Programming language classifies values and expressions into '''types''', how it can (See the dynamic typing section below. )
Objective-C requires the interface and implementation of a class to 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, suffixed . h, are similar to C header files.
The interface of the class is usually defined in a header file. Convention is usually to create the name of the header file based on the name of the class. So if we have the class Thing, Thing’s interface goes in the file Thing. h.
The interface declaration is in this form:
@interface classname : superclass name { 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
Hyphens mark instance methods and plus signs mark class methods (like static member functions in C++). In Object-oriented programming, the term method refers to a Subroutine that is exclusively associated either with a class (called class methods In Object-oriented programming, the term method refers to a Subroutine that is exclusively associated either with a class (called class methods This is different from the meaning of a preceding – and + in UML diagrams which mean private and public method, respectively. the Unified Modeling Language (UML a class diagram is a type of static structure diagram that describes the structure of a system by showing the system's classes
Return types can be any standard C type such as void which indicates that no value is returned, primitive types such as float, int and BOOL, and pointers to Objective-C classes such as NSArray *, NSString *, and NSImage *. In Objective-C, the return type id represents a pointer to an arbitrary object. If no return type is specified as with classMethod1, the return type is assumed to be id.
In all methods, parameters are defined with a colon followed by the expected parameter type in parentheses and the parameter name. In some cases it is useful to add descriptive text before each parameter, and in some cases it is unnecessary. When working with large projects it is often very useful to have long, descriptive method names that make it easier to determine how each parameter is used.
-(void) setRange:(int)start :(int)end; -(void) importDocumentWithName:(NSString *)name withSpecifiedPreferences:(Preferences *)prefs beforePage:(int)insertPage;
The interface only declares the prototypes for the methods, and not the methods themselves, which go in the implementation. The implementation is usually stored in a main file, for example, Thing. m. The implementation is written
@implementation classname + classMethod { // implementation } - instanceMethod { // implementation } @end
Methods are written in a different way from C-style functions. For example, a function in both C and Objective-C follows this general form:
int do_something(int i) { return square_root(i); }
with int do_something(int) as the prototype.
When this is implemented as a method, this becomes:
- (int) do_something:(int) i { return [self square_root: i]; }
A more canonical way of writing the above method would be like this, by naming the first argument in the selector name:
- (int) doSomethingWithInt: (int) i { return [self squareRootOfInt:i]; }
This syntax may appear to be more troublesome but it allows pseudo-naming of parameters, for example
- (int) changeColorWithRed:(int) r green:(int) g blue:(int) b
which can be invoked thus:
[myColor changeColorWithRed:5 green:2 blue:6];
Internal representations of this method vary between different implementations of Objective-C. Canonical is an Adjective derived from canon. Canon comes from the Greek word kanon, "rule" (perhaps originally from In Computer programming, named parameters refers to a computer language's support for function calls that clearly state the name of each parameter within the If myColor is of the class Color, internally, instance method -changeColorWithRed:green:blue: might be labeled _i_Color_changeColorWithRed_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, and generally even message-sends are converted to a call to a function defined in a run-time library rather than directly accessing the internal name. This is partially because it is rarely known at compile-time which method will actually be called, because the class of the receiver (i. e. , the object being sent the message) is rarely known until runtime.
Once 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 { self = [super init]; if (self) { ivar1 = value1; ivar2 = value2; . . . } return self; }
Objective-C was extended at NeXT to introduce the concept of multiple inheritance of specification, but not implementation, through the introduction of protocols. NeXT Computer Inc (later NeXT Software Inc) was an American Computer company headquartered in Redwood City, California that Multiple inheritance refers to a feature of some object-oriented Programming languages in which a class can inherit behaviors and features from This is a pattern achievable either as an abstract multiply inherited base class in C++, or else, more popularly, adopted (e. g. , in Java or C#) as an "interface". Objective-C makes use of both 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 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. In Computer science, reflection is the process by which a Computer program can observe and modify its own structure and behavior
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. However, Objective-C 2. 0 added support for marking certain methods in a protocol optional; the compiler will not enforce that such methods are implemented.
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 which is useful, and when stated in a class definition
@interface SomeClass : SomeSuperClass <Locking> @end
denotes that instances of SomeClass will provide an implementation for the two instance methods using whatever means they want. This abstract specification is particularly useful to describe the desired behaviors of plug-ins for example, without constraining at all what the implementation hierarchy should be.
Objective-C, like Smalltalk, can use dynamic typing; we can send an object a message not specified in its interface. In Computer science, a type system defines how a Programming language classifies values and expressions into '''types''', how it can This can allow for increased flexibility — in Objective-C an object can "capture" this message, and depending on the object, can send the message off again to a different object (who can respond to the message correctly and 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 instead, in case the message cannot be forwarded. If the object does not forward the message, handle the error, or respond to it, a runtime error occurs. In Computer science, runtime or run time describes the operation of a Computer program, the duration of its execution from beginning to termination
Static typing information may also optionally be added to variables. This information is then checked at compile time. In the following 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. In the first statement, the object may be of any class. In the second statement, the object must conform to the aProtocol protocol, and in the third, it must be a member of the NSNumber class.
- setMyValue:(id) foo; - setMyValue:(id <aProtocol>) foo; - setMyValue:(NSNumber*)foo;
Dynamic typing can be a powerful feature. When implementing container classes using statically-typed languages without generics like pre-1. 5 Java, 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. In Computer science, a container is a class, a Data structure, or an Abstract data type (ADT whose instances are collections of other objects Casting however breaks the discipline of static typing – if you put in an Integer and read out a String, you get an error. In Computer science, type conversion or typecasting refers to changing an entity of one Data type into another In Computer science, a type system defines how a Programming language classifies values and expressions into '''types''', how it can The integers (from the Latin integer, literally "untouched" hence "whole" the word entire comes from the same origin but via French In Computer programming and some branches of Mathematics, a string is an ordered Sequence of Symbols. One way of alleviating the problem is to resort to generic programming, but then container classes must be homogeneous in type. Generic programming is a style of Computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated This need not be the case with dynamic typing.
Since Objective-C permits the sending of a message to an object which might not respond to it, the object has a number of things it can do with the message. One of these things could be to forward the message on to an object which can respond to it. Forwarding can be used to implement certain design patterns, such as the Observer pattern or the Proxy pattern very simply. In Software engineering, a design pattern is a general reusable solution to a commonly occurring problem in Software design. The observer pattern (sometimes known as Publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a In Computer programming, the proxy pattern is a Software design 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
and as such an object wishing to implement forwarding needs only to override the forwarding method to define the forwarding behaviour. The action methods performv:: need not be overridden as this method merely performs the method based on the selector and arguments.
Here 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 - forward: (SEL) sel : (marg_list) 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; }
If we were to compile the program, the compiler would report
$ 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 certain circumstances, such a warning can help us find errors, but in this circumstance, we can safely ignore this warning, since we have implemented forwarding. If we were to run the program
$ . /a. out Recipient says hello!
Cox’s main concern was the maintainability of large code bases. 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 added the concept of Categories to help with this process.
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. In Computer science, runtime or run time describes the operation of a Computer program, the duration of its execution from beginning to termination 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 the system you are supplied with does not contain a spell checker in its String implementation, you can add it without modifying the String source code. In Computing, a spell checker is an applications program that flags words in a document that may not be spelled correctly
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. The fragile base class problem is a fundamental architectural problem of Object-oriented programming systems where base classes ( superclasses are considered "fragile"
If you declare a method in a category with the same method signature as an existing method in a class, the category’s method is adopted. In Computer programming, especially Object-oriented programming, a method is commonly identified by its unique method signature. 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. TOM was an Object oriented Programming language developed in the 1990s that built upon the lessons learned from Objective-C. Other languages have instead used prototype oriented solutions, the most notable being Self. Prototype-based programming is a style of Object-oriented programming in which classes are not present and behavior reuse (known as inheritance in class-based Self is an object-oriented programming language based on the concept of prototypes.
This 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. In Object-oriented programming, the term method refers to a Subroutine that is exclusively associated either with a class (called class methods Whilst 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).
#include <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; } @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]; }
Compilation 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.
Objective-C permits a class to wholly replace another class within a program. The replacing class is said to "pose as" the target class. All messages sent to the target class are then instead received by the posing class. There are several restrictions on which classes can pose:
Posing, similarly to categories, allows globally augmenting 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.
However, class posing was declared deprecated with Mac OS X v10.5 and unavailable in the 64-bit runtime. Mac OS X version 105 “Leopard” is the sixth major release of Mac OS X, Apple’s desktop and server Operating system for Macintosh
#importIn the C language, the #include pre-compile directive allows for the insertion of entire files before any compilation actually begins. Objective-C adds the #import directive, which does the same thing, except that it knows not to insert a file which has already been inserted.
For example, if file A includes files X and Y, but X and Y each include the file Q, then Q will be inserted twice into the resultant file, causing "duplicate definition" compile errors. But if file Q is included using the #import directive, only the first inclusion of Q will occur—all others will be ignored.
A few compilers, including GCC, support #import for C programs too; its use is discouraged on the basis that the user of the header file has to distinguish headers which should be included only once, from headers designed to be used multiple times. The GNU Compiler Collection (usually shortened to GCC) is a set of Compilers produced for various Programming languages by the GNU Project It is argued that this burden should be placed on the implementor; to this end, the implementor may place the directive #pragma once in the header file, or use the traditional #include guard technique:
#ifndef HEADER_H #define HEADER_H . In the C and C++ programming languages #pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source In the C and C++ programming languages an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of . . contents of header. h . . . #endif
If a header file uses guards or #pragma once, it makes no difference whether it is #included or #imported. The same objection to #import actually applies to Objective-C as well, and many Objective-C programs also use guards in their headers.
Objective-C's features often allow for flexible, and oftentimes easy, solutions to programming issues.
Objective-C++ is a front-end to the GNU Compiler Collection which can compile source files which use a combination of C++ and Objective-C syntax. The GNU Compiler Collection (usually shortened to GCC) is a set of Compilers produced for various Programming languages by the GNU Project Objective-C++ adds to C++ the extensions Objective-C adds to C. As nothing is done to unify the semantics behind the various language features, certain restrictions apply:
At the 2006 Worldwide Developers Conference, Apple announced the forthcoming release of "Objective-C 2. 0," a revision of the Objective-C language to include "modern garbage collection, syntax enhancements[1], runtime performance improvements[2], and 64-bit support". Mac OS X v10.5, released in October 2007, included an Objective-C 2. Mac OS X version 105 “Leopard” is the sixth major release of Mac OS X, Apple’s desktop and server Operating system for Macintosh 0 compiler. It is not yet known when these language improvements will be available in the GNU runtime.
Objective-C 2. 0 provides an optional conservative yet generational garbage collector. When run in backwards-compatible mode, the runtime turns reference counting operations such as "retain" and "release" into no-ops. In Technology, especially Computing (irrespective of platform a product is said to be backward compatible when it is able to take the place of an older product In Computer science, reference counting is a technique of storing the number of references pointers or handles to a resource such as an object or block of memory In Computer science NOP or NOOP (short for N o OP eration) is an Assembly language instruction sequence of programming All objects are subject to garbage collection when garbage collection is enabled. Regular C pointers may be qualified with "__strong" to also trigger the underlying write-barrier compiler intercepts and thus participate in garbage collection. A zero-ing weak subsystem is also provided such that pointers marked as "__weak" are set to zero when the object (or more simply GC memory) is collected.
Objective-C 2. 0 introduces a new syntax to declare instance variables as properties, with optional attributes to configure the generation of accessor methods. In some object-oriented Programming languages a property is a special sort of class member intermediate between a field (or Data member A property may be declared as "readonly", and may be provided with storage semantics such as "assign", "copy" or "retain".
@interface Person : NSObject { @public NSString *name; @private int age; } @property(copy) NSString *name; @property(readonly) int age; -(id)initWithAge:(int)age; @end
Properties are implemented by way of the @synthesize keyword, which generates getter and setter methods according to the property declaration. Alternately, the @dynamic keyword can be used to indicate that accessor methods will be provided by other means.
@implementation Person @synthesize name; @dynamic age; -(id)initWithAge:(int)initAge { age = initAge; // NOTE: direct instance variable assignment, not property setter return self; } -(int)age { return 29; // NOTE: lying about age } @end
Properties can be accessed using dot notation or by name via the "valueForKey:"/"setValue:forKey:" methods.
Person *aPerson = [[Person alloc] initWithAge: 53]; aPerson. name = @"Steve"; // NOTE: dot notation, uses synthesized setter NSLog(@"Access by getter(%@), property name(%@) and direct instance variable access (%@)", aPerson. name, [aPerson valueForKey:@"name"], aPerson->name);
In order to use dot notation to invoke property accessors within an instance method, the "self" keyword should be used:
-(void) introduceMyselfWithProperties:(BOOL)useGetter { NSLog(@"Hi, my name is %@. ", (useGetter ? self. name : name)); // NOTE: getter vs. ivar access }
A class or protocol's properties may be dynamically introspected. In Computing, type introspection is a capability of some Object-oriented programming languages to determine the type of an object at Runtime
int i, propertyCount = 0; objc_property_t *propertyList = class_copyPropertyList([aPerson class], &propertyCount); for (i=0; i<propertyCount; i++) { objc_property_t *thisProperty = propertyList + i; const char* propertyName = property_getName(*thisProperty); NSLog(@"Person has a property: '%s'", propertyName); }
Instead of using an Enumerator object to iterate through a collection, Objective-C 2. 0 offers the foreach syntax. The following two loops are equivalent in Objective-C 2. 0.
for (int i=0; i<[thePeople count]; i++) { Person *p = [thePeople objectAtIndex:i]; NSLog(@"%@ is %i years old. ", [p getName], [p getAge]); } for (Person *p in thePeople) NSLog(@"%@ is %i years old. ", [p getName], [p getAge]);
All Objective-C applications developed for Mac OS X that make use of the above improvements for Objective-C 2. 0 are incompatible with all operating systems prior to 10. 5 (Leopard).
Even using fast enumeration, which one might expect to generate the exact same binaries as standard enumeration, will cause an application to crash on OS X version 10. 4 or earlier. In fact, Apple claims fast enumeration generates more efficient code than standard enumeration.
There are also many added methods and constants in the Objective-C 2. 0 Cocoa framework that appear in completion lists and cause incompatibility with earlier systems. Xcode running on Leopard offers no warning that 10. 5-specific functions are being used so it is good practice to get well acquainted with Cocoa classes before developing with them if you want your application to be compatible with older versions of Mac OS X.
Objective-C today is often used in tandem with a fixed library of standard objects (often known as a "kit" or "framework"), such as Cocoa or GNUstep. These libraries often come with the operating system: the GNUstep libraries often come with Linux distributions and Cocoa comes with Mac OS X. A Linux distribution (also called GNU/Linux by distributions such as Debian, Fedora, Ubuntu, Linux Mint, Mandriva and The programmer is not forced to inherit functionality from the existing base class (NSObject). Objective-C allows for the declaration of new root classes which do not inherit any existing functionality. Originally, Objective-C based programming environments typically offered an Object class as the base class from which almost all other classes inherited. With the introduction of OpenStep, NeXT created a new base class named NSObject which offered additional features over Object (an emphasis on using object references and reference counting instead of raw pointers, for example). Almost all classes in Cocoa inherit from NSObject.
Not only did the renaming serve to differentiate the new default behavior of classes within the OpenStep API, but it allowed code which used Object — the original base class used on NeXTSTEP (and, more or less, other Objective-C class libraries) — to co-exist in the same runtime with code which used NSObject (with some limitations). As well, the introduction of the two letter prefix became a sort of simplistic form of namespaces, which Objective-C lacks. Using a prefix to create an informal packaging identifier became an informal coding standard in the Objective-C community, and continues to this day.
Besides the GCC/NeXT/Apple Computer implementation, which added several extensions to the original Stepstone implementation, there exists another free open-source Objective-C implementation, which implements a slightly different set of extensions: The Portable Object Compiler [3] implements, among other things, also Smalltalk-like blocks for Objective-C. The GNU Compiler Collection (usually shortened to GCC) is a set of Compilers produced for various Programming languages by the GNU Project NeXT Computer Inc (later NeXT Software Inc) was an American Computer company headquartered in Redwood City, California that Apple Inc, ( formerly Apple Computer Inc, is an American Multinational corporation with a focus on designing and manufacturing Consumer electronics StepStone is the name of a worldwide total talent software company In the USA - Stepstone (originally Productivity Products International) was a software company Free and open source software, also F/OSS, FOSS, or FLOSS (for Free/Libre/Open Source Software) is software which is liberally licensed Smalltalk is an object-oriented, dynamically typed, reflective programming language.
Objective-C implementations use a thin runtime written in C which adds little to the size of the application. In Computer science, runtime or run time describes the operation of a Computer program, the duration of its execution from beginning to termination In contrast, most OO systems at the time that it was created (and Java even today) used large virtual machine runtimes. In Computer science, a virtual machine (VM is a Software implementation of a machine (computer that executes programs like a real machine Programs written in Objective-C tend to be not much larger than the size of their code and that of the libraries (which generally do not need to be included in the software distribution), in contrast to Smalltalk systems where a large amount of memory was used just to open a window. A software distribution, also referred to as a software distro, is a bundle of a specific Software (or a collection of multiple even an entire Operating Objective-C applications tend to be larger than similar C or C++ applications because Objective-C dynamic typing does not allow methods to be stripped or inlined.
Likewise, the language can be implemented on top of existing C compilers (in GCC, first as a preprocessor, then as a module) rather than as a new compiler. The GNU Compiler Collection (usually shortened to GCC) is a set of Compilers produced for various Programming languages by the GNU Project This allows Objective-C to leverage the huge existing collection of C code, libraries, tools, and mindshare. Existing C libraries — even in object code libraries — can be wrapped in Objective-C wrappers to provide an OO-style interface. In Computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) translates one interface
All of these practical changes lowered the barrier to entry, likely the biggest problem for the widespread acceptance of Smalltalk in the 1980s. In Economics and especially in the theory of Competition, barriers to entry are obstacles in the path of a firm which wants to enter a given Market
The first versions of Objective-C did not support garbage collection. In Computer science, garbage collection ( GC) is a form of automatic Memory management. At the time this decision was a matter of some debate, and many people considered long "dead times" (when Smalltalk did collection) to render the entire system unusable. Although some 3rd party implementations have added this feature (most notably GNUstep), Apple implemented it as of Mac OS X v10.5. Mac OS X version 105 “Leopard” is the sixth major release of Mac OS X, Apple’s desktop and server Operating system for Macintosh [1]
Another common criticism is that Objective-C does not have language support for namespaces. A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers (i Instead programmers are forced to add prefixes to their class names, which can cause collisions. As of 2007, all Mac OS X classes and functions in the Cocoa programming environment are prefixed with "NS" (as in NSObject or NSButton) to clearly identify them as belonging to the Mac OS X core; the "NS" derives from the names of the classes as defined during the development of NeXTSTEP. Year 2007 ( MMVII) was a Common year starting on Monday of the Gregorian calendar in the 21st century. Cocoa is Apple Inc 's native Object-oriented application program environment for the Mac OS X Operating system Nextstep was the original object-oriented, multitasking Operating system that NeXT Computer developed to run on its range of proprietary computers
Since Objective-C is a strict superset of C, it does not treat C primitive types as first-class objects either. In Computing, a first-class object (also value, entity, and citizen) in the context of a particular Programming language, is an entity
Unlike C++, Objective-C does not support operator overloading. C++ (" C Plus Plus " ˌsiːˌplʌsˈplʌs is a general-purpose Programming language. In Computer programming, operator overloading (less commonly known as operator Ad-hoc polymorphism) is a specific case of polymorphism in Also unlike C++, Objective-C allows an object only to directly inherit from one class (forbidding multiple inheritance). Multiple inheritance refers to a feature of some object-oriented Programming languages in which a class can inherit behaviors and features from However, categories and protocols may be used as alternative functionality to multiple inheritance.
Because Objective-C uses dynamic runtime typing and because all method calls are function calls (or, in some cases, syscalls), many common performance optimizations cannot be applied to Objective-C methods (for example: inlining, constant propagation, interprocedural optimizations, and scalar replacement of aggregates). This limits the performance of Objective-C abstractions relative to similar abstractions in languages such as C++. Proponents of Objective-C claim that it should not be used for low level abstraction in the way that C++ or Java are used, because Objective-C is known to have a high runtime cost.
The design and implementation of C++ and Objective-C represent different approaches to extending C. C++ (" C Plus Plus " ˌsiːˌplʌsˈplʌs is a general-purpose Programming language.
In addition to C’s style of procedural programming, C++ directly supports object-oriented programming, generic programming, and metaprogramming. Object-oriented programming (OOP is a Programming paradigm that uses " objects " and their interactions to design applications and computer programs Generic programming is a style of Computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated Metaprogramming is the writing of Computer programs that write or manipulate other programs (or themselves as their data or that do part of the work at Compile time C++ also comes with a large standard library which includes several container classes. In Computer science, a container is a class, a Data structure, or an Abstract data type (ADT whose instances are collections of other objects Objective-C, on the other hand, adds only object-oriented features to C. Objective-C in its purest fashion does not contain the same number of standard library features, but in most places where Objective-C is used, it is used with an OpenStep-like library such as OPENSTEP, Cocoa, or GNUstep which provide similar functionality to some of C++’s standard library. OpenStep is an Object-oriented Application programming interface (API specification for an Object-oriented operating system that uses any modern Operating OpenStep is an Object-oriented Application programming interface (API specification for an Object-oriented operating system that uses any modern Operating Cocoa is Apple Inc 's native Object-oriented application program environment for the Mac OS X Operating system GNUstep is a Free software implementation of NeXT 's OpenStep Objective-C libraries (called frameworks) Widget toolkit
One notable difference is that Objective-C provides runtime support for some reflective features, whereas C++ adds only a small amount of runtime support to C. In Computer science, reflection is the process by which a Computer program can observe and modify its own structure and behavior In Objective-C, an object can be queried about its own properties, for example whether it will respond to a certain message. In C++ this is not possible without the use of external libraries; however, it is possible to query whether two objects are of the same type (including built-in types) and whether an object is an instance of a given class (or superclass). In Computer science, a superclass is a class from which other classes are derived
The use of reflection is part of the wider distinction between dynamic (run-time) features versus static (compile-time) features of a language. Although Objective-C and C++ each employ a mix of both features, Objective-C is decidedly geared toward run-time decisions while C++ is geared toward compile-time decisions. The tension between dynamic and static programming involves many of the classic trade-offs in computer science.