Objective-C
Encyclopedia
Objective-C is a reflective
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....

, object-oriented
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

 that adds Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...

-style messaging
Message passing
Message passing in computer science is a form of communication used in parallel computing, object-oriented programming, and interprocess communication. In this model, processes or objects can send and receive messages to other processes...

 to the C programming language
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

.

Today, it is used primarily on Apple's Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

 and iOS: two environments derived from the OpenStep
OpenStep
OpenStep was an object-oriented application programming interface specification for an object-oriented operating system that used a non-NeXTSTEP operating system as its core, principally developed by NeXT with Sun Microsystems. OPENSTEP was a specific implementation of the OpenStep API developed...

 standard, though not compliant with it. Objective-C is the primary language used for Apple's Cocoa
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...

 API, and it was originally the main language on NeXT
NeXT
Next, Inc. was an American computer company headquartered in Redwood City, California, that developed and manufactured a series of computer workstations intended for the higher education and business markets...

's NeXTSTEP
NEXTSTEP
NeXTSTEP was the object-oriented, multitasking operating system developed by NeXT Computer to run on its range of proprietary workstation computers, such as the NeXTcube...

 OS. Generic Objective-C programs that do not use 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...

 or Clang
Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages. It uses the Low Level Virtual Machine as its back end, and Clang has been part of LLVM releases since LLVM 2.6....

.

History

Objective-C was created primarily by Brad Cox
Brad Cox
Brad Cox is a computer scientist and Ph.D. 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, originally named Productivity Products International , 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
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...

 while at ITT Corporation
ITT Corporation
ITT Corporation is a global diversified manufacturing company based in the United States. ITT participates in global markets including water and fluids management, defense and security, and motion and flow control...

's Programming Technology Center in 1981. The earliest work on Objective C traces back to around that time.
Cox was intrigued by 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; that is, the application of engineering to software...

 and programming. He realized that a language like Smalltalk would be invaluable in building development environments for system developers at ITT. However, he and Tom Love also recognized that backward compatibility with C was critically important in ITT's telecom engineering milieu.
Cox began writing a pre-processor for C 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 Pre-Compiler.
Love was hired by Schlumberger Research in 1982 and had the opportunity to acquire the first commercial copy of Smalltalk-80, which further influenced the 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)
Stepstone
Stepstone, originally named Productivity Products International , 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....

, to commercialize their product, which coupled an Objective-C compiler with class libraries. In 1986, Cox published the main description of Objective-C in its original form in the book Object-Oriented Programming, An Evolutionary Approach. Although he was careful to point out that there is more to the problem of reusability than just the language, Objective-C often found itself compared feature for feature with other languages.

Popularization through NeXT

After Steve Jobs
Steve Jobs
Steven Paul Jobs was an American businessman and inventor widely recognized as a charismatic pioneer of the personal computer revolution. He was co-founder, chairman, and chief executive officer of Apple Inc...

 left Apple Inc., he started the company NeXT
NeXT
Next, Inc. was an American computer company headquartered in Redwood City, California, that developed and manufactured a series of computer workstations intended for the higher education and business markets...

. In 1988, NeXT licensed Objective-C from StepStone (the new name of PPI, the owner of the Objective-C trademark) and extended the GCC compiler to support Objective-C, and developed the AppKit
Application Kit
The Application Kit is a collection of classes within the OpenStep specification and provided by such operating systems as OPENSTEP, GNUstep, and Mac OS X under Cocoa, providing classes oriented around graphical user interface capabilities...

 and Foundation Kit
Foundation Kit
The Foundation Kit, or just Foundation for short, is an Objective-C framework in the OpenStep specification. It provides basic classes such as wrapper classes and data structure classes. This framework uses the prefix NS .-NSObject:...

 libraries on which the NeXTstep
NEXTSTEP
NeXTSTEP was the object-oriented, multitasking operating system developed by NeXT Computer to run on its range of proprietary workstation computers, such as the NeXTcube...

 user interface and interface builder were based. While the NeXT workstations failed to make a great impact in the marketplace, the tools were widely lauded in the industry. This led NeXT to drop hardware production and focus on software tools, selling NeXTstep (and OpenStep) as a platform for custom programming.

The GNU
GNU
GNU is a Unix-like computer operating system developed by the GNU project, ultimately aiming to be a "complete Unix-compatible software system"...

 project started work on its free clone of NeXTStep, named GNUstep
