In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... , object-oriented
Object-oriented programming
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... programming language
Programming language
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... which adds Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al... -style messaging
Message passing
Message passing in computer science, is a form of communication used in parallel computing, object-oriented programming, and interprocess communication.... to C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... .
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... , iPhone OS
IPhone OS
The iPhone OS or OS X iPhone is the operating system developed by Apple Inc. for the iPhone and iPod Touch. Like Mac OS X, from which it was derived, it uses the Darwin foundation.... , and GNUstep
GNUstep
GNUstep is a free software implementation of NeXT's OpenStep Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows.... , three environments based on the OpenStep
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... standard, and is the primary language used for the NeXTSTEP
NEXTSTEP
Nextstep was the original Object-oriented operating system, computer multitasking operating system that NeXT developed to run on its range of proprietary computers, such as the NeXTcube.... , OPENSTEP
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... , and Cocoa
Cocoa (API)
Cocoa is one of Apple Inc.'s native object-oriented application program environment for the Mac OS X operating system. It is one of four major Application programming interfaces available for Mac OS X; the others are Carbon , POSIX , and Java platform.... application frameworks. Generic Objective-C programs which do not make use of these libraries can also be compiled for any system supported by gcc
GNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain.... , which includes an Objective-C compiler.
Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches.... practice was based on structured programming
Structured programming
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 reducing reliance on the GOTO Statement .... .
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... , object-oriented
Object-oriented programming
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... programming language
Programming language
A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer.... which adds Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al... -style messaging
Message passing
Message passing in computer science, is a form of communication used in parallel computing, object-oriented programming, and interprocess communication.... to C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... .
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... , iPhone OS
IPhone OS
The iPhone OS or OS X iPhone is the operating system developed by Apple Inc. for the iPhone and iPod Touch. Like Mac OS X, from which it was derived, it uses the Darwin foundation.... , and GNUstep
GNUstep
GNUstep is a free software implementation of NeXT's OpenStep Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows.... , three environments based on the OpenStep
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... standard, and is the primary language used for the NeXTSTEP
NEXTSTEP
Nextstep was the original Object-oriented operating system, computer multitasking operating system that NeXT developed to run on its range of proprietary computers, such as the NeXTcube.... , OPENSTEP
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... , and Cocoa
Cocoa (API)
Cocoa is one of Apple Inc.'s native object-oriented application program environment for the Mac OS X operating system. It is one of four major Application programming interfaces available for Mac OS X; the others are Carbon , POSIX , and Java platform.... application frameworks. Generic Objective-C programs which do not make use of these libraries can also be compiled for any system supported by gcc
GNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain.... , which includes an Objective-C compiler.
Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches.... practice was based on structured programming
Structured programming
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 reducing reliance on the GOTO Statement .... . 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 a low level of code reuse.
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... as a potential solution to the problem. In fact, Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al... had already addressed many of these engineering issues; some of the most complex systems in the world were Smalltalk environments. On the downside, Smalltalk used a virtual machine
Virtual machine
In computer science, a virtual machine is a software implementation of a machine that executes programs like a real machine.Definitions... . 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.
Brad Cox is a computer scientist and Doctor of Philosophy of mathematical biology known mostly for his work in software engineering , software componentry, and the Objective-C programming language.... and Tom Love in the early 1980s at their company Stepstone
Stepstone
Stepstone was a software company founded in 1983 by Brad Cox and Tom Love, best known for releasing the original version of the Objective-C programming language.... . Both had been introduced to Smalltalk while at ITT
ITT Corporation
ITT Corporation is a global diversified manufacturing company with 2007 revenues of $9.0 billion. ITT participates in global markets including water and fluids management, defense and security, and motion and flow control.... ’s Programming Technology Center in 1981. Cox had become interested in the problems of true reusability in software design
Software engineering
Software engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches.... and programming. 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. 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 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.
NeXT, Inc. was an American computer company headquartered in Redwood City, California, California, that developed and manufactured a series of computer workstations intended for the higher education and business markets.... , the company started by Steve Jobs
Steve Jobs
Steven Paul Jobs is an United States businessman and co-founder, Chairman, and Chief executive officer of Apple Inc.. Jobs is the former CEO of Pixar Animation Studios.... after he left 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
NEXTSTEP
Nextstep was the original Object-oriented operating system, computer multitasking operating system that NeXT developed to run on its range of proprietary computers, such as the NeXTcube.... user interface and interface builder were based. 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
GNUstep
GNUstep is a free software implementation of NeXT's OpenStep Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows.... , based on the OpenStep
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... standard. Dennis Glatting wrote the first gnu-objc runtime
Runtime
In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination .... 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 used OpenStep in its new operating system, Mac OS X
Mac OS X
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... . This included Objective-C and NeXT's Objective-C based developer tool, Project Builder
Xcode
Xcode is a suite of tools for developing software on Mac OS X, developed by Apple Inc.. Xcode 3.0, the latest major version, is bundled free with Mac OS X v10.5, though it is not installed by default.... (later replaced by Xcode
Xcode
Xcode is a suite of tools for developing software on Mac OS X, developed by Apple Inc.. Xcode 3.0, the latest major version, is bundled free with Mac OS X v10.5, though it is not installed by default.... ), as well as its interface design tool, Interface Builder
Interface Builder
Interface Builder is a software development application for Apple Inc. Mac OS X operating system. It is part of Xcode , the Apple Developer Connection developer's toolset.... . Most of Apple's present-day Cocoa API
Cocoa (API)
Cocoa is one of Apple Inc.'s native object-oriented application program environment for the Mac OS X operating system. It is one of four major Application programming interfaces available for Mac OS X; the others are Carbon , POSIX , and Java platform.... is based on OpenStep interface objects, and is the most significant Objective-C environment being used for active development.
Syntax
Objective-C is a very thin layer on top of C. Objective-C is a strictsuperset
SuperSet
SuperSet Software was a group founded by friends and former Eyring Research Institute co-workers Drew Major, Dale Neibaur, Kyle Powell and later joined by Mark Hurst.... 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 messaging.
Messages
Objective-C syntax offers alternatives to a few "kludges
Kludge
A kludge is a workaround, an ad hoc engineering solution, a clumsy or inelegant solution to a problem, typically using parts that are cobbled together.... " in C syntax but more importantly supports object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... (OOP). The Objective-C model of object-oriented programming is based on sending messages
Message passing
Message passing in computer science, is a form of communication used in parallel computing, object-oriented programming, and interprocess communication.... to sovereign (even self-correcting) objects. This is unlike the Simula
Simula
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 and Kristen Nygaard.... -style programming model used by C++
C++
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... and this distinction is semantically important. The basic difference is that in Objective-C one does not call a method; one sends a message. In Objective-C the "receiver" of a message can opt to refuse it. Both styles carry their own strengths and weaknesses. Simula-style OOP allows multiple inheritance and faster execution by using compile-time binding whenever possible but 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 and is dynamically bound
Dynamic binding
In object oriented programming, dynamic binding refers to determining the exact implementation of a request based on both the request name and the receiving object at the run-time.... , but in some cases runs slower and some programmers (especially ones from Simula based languages) feel that it is a hassle to debug.
An object with method method is said to "respond" to the message method. 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];
This mechanism allows messages to be sent to an object defined first at runtime — something statically typed languages such as C++ are incapable of per the current standards for such languages. C++ will be able to support messaging per ANSI Standard if the Boost library
Boost library
The Boost C++ Libraries are a collection of peer-reviewed, open source Library that extend the functionality of C++. Most of the libraries are licensed under the Boost Software License, designed to allow Boost to be used with both open and closed source projects.... is standardized. Qt
Qt (toolkit)
Qt is a cross-platform application development framework, widely used for the development of graphical user interface programs , and also used for developing non-GUI programs such as console tools and servers.... provides this capability to C++ and other languages (but Objective-C is poorly supported) by adding the "connect" function as well as a large array of classes that afford and support this functionality. (See the dynamic typing section below for more advantages of dynamic (late) binding).
Objective-C has a few features in message-passing that relate to how it handles OOP. Objective-C messages do not need to execute because they are dynamically bound. If a message is implemented by an object, it will execute. If not, it will not execute, yet the code will still compile and run. So for example, every object is sent an "awakeFromNib" message, but those objects don't necessarily have to implement "awakeFromNib" to compile – if an object does implement "awakeFromNib", then that code will be executed when the message is sent, otherwise the message is ignored.
Messages can also be sent to the object that implements them or to the superclass
Superclass
Superclass may be:* The global ruling class created by globalization .* Superclass , a book about global governance by David Rothkopf.* Superclass , a taxonomic rank intermediate between subphylum and class.... that an object is derived from. These can be accessed using the "self" and "super" object pointers. Also, messages can be sent to nil
Nil
Nil is a word commonly used to mean nothing or 0 . It is one of several names for the number 0. See also null.Specific uses of Nil include:... objects.
Interfaces and implementations
Objective-C requires 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; the implementation (method) files, normally suffixed .m, can be very similar to C code files.
Interface
The interface of the 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 Class would thus be found in the file Class.h.
The interface declaration of the form:
@interface classname : superclassname
+classMethod1;
+(return_type)classMethod2;
+(return_type)classMethod3parameter_varName;
Plus signs denote class methods, minus signs denote instance methods. Class methods have no access to instance variables.
If you are translating from C++/C97 the above code is somewhat equivalent to:
struct classname : superclassname ;
Note that instanceMethod2 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 followed by the argument name. In some cases (e.g. when writing system APIs) it is useful to add descriptive text before each parameter.
The interface only declares the class interface and not the methods themselves; the actual code is written in the implementation. Implementation (method) files normally have the file extension .m.
In computer programming, named parameters or keyword arguments refer to a computer language's support for function calls that clearly state the name of each Parameter within the function call itself.... .
Internal representations of this 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, and generally messages are converted to function calls defined in the Objective-C runtime library – it's not necessarily known at link time which method will be called: the class of the receiver (the object being sent the message) need not be known until runtime.
Instantiation
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:
NeXT, Inc. was an American computer company headquartered in Redwood City, California, California, that developed and manufactured a series of computer workstations intended for the higher education and business markets.... to introduce the concept of multiple inheritance
Multiple inheritance
Multiple inheritance refers to a feature of some object-oriented programming programming languages in which a class can inheritance behaviors and features from more than one superclass .... 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 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
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... ), 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. 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.
denotes that there is the abstract idea of locking which is useful, and when stated in a class definition
@interface SomeClass : SomeSuperClass
@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.
Dynamic typing
Objective-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 — 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
Runtime
In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination .... error occurs.
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.
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
Container (data structure)
In computer science, a container is a Class , a data structure, or an abstract data type whose instances are collections of other objects. They are used to store objects in an organized way following specific access rules.... for a generic type of object, and then cast back and forth between the abstract generic type and the real type. Casting
Type conversion
In computer science, type conversion or typecasting refers to changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies.... however breaks the discipline of static typing
Type system
In computer science, a type system may be defined as "a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute.".... – if you put in an Integer
Integer
The integers are natural numbers including 0 and their negative and non-negative numberss . They are numbers that can be written without a fractional or decimal component, and fall within the set .... and read out a String
String (computer science)
In computer programming and some branches of mathematics, a string is an ordered sequence of symbols. These symbols are chosen from a predetermined set or alphabet.... , you get an error. One way of alleviating the problem is to resort to generic programming
Generic programming
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 when needed for specific types provided as parameters and was pioneered by Ada which appeared in 1983.... , but then container classes must be homogeneous in type. This need not be the case with dynamic typing.
Forwarding
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
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code .... , such as the Observer pattern
Observer pattern
The observer pattern is a design pattern in which an Object #Objects_in_object-oriented_programming , called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their Method .... or the Proxy pattern
Proxy pattern
In computer programming, the proxy pattern is a software design pattern.A proxy, in its most general form, is a class functioning as an interface to something else.... very simply.
The Objective-C runtime specifies a pair of methods in Object
forwarding methods:
- (retval_t) forward sel args; // with GCC
- (id) forward sel args; // with NeXT/Apple systems
action methods:
- (retval_t) performv sel args; // with GCC
- (id) performv sel 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.
Example
Here is an example of a program which demonstrates the basics of forwarding.
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 borrowed and extended the concept of Categories to help with this process from Smalltalk implementations (e.g., see ).
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
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
Spell checker
In computing, a spell checker is an application software that flags words in a document that may not be spelling correctly. Spell checkers may be stand-alone capable of operating on a block of text, or as part of a larger application, such as a word processor, email client, electronic dictionary, or search engine.... in its String implementation, you can add it 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.
The fragile base class problem is a fundamental architectural problem of object-oriented programming systems where base classes are considered "fragile" because seemingly safe modifications to a base class, when inherited by the subclass es, may cause the derived classes to malfunction.... problem for methods.
If you declare a method in a category with the same method signature
Method signature
In computer programming, especially object-oriented programming, a Method is commonly identified by its unique method signature. This usually includes the method name, the number and type of its parameters, and its return type.... 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
TOM (object-oriented programming language)
TOM was an object oriented programming language developed in the 1990s that built upon the lessons learned from Objective-C. The main purpose of TOM was to allow for "unplanned reuse" of code via a well-developed extension mechanism.... took the Objective-C system a step further and allowed for the addition of variables as well. Other languages have instead used prototype oriented
Prototype-based programming
Prototype-based programming is a style of object-oriented programming in which class es are not present, and behavior reuse is performed via a process of cloning existing object s that serve as prototypes.... solutions, the most notable being Self
Self programming language
Self is an Object-oriented programming computer programming programming language based on the concept of Prototype-based programming. It was used mainly as an experimental test system for language design in the 1980s and 1990s.... .
Example usage of categories
This example builds up an Integer class, by defining first a basic class with only accessor method
Method (computer science)
In object-oriented programming, a method is a subroutine that is exclusively associated either with a class or with an object . Like a procedure in procedural programming languages, a method usually consists of a sequence of statement to perform an action, a set of input parameter to customize those actions, and possibly an output value... s implemented, and adding two categories, Arithmetic and Display, which extend the basic class. 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, also known as monkey patching).
Objective-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
Mac OS X v10.5
Mac OS X version 10.5 "Leopard" is the sixth Software version of Mac OS X, Apple Inc. desktop and server operating system for Apple Macintosh computers, and the successor to Mac OS X v10.4 "Tiger".... 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:
A class may only pose as one of its direct or indirect superclasses
The posing class must not define any new instance variables which are absent from the target class (though it may define or override methods).
The target class may not have received any messages prior to the posing.
Posing, similarly to categories, allows globally augmenting existing classes. Posing permits two features absent from categories:
A posing class can call overridden methods through super, thus incorporating the implementation of the target class.
A posing class can override methods defined in categories.
This intercepts every invocation of setMainMenu to NSApplication.
#import
In 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.
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain.... , 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. It is argued that this burden should be placed on the implementor; to this end, the implementor may place the directive #pragma once
Pragma once
In the C and C++ programming languages, #pragma once is a non-standard but widely supported C preprocessor designed to cause the current source file to be included only once in a single compilation.... in the header file, or use the traditional #include guard
Include guard
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 double inclusion when dealing with the #include compiler directive.... technique:
ifndef HEADER_H
define HEADER_H
... 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.
Other features
Objective-C's features often allow for flexible, and often easy, solutions to programming issues.
Remote procedure call is an Inter-process communication technology that allows a computer program to cause a subroutine or procedure to execute in another address space without the programmer explicitly coding the details for this remote interaction.... can be easily implemented using categories and message forwarding.
In computer science, pointer swizzling is the conversion of references based on name or position to direct pointer references. It is typically performed during the deserialization of a relocatable object from disk, such as an executable file or pointer-based data structure.... of the isa pointer allows for classes to change at runtime. Typically used for debugging
Debugging
Debugging is a methodical process of finding and reducing the number of computer bugs, or defects, in a computer program or a piece of electronic hardware thus making it behave as expected.... where freed objects are swizzled into zombie objects, whose only purpose is to report an error when someone calls them. Swizzling was also used in EOF
Enterprise Objects Framework
The Enterprise Objects Framework was introduced by NeXT in 1994 as a pioneering object-relational mapping product for its NeXTSTEP and OpenStep development platforms.... to create database faults. Swizzling is used today by Apple’s Foundation Framework to implement Key-Value Observing.
In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be stored on a storage medium or transmitted across a computer network connection link.... , commonly called archival in Objective-C, can be done by overriding write and read methods.
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain.... which can compile source files which use a combination of C++ and Objective-C syntax. 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:
A C++ class cannot derive from an Objective-C class and vice versa.
C++ namespaces cannot be declared inside an Objective-C declaration.
Objective-C classes cannot have instance variables of C++ classes which do not have a default constructor or which have one or more virtual methods, but pointers to C++ objects can be used as instance variables without restriction (allocate them with new in the -init method).
C++ "by value" semantics cannot be applied to Objective-C objects, which are only accessible through pointers.
An Objective-C declaration cannot be within a C++ template declaration and vice versa. Objective-C types, (e.g., Classname *) can be used as C++ template parameters, however.
Objective-C and C++ exception handling is distinct; the handlers of each cannot handle exceptions of the other type.
Care must be taken since the destructor calling conventions of Objective-C and C++’s exception run-time models do not match (i.e., a C++ destructor will not be called when an Objective-C exception exits the C++ object’s scope).
The Apple Worldwide Developers Conference, commonly abbreviated WWDC, is a business conference held annually in California by Apple Inc. The conference is primarily used by Apple to showcase its new software and technologies for software developer, as well as offering hands-on labs and feedback sessions.... , Apple announced the forthcoming release of "Objective-C 2.0," a revision of the Objective-C language to include "modern garbage collection, syntax enhancements, runtime performance improvements, and 64-bit support". Mac OS X v10.5
Mac OS X v10.5
Mac OS X version 10.5 "Leopard" is the sixth Software version of Mac OS X, Apple Inc. desktop and server operating system for Apple Macintosh computers, and the successor to Mac OS X v10.4 "Tiger".... , released in October 2007, included an Objective-C 2.0 compiler. It is not yet known when these language improvements will be available in the GNU runtime.
Garbage collection
Objective-C 2.0 provides an optional conservative yet generational garbage collector. When run in backwards-compatible mode, the runtime turns reference counting
Reference counting
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.... operations such as "retain" and "release" into no-ops. 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.
Properties
Objective-C 2.0 introduces a new syntax to declare instance variables as properties
Property (programming)
In some object-oriented programming programming languages, a property is a special sort of Class member, intermediate between a field and a method .... , with optional attributes to configure the generation of accessor methods. A property may be declared as "readonly", and may be provided with storage semantics such as "assign", "copy" or "retain". By default, properties are considered atomic, which results in a lock preventing multiple threads from accessing them at the same time. A property can be declared as "nonatomic" which removes this lock.
@interface Person : NSObject
@property(copy) NSString *name;
@property(readonly) int age;
-(id)initWithAgeage;
@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)initWithAgeinitAge
-(int)age
@end
Properties can be accessed using the traditional message passing syntax, 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, equivalent to [aPerson setName: @"Steve"];
NSLog(@"Access by message (%@), dot notation(%@), property name(%@) and direct instance variable access (%@)",
[aPerson name], 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) introduceMyselfWithPropertiesuseGetter
A class or protocol's properties may be dynamically introspected
Type introspection
In computing, type introspection is a capability of some object-oriented programming 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
Fast enumeration
Instead of using an Enumerator object to iterate through a collection, Objective-C 2.0 offers the fast enumeration syntax. The following two loops are equivalent in Objective-C 2.0.
for (int i=0; i<[thePeople count]; i++)
for (Person *p in thePeople)
NSLog(@"%@ is %i years old.", [p getName], [p getAge]);
Fast enumeration generates more efficient code than standard enumeration because methods calls to enumerate over objects are replaced by pointer arithmetic using the NSFastEnumeration protocol.
Implications for Cocoa development
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.
Today
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 distribution
Linux distribution
A Linux distribution is a member of the family of Unix-like software distributions built on top of the Linux kernel. Such distributions consist of a large collection of software applications such as word processors, spreadsheets, media players and database applications.... s and Cocoa comes with Mac OS X. 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.
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain.... /NeXT
NeXT
NeXT, Inc. was an American computer company headquartered in Redwood City, California, California, that developed and manufactured a series of computer workstations intended for the higher education and business markets.... /Apple implementation, which added several extensions to the original Stepstone
Stepstone
Stepstone was a software company founded in 1983 by Brad Cox and Tom Love, best known for releasing the original version of the Objective-C programming language.... implementation, there exists another free open-source
Free and open source software
Free and open source software, also F/OSS, FOSS, or FLOSS is software which is liberally software licence to grant the right of users to study, change, and improve its design through the availability of its source code.... Objective-C implementation, which implements a slightly different set of extensions: The Portable Object Compiler implements, among other things, also Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al... -like blocks for Objective-C.
In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination .... written in C which adds little to the size of the application. In contrast, most OO systems at the time that it was created used large virtual machine
Virtual machine
In computer science, a virtual machine is a software implementation of a machine that executes programs like a real machine.Definitions... runtimes. 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
Software distribution
A software distribution, also referred to as a software distro, is a bundle of a specific software , already compiled and configured. It is generally the closest thing to a turnkey form of a usually GNU General Public License, free software source code for a software.... ), in contrast to Smalltalk systems where a large amount of memory was used just to open a window. 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
GNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain.... , first as a preprocessor, then as a module) rather than as a new compiler. This allows Objective-C to leverage the huge existing collection of C code, libraries, tools, and mindshare. Existing C libraries can be wrapped in Objective-C wrappers
Adapter pattern
In computer programming, the adapter design pattern translates one Interface for a Class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface.... to provide an OO-style interface.
In economics and especially in the theory of competition, barriers to entry are obstacles in the path of a company that make it difficult to enter a given market.... , likely the biggest problem for the widespread acceptance of Smalltalk in the 1980s.
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage , or memory used by Object that will never be accessed or mutated again by the Application software.... . 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. Some 3rd party implementations have added this feature (most notably GNUstep) and Apple have implemented it as of Mac OS X v10.5
Mac OS X v10.5
Mac OS X version 10.5 "Leopard" is the sixth Software version of Mac OS X, Apple Inc. desktop and server operating system for Apple Macintosh computers, and the successor to Mac OS X v10.4 "Tiger".... .
Another common criticism is that Objective-C does not have language support for namespace
Namespace (computer science)
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated with that namespace.... s. Instead, programmers are forced to add prefixes to their class names, which are traditionally shorter than namespace names and thus more prone to collisions. As of 2007, all Mac OS X classes and functions in the Cocoa programming environment are prefixed with "NS" (e.g. NSObject, NSButton) to 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
NEXTSTEP
Nextstep was the original Object-oriented operating system, computer multitasking operating system that NeXT developed to run on its range of proprietary computers, such as the NeXTcube.... .
Since Objective-C is a strict superset of C, it does not treat C primitive types as first-class object
First-class object
In computing, a first-class object , in the context of a particular programming language, is an entity which can be used in programs without restriction .... s either.
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... , Objective-C does not support operator overloading
Operator overloading
In computer programming, operator overloading is a specific case of polymorphism in which some or all of operator s like +, =, or have different implementations depending on the types of their arguments.... . Also unlike C++, Objective-C allows an object to directly inherit only from one class (forbidding multiple inheritance
Multiple inheritance
Multiple inheritance refers to a feature of some object-oriented programming programming languages in which a class can inheritance behaviors and features from more than one superclass .... ). 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.
Philosophical differences between Objective-C and C++
C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features.... and Objective-C represent different approaches to extending C.
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... , generic programming
Generic programming
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 when needed for specific types provided as parameters and was pioneered by Ada which appeared in 1983.... , and metaprogramming
Metaprogramming
Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at runtime that would otherwise be done at compile time.... . C++ also comes with a large standard library which includes several container classes
Container (data structure)
In computer science, a container is a Class , a data structure, or an abstract data type whose instances are collections of other objects. They are used to store objects in an organized way following specific access rules.... . 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
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... -like library such as OPENSTEP
OpenStep
OpenStep is an object-oriented application programming interface specification for an object-oriented operating system that uses any modern operating system as its core, principally developed by NeXT with Sun Microsystems.... , Cocoa
Cocoa (API)
Cocoa is one of Apple Inc.'s native object-oriented application program environment for the Mac OS X operating system. It is one of four major Application programming interfaces available for Mac OS X; the others are Carbon , POSIX , and Java platform.... , or GNUstep
GNUstep
GNUstep is a free software implementation of NeXT's OpenStep Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows.... which provide similar functionality to some of C++’s standard library.
One notable difference is that Objective-C provides runtime support for some reflective
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... features, whereas C++ adds only a small amount of runtime support to C. 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.
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 programming.
Programming languages are used for controlling the behavior of a machine . Like natural languages, programming languages conform to rules for syntax and semantics....