GNUstep
GNUstep is a free software implementation of Cocoa Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows. It is part of the GNU Project.GNUstep features a cross-platform, object-oriented development...

, based on the OpenStep
OpenStep
OpenStep was an object-oriented application programming interface specification for an object-oriented operating system that used a non-NeXTSTEP operating system as its core, principally developed by NeXT with Sun Microsystems. OPENSTEP was a specific implementation of the OpenStep API developed...

 standard. Dennis Glatting wrote the first GNU Objective-C runtime in 1992. The GNU Objective-C runtime, which has been in use since 1993, is the one developed by Kresten Krab Thorup when he was a university student in Denmark
Denmark
Denmark is a Scandinavian country in Northern Europe. The countries of Denmark and Greenland, as well as the Faroe Islands, constitute the Kingdom of Denmark . It is the southernmost of the Nordic countries, southwest of Sweden and south of Norway, and bordered to the south by Germany. Denmark...

. Thorup also worked at NeXT from 1993 to 1996.

After acquiring NeXT in 1996, Apple Computer
Apple Computer
Apple Inc. is an American multinational corporation that designs and markets consumer electronics, computer software, and personal computers. The company's best-known hardware products include the Macintosh line of computers, the iPod, the iPhone and the iPad...

 used OpenStep in its new operating system, Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. 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
Project Builder
Project Builder was an integrated development environment originally developed by NeXT for the NeXTSTEP operating system. It was rewritten and informally dubbed PBX while distributed by Apple Computer for software development on Mac OS X computer systems prior to Mac OS X v10.3...

 (which had been expanded and is now called Xcode
Xcode
Xcode is a suite of tools, developed by Apple, for developing software for Mac OS X and iOS. Xcode 4.2, the latest major version, is available on the Mac App Store for free for Mac OS X 10.7 , and on the Apple Developer Connection website for free to registered developers Xcode is a suite of tools,...

), as well as its interface design tool, Interface Builder
Interface Builder
Interface Builder is a software development application for Apple's Mac OS X operating system. It is part of Xcode , the Apple Developer Connection developer's toolset. Interface Builder allows Cocoa and Carbon developers to create interfaces for applications using a graphical user...

. Most of Apple's present-day Cocoa API
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...

 is based on OpenStep interface objects, and is the most significant Objective-C environment being used for active development.

Syntax

Objective-C is a thin layer on top of C, and moreover is a strict superset
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; it is possible to compile any C program with an Objective-C compiler, and to freely include C code within an Objective-C class.

Objective-C derives its object syntax from Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...

. All of the syntax for non-object-oriented operations (including primitive variables, preprocessing, expressions, function declarations, and function calls) are identical to that of C, while the syntax for object-oriented features is an implementation of Smalltalk-style messaging.

Messages

The Objective-C model of object-oriented programming is based on message passing
Message passing
Message passing in computer science is a form of communication used in parallel computing, object-oriented programming, and interprocess communication. In this model, processes or objects can send and receive messages to other processes...

 to object instances. In Objective-C one does not call a method; one sends a message. 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 statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

. The difference between these two concepts is in how the code referenced by the method or message name is executed. In a Simula-style language, the method name is in most cases bound
Name binding
In programming languages, name binding is the association of objects with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-object bindings as a service and notation for the programmer is implemented...

 to a section of code in the target class by the compiler. In Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...

 and Objective-C, the target of a message is resolved at runtime, with the receiving object itself interpreting the message. A method is identified by a selector or SEL — a NUL-terminated string representing its name — and resolved to a C method pointer implementing it: an IMP. A consequence of this is that the message-passing system has no type checking. The object to which the message is directed — the receiver — is not guaranteed to respond to a message, and if it does not, it simply raises an exception.

Sending the message method to the object pointed to by the pointer obj would require the following code in C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

:

obj->method(argument);

In Objective-C, this is written as follows:

[obj method: argument];

Both styles of programming have their strengths and weaknesses. Object-oriented programming in the Simula style allows multiple inheritances and faster execution by using compile-time binding whenever possible, but it does not support dynamic binding
Dynamic dispatch
In computer science, dynamic dispatch is the process of mapping a message to a specific sequence of code at runtime. This is done to support the cases where the appropriate method can't be determined at compile-time...

 by default. It also forces all methods to have a corresponding implementation unless they are virtual, meaning the method is a placeholder for methods with the same name to be defined in objects derived from the base object. An implementation is still required for the method to be called in the derived object. Smalltalk-style programming allows messages to go unimplemented, with the method resolved to its implementation at runtime. For example, a message may be sent to a collection of objects, to which only some will be expected to respond, without fear of producing runtime errors. Message passing also does not require that an object be defined at compile time. (See the dynamic typing section below for more advantages of dynamic (late) binding.)

Due to the overhead of interpreting the messages, an initial Objective-C message takes three times as long as a C++ virtual method call. Subsequent calls are IMP cached and are faster than the C++ virtual method call in some implementations.

Interfaces and implementations

Objective-C requires that the interface and implementation of a class be in separately declared code blocks. By convention, developers place the interface in a header file
Header file
Some programming languages use header files. These files allow programmers to separate certain elements of a program's source code into reusable files. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers...

 and the implementation in a code file. The header files, normally suffixed .h, are similar to C header files while the implementation (method) files, normally suffixed .m, can be very similar to C code files.

Interface

The interface of a class is usually defined in a header file. A common convention is to name the header file after the name of the class, e.g. Ball.h would contain the interface for the class Ball.

An interface declaration takes the form:

@interface classname : superclassname {
// instance variables
}
+ classMethod1;
+ (return_type)classMethod2;
+ (return_type)classMethod3:(param1_type)param1_varName;

- (return_type)instanceMethod1:(param1_type)param1_varName :(param2_type)param2_varName;
- (return_type)instanceMethod2WithParameter:(param1_type)param1_varName andOtherParameter:(param2_type)param2_varName;
@end


In the above, plus signs denote class methods, or methods that can be called on the class itself (not on an instance), and minus signs denote instance methods, which can only be called on a particular instance of the class. Class methods also have no access to instance variables.

The code above is roughly equivalent to the following C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 interface:



class classname : public superclassname {
protected:
// instance variables

public:
// Class (static) functions
static void * classMethod1;
static return_type classMethod2;
static return_type classMethod3(param1_type param1_varName);

// Instance (member) functions
return_type instanceMethod1(param1_type param1_varName, param2_type param2_varName);
return_type instanceMethod2WithParameter(param1_type param1_varName, param2_type param2_varName=default);
};


Note that instanceMethod2WithParameter:andOtherParameter: demonstrates the interleaving of selector segments with argument expressions, for which there is no direct equivalent in C/C++.

Return types can be any standard C type, a pointer to a generic Objective-C object, or a pointer to a specific type of object such as NSArray *, NSImage *, or NSString *. The default return type is the generic Objective-C type id.

Method arguments begin with a colon followed by the expected argument type in parentheses and the argument name. In some cases (e.g. when writing system APIs) it is useful to add descriptive text before each parameter.


- (void)setRangeStart:(int)start end:(int)end;
- (void)importDocumentWithName:(NSString *)name withSpecifiedPreferences:(Preferences *)prefs beforePage:(int)insertPage;


Implementation

The interface only declares the class interface and not the methods themselves: the actual code is written in the implementation file. Implementation (method) files normally have the file extension .m, which originally signified "messages".


@implementation classname
+ (return_type)classMethod {
// implementation
}
- (return_type)instanceMethod {
// implementation
}
@end


Methods are written using their interface declarations.
Comparing Objective-C and C:


- (int)method:(int)i {
return [self square_root:i];
}



int function (int i) {
return square_root(i);
}


The syntax allows pseudo-naming of arguments
Named parameter
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.- Overview :...

.

- (int)changeColorToRed:(float)red green:(float)green blue:(float)blue;

[myColor changeColorToRed:5.0 green:2.0 blue:6.0];


Internal representations of a method vary between different implementations of Objective-C. If myColor is of the class Color, instance method -changeColorToRed:green:blue: might be internally labeled _i_Color_changeColorToRed_green_blue. The i is to refer to an instance method, with the class and then method names appended and colons changed to underscores. As the order of parameters is part of the method name, it cannot be changed to suit coding style or expression as with true named parameters.

However, internal names of the function are rarely used directly. Generally, messages are converted to function calls defined in the Objective-C runtime library. It is not necessarily known at link time which method will be called because the class of the receiver (the object being sent the message) need not be known until runtime.

Instantiation

Once an Objective-C class is written, it can be instantiated. This is done by first allocating an uninitialized instance of the class (an object) and then by initializing it. An object is not fully functional until both steps have been completed. These steps should be accomplished with a single line of code so that there is never an allocated object that hasn't undergone initialization (and because it is not advisable to keep the intermediate result since -init can return a different object than that which it is called on).

Instantiation with the default, no-parameter initializer:

MyObject *o = Dynamic typing]] section).

The initializer pattern is used in order to assure that the object is properly initialized by its superclass before the init method performs its initialization. It performs the following actions:
  1. self = [super init]
    Sends the superclass instance an init message and assigns the result to self (pointer to the current object).
  2. if (self)
    Checks if the returned object pointer is valid before performing any initialization.
  3. return self
    Returns the value of self to the caller.


A non-valid object pointer has the value nil; conditional statements like "if" treat nil like a null pointer, so the initialization code will not be executed if [super init] returned nil. If there is an error in initialization the init method should perform any necessary cleanup, including sending a "release" message to self, and return nil to indicate that initialization failed, any checking for such errors must only be performed after having called the superclass initialization to ensure that destroying the object will be done correctly.

If a class has more than one initialization method, only one of them (the "dedicated initializer") needs to follow this pattern; others can call the dedicated initializer instead of the superclass initializer.

Protocols

Objective-C was extended at [[NeXT]] to introduce the concept of [[multiple inheritance]] of specification, but not implementation, through the introduction of [[protocol (object-oriented programming);
}
@end


Display.h
  1. import "Integer.h"


@interface Integer (Display)
- (id) showstars;
- (id) showint;
@end


Display.m
  1. 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


main.m
  1. import "Integer.h"
  2. import "Arithmetic.h"
  3. import "Display.h"


int main(void) {
Integer *num1 = [Integer new], *num2 = [Integer new];
int x;

printf("Enter an integer: ");
scanf("%d", &x);

[num1 integer:x];
[num1 showstars];

printf("Enter an integer: ");
scanf("%d", &x);

[num2 integer:x];
[num2 showstars];

[num1 add:num2];
[num1 showint];

return 0;
}

Posing

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 Leopard is the sixth major release of Mac OS X, Apple's desktop and server operating system for Macintosh computers. Leopard was released on 26 October 2007 as the successor of Tiger , and is available in two variants: a desktop version suitable for personal computers, and a...

, and is 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 that 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 with categories, allows global augmentation of 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.


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.

Preprocessor Directives

Objective-C includes powerful preprocessor directives which allows the language to be fundamentally changed.

#import

In the C language, the #include pre-compile directive always causes a file's contents to be inserted into the source at that point. Objective-C has the equivalent #import directive except each file is included only once per compilation unit, obviating the need for 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 directive...

s.

#define

The #define statement is possibly the most powerful preprocessor statement in ObjC. It has multiple uses, including the ability to define constants as either numbers or string constants, the creation of macros, as well as the ability to modify the language itself.

Constants
The #define statement allows for the creation of either string or number constants.

#define kStringConstant "My String"
Once defined, the constant can be used as a normal string or a normal number within the language.

Examples

  1. define myConstant @"my constant"


NSLog(@"i like %@", myConstant);
//this would output
//i like my constant


  1. define myNumberConstant 20
  2. define myDecimal 20.12


float myFloat = myNumberConstant + myDecimal;
NSLog(@"my float = %f", myFloat);
//this with output
//my float = 40.12


Macros
Macros can be used within ObjC to create small functions that perform simple (typically mathematical) tasks.

Example

  1. define Add(x,y) ( x + y )


int a = 1;
int b = 2;
int c = Add(a,b);
NSLog(@"Add result: %i", c);
// this will output
// Add result: 3


Modifying the language
The #define statement can be used to replace normal syntax in ObjC.

Examples

  1. define plus +
  2. define star *
  3. define open {
  4. define close }


int a = 1 plus 2;
int b = 1 + 2;

// the above two statements will yield the same results

NSString star string = [NSString stringWithString:@"myString"];
NSString * stringTwo = [NSString stringWithString:@"myOtherString"];

//these will both work, this showcases the fact that the #define statement can replace almost anything

-(void) method open
//again this shows the versatility of the #define directive
close



Undef
The #undef command will undefine a previously defined constant or command

#ifdef

The #ifdef directive allows optional compiling of the section of code within the #ifdef and #endif statements.

Examples

  1. define DEBUG

  1. ifdef DEBUG

//this statement does not check for a specific value being set for the DEBUG constant, rather it checks if it is defined.

//if a variable is previously defined, the #undef statement can be called to remove it, and cause any #ifdef
// statements checking for it to return no

-(void)myFunction{
//this code will be compiled if DEBUG is defined
}
  1. else

-(void)myOtherFunction{
//this code will be compiled if DEBUG is not defined
}
  1. endif



#ifndef
The #ifndef statement is used to compile certain code when a constant is not defined.

Defining constants in compile commands
Code constants can also be sent via a command line compile command.

gcc -framework Foundation -D DEBUG myapp.m -o myapp

This command defines the DEBUG constant which will cause any #ifdef statements to return yes.

Other features

Objective-C's features often allow for flexible, and often easy, solutions to programming issues.
  • Delegating methods to other objects and remote invocation
    Remote procedure call
    In computer science, a remote procedure call is an inter-process communication 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.
  • Swizzling
    Pointer swizzling
    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 bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected. Debugging tends to be harder when various subsystems are tightly coupled, as changes in one may cause bugs to emerge...

     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 Enterprise Objects Framework
    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. The EOF abstracts the process of interacting with a relational database, mapping database rows to Java or Objective-C objects. This...

     to create database faults. Swizzling is used today by Apple’s Foundation Framework to implement Key-Value Observing.
  • Serialization
    Serialization
    In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object state into a format that can be stored and "resurrected" later in the same or another computer environment...

    , commonly called Archiving in Objective-C, can be done by overwriting read and write methods.

Objective-C++

Objective-C++ is a front-end to the GNU Compiler Collection
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 can compile source files that 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 declarations may appear only in global scope, not inside a C++ namespace
  • Objective-C classes cannot have instance variables of C++ classes that do not have a default constructor or that 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. However, Objective-C types, (e.g., Classname *) can be used as C++ template parameters.
  • 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 new 64-bit runtime resolves this by introducing interoperability with C++ exceptions in this sense.

Objective-C 2.0

At the 2006 Worldwide Developers Conference
Worldwide Developers Conference
The Apple Worldwide Developers Conference, commonly abbreviated WWDC, is a conference held annually in California by Apple Inc. The conference is primarily used by Apple to showcase its new software and technologies for developers, as well as offering hands-on labs and feedback sessions...

, Apple announced the 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 Leopard is the sixth major release of Mac OS X, Apple's desktop and server operating system for Macintosh computers. Leopard was released on 26 October 2007 as the successor of Tiger , and is available in two variants: a desktop version suitable for personal computers, and a...

, released in October 2007, included an Objective-C 2.0 compiler. GCC 4.6
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...

 supports many new Objective-C features, such as declared and synthesized properties, dot syntax, fast enumeration, optional protocol methods, method/protocol/class attributes, class extensions and a new GNUnn Objective-C runtime API.

Garbage collection

Objective-C 2.0 provides an optional conservative, yet generational garbage collector
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...

. 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, block of memory, disk space or other resource...

 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. The garbage collector does not exist on the iOS implementation of Objective-C 2.0. Garbage Collection in Objective-C runs on a low-priority background thread, and can halt on user events, with the intention of keeping the user experience responsive.

Properties

Objective-C 2.0 introduces a new syntax to declare instance variables as properties
Property (programming)
A property, in some object-oriented programming languages, is a special sort of class member, intermediate between a field and a method. Properties are read and written like fields, but property reads and writes are translated to get and set method calls...

, with optional attributes to configure the generation of accessor methods. Properties are, in a sense, public instance variables; that is, declaring an instance variable as a property provides external classes with access (possibly limited, e.g. read only) to that property. 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 {
@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, if not read-only) methods according to the property declaration. Alternatively, the getter and setter methods must be implemented explicitly, or the @dynamic keyword can be used to indicate that accessor methods will be provided by other means.


@implementation Person
@synthesize name;

-(id)initWithAge:(int)initAge {
age = initAge; // NOTE: direct instance variable assignment, not property setter
return self;
}

-(int)age {
return 29;
}
@end


Properties can be accessed using the traditional message passing syntax, dot notation, or, in Key-Value Coding, by name via the "valueForKey:"/"setValue:forKey:" methods.


Person *aPerson = erson 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) 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
Type introspection
In computing, type introspection is a capability of some object-oriented programming languages to determine the type of an object at runtime. This is a notable capability of the Objective-C language, and is a common feature in any language that allows object classes to be manipulated as first-class...

.


int i;
int 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);
}

Non-fragile instance variables

Objective-C 2.0 provides non-fragile instance variables where supported by the runtime (i.e. when building 64-bit Mac OS X code as well as all iOS code). Under the modern runtime, an extra layer of indirection is added to instance variable access, allowing the dynamic linker to adjust instance layout at runtime. This feature allows for two important improvements to Objective-C code:
  • This eliminates the fragile binary interface problem
    Fragile binary interface problem
    The fragile binary interface problem or FBI is a shortcoming of certain object-oriented programming language compilers, in which internal changes to an underlying class library can cause descendant libraries or programs to cease working...

     - Superclasses can change sizes without affecting binary compatibility.
  • This allows instance variables that provide the backing for properties to be synthesized at runtime without them being declared in the class’ interface.

Fast enumeration

Instead of using an NSEnumerator object or indices to iterate through a collection, Objective-C 2.0 offers the fast enumeration syntax. In Objective-C 2.0, the following loops are functionally equivalent, but have different performance characteristics.


// Using NSEnumerator
NSEnumerator *enumerator = [thePeople objectEnumerator];
Person *p;

while ((p = [enumerator nextObject]) != nil) {
NSLog(@"%@ is %i years old.", [p name], [p age]);
}



// Using indexes
for (int i = 0; i < [thePeople count]; i++) {
Person *p = [thePeople objectAtIndex:i];
NSLog(@"%@ is %i years old.", [p name], [p age]);
}



// Using fast enumeration
for (Person *p in thePeople) {
NSLog(@"%@ is %i years old.", [p name], [p age]);
}


Fast enumeration generates more efficient code than standard enumeration because method 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). Since fast enumeration does not generate exactly the same binaries as standard enumeration, its use will cause an application to crash on OS X version 10.4 or earlier.

Portable Object Compiler

Besides the 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...

/NeXT
NeXT
Next, Inc. was an American computer company headquartered in Redwood City, 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, originally named Productivity Products International , 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, another free, open-source
Free and open source software
Free and open-source software or free/libre/open-source software is software that is liberally licensed to grant users the right to use, study, change, and improve its design through the availability of its source code...

 Objective-C implementation called the Portable Object Compiler also exists. The set of extensions implemented by the Portable Object Compiler differs from the GCC/NeXT/Apple implementation; in particular, it includes Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...

-like blocks for Objective-C, while it lacks protocols and categories, two features used extensively in OpenStep and its derivatives and relatives. Overall, POC represents an older, pre-NeXT stage in the language's evolution, roughly conformant to Brad Cox's 1991 book.

It also includes a runtime library called ObjectPak, which is based on Cox's original ICPak101 library (which in turn derives from the Smalltalk-80 class library), and is quite radically different from the OpenStep FoundationKit.

GEOS Objective-C

The PC GEOS
GEOS (16-bit operating system)
GEOS is a computer operating environment, graphical user interface, and suite of application software. Originally released as PC/GEOS, it runs on DOS-based, IBM PC compatible computers. The package later became GeoWorks Ensemble, then NewDeal Office, and is now Breadbox Ensemble...

 system used a programming language known as GEOS Objective-C or goc; despite the name similarity, the two languages are similar only in overall concept and the use of keywords prefixed with an @ sign.

Clang

The Clang
Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages. It uses the Low Level Virtual Machine as its back end, and Clang has been part of LLVM releases since LLVM 2.6....

 compiler suite, part of the LLVM project, implements Objective-C as well as other languages.

Library use

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
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...

 or GNUstep
GNUstep
GNUstep is a free software implementation of Cocoa Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows. It is part of the GNU Project.GNUstep features a cross-platform, object-oriented development...

. These libraries often come with the operating system: the GNUstep libraries often come with GNU/Linux based distributions 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 that 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 that 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 that used NSObject (with some limitations). The introduction of the two letter prefix also became a 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.

Analysis of the language

Objective-C implementations use a thin runtime system written in C, which adds little to the size of the application. In contrast, most object-oriented systems at the time that it was created used large virtual machine
Virtual machine
A virtual machine is a "completely isolated guest operating system installation within a normal host operating system". Modern virtual machines are implemented with either software emulation or hardware virtualization or both together.-VM Definitions:A virtual machine is a software...

 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), 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. Since the programmer has such freedom to delegate, forward calls, build selectors on the fly and pass them to the runtime system, the Objective-C compiler cannot assume it's safe to remove unused methods or to inline calls.

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, etc. Existing C libraries can be wrapped in Objective-C wrappers
Adapter pattern
In computer programming, the adapter pattern is a design pattern that translates one interface for a class into a compatible interface...

 to provide an OO-style interface. In this aspect, it is similar to GObject
GObject
The GLib Object System, or GObject, is a free software library providing a portable object system and transparent cross-language interoperability...

 library and Vala
Vala (programming language)
Vala is a programming language created with the goal of bringing modern language features to C, with no added runtime needs and with little overhead, by targeting the GObject object system. It is being developed by Jürg Billeter and Raffaele Sandrini. The syntax borrows heavily from C#...

 language, which are widely used in development of GTK applications.

All of these practical changes lowered the barrier to entry
Barriers to entry
In theories of competition in economics, barriers to entry are obstacles that make it difficult to enter a given market. The term can refer to hindrances a firm faces in trying to enter a market or industry - such as government regulation, or a large, established firm taking advantage of economies...

, likely the biggest problem for the widespread acceptance of Smalltalk in the 1980s.

The first versions of Objective-C did not support garbage collection
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...

. 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 has implemented it as of Mac OS X v10.5
Mac OS X v10.5
Mac OS X Leopard is the sixth major release of Mac OS X, Apple's desktop and server operating system for Macintosh computers. Leopard was released on 26 October 2007 as the successor of Tiger , and is available in two variants: a desktop version suitable for personal computers, and a...

.

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 only with that namespace. The same identifier can be independently defined in multiple namespaces...

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 or iOS core; the "NS" derives from the names of the classes as defined during the development of NeXTstep
NEXTSTEP
NeXTSTEP was the object-oriented, multitasking operating system developed by NeXT Computer to run on its range of proprietary workstation 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 programming language design, a first-class citizen , in the context of a particular programming language, is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable...

s.

Unlike C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, Objective-C does not support operator overloading
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...

. Also unlike C++, Objective-C allows an object to directly inherit only from one class (forbidding multiple inheritance
Multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....

). However, categories and protocols may be used as an alternative way to achieve the same results.

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++ where such optimizations are possible. However, this is an unavoidable tradeoff because such optimizations would be rendered ineffective by categories or other Objective-C runtime features that are impossible in C++.

Philosophical differences between Objective-C and C++

The design and implementation of C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 and Objective-C represent different approaches to extending C.

In addition to C’s style of procedural programming, C++ directly supports certain forms of object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, generic programming
Generic programming
In a broad definition, 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 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 compile time that would otherwise be done at runtime...

. C++ also comes with a large standard library that 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. In other words; they are used for storing objects in an organized way following specific access rules...

. Similarly, Objective-C adds object-oriented programming
Polymorphism in object-oriented programming
Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability to create a variable, a function, or an object that has more than one form. The word derives from the Greek "πολυμορφισμός" meaning "having multiple forms"...

, dynamic typing, and reflection
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....

 to C. Objective-C does not provide a standard library, per se, but in most places where Objective-C is used, it is used with an OpenStep
OpenStep
OpenStep was an object-oriented application programming interface specification for an object-oriented operating system that used a non-NeXTSTEP operating system as its core, principally developed by NeXT with Sun Microsystems. OPENSTEP was a specific implementation of the OpenStep API developed...

-like library such as OPENSTEP
OpenStep
OpenStep was an object-oriented application programming interface specification for an object-oriented operating system that used a non-NeXTSTEP operating system as its core, principally developed by NeXT with Sun Microsystems. OPENSTEP was a specific implementation of the OpenStep API developed...

, Cocoa
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...

, or GNUstep
GNUstep
GNUstep is a free software implementation of Cocoa Objective-C libraries , widget toolkit, and application development tools not only for Unix-like operating systems, but also for Microsoft Windows. It is part of the GNU Project.GNUstep features a cross-platform, object-oriented development...

, which provide functionality similar to C++’s standard library.

One notable difference is that Objective-C provides runtime support reflective
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....

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: dynamic features add flexibility, static features add speed and type checking.

Generic programming and metaprogramming is implemented and supported differently in each language - in Objective-C it is handled by dynamic typing and reflection, whereas in C++ it is handled via template.

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK