Objective-C

Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It is one of two main programming languages supported by Apple for macOS, iOS, and their respective application programming interfaces (APIs), Cocoa and Cocoa Touch. It was the singular main language until the introduction of Swift in 2014.
The language was originally developed in the early 1980s. It was later selected as the main language used by NeXT for its NeXTSTEP operating system, from which macOS and iOS are derived. Portable Objective-C programs that do not use Apple libraries, or those using parts that may be ported or reimplemented for other systems, can also be compiled for any system supported by GNU Compiler Collection (GCC) or Clang.
Objective-C source code 'implementation' program files usually have filename extensions, while Objective-C 'header/interface' files have extensions, the same as C header files. Objective-C++ files are denoted with a file extension.
History.
Objective-C was created primarily by Brad Cox and Tom Love in the early 1980s at their company Productivity Products International (PPI).
Leading up to the creation of their company, both had been introduced to Smalltalk while at ITT Corporation'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 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 abilities 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 one cross-platform format.
Love and Cox eventually formed PPI to commercialize their product, which coupled an Objective-C compiler with class libraries. In 1986, Cox published the main description of Objective-C in its original form in the book "Object-Oriented Programming, An Evolutionary Approach". Although he was careful to point out that there is more to the problem of reusability than just what Objective-C provides, the language often found itself compared feature for feature with other languages.
Popularization through NeXT.
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. NeXT developed the AppKit and Foundation Kit libraries on which the NeXTSTEP 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.
In order to circumvent the terms of the GPL, NeXT had originally intended to ship the Objective-C frontend separately, allowing the user to link it with GCC to produce the compiler executable. Though initially accepted by Richard M. Stallman, this plan was rejected after Stallman consulted with GNU's lawyers and NeXT agreed to make Objective-C part of GCC.
The work to extend GCC was led by Steve Naroff, who joined NeXT from StepStone. The compiler changes were made available as per GPL license terms, but the runtime libraries were not, rendering the open source contribution unusable to the general public. This led to other parties developing such runtime libraries under open source license. Later, Steve Naroff was also principal contributor to work at Apple to build the Objective-C frontend to Clang.
The GNU project started work on its free software implementation of Cocoa, named GNUstep, based on the OpenStep 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. Thorup also worked at NeXT from 1993 to 1996.
Apple development and Swift.
After acquiring NeXT in 1996, Apple Computer used OpenStep in its then-new operating system, Mac OS X. This included Objective-C, NeXT's Objective-C-based developer tool, Project Builder, and its interface design tool, Interface Builder. Both were later merged into one application, Xcode. Most of Apple's current Cocoa API is based on OpenStep interface objects and is the most significant Objective-C environment being used for active development.
At WWDC 2014, Apple introduced a new language, Swift, which was characterized as "Objective-C without the C".
Syntax.
Objective-C is a thin layer atop C and is a "strict superset" of C, meaning that it is possible to compile any C program with an Objective-C compiler and to freely include C language code within an Objective-C class.
Objective-C derives its object syntax from Smalltalk. All of the syntax for non-object-oriented operations (including primitive variables, pre-processing, expressions, function declarations, and function calls) are identical to those 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 to object instances. In Objective-C one does not "call a method"; one "sends a message". This is unlike the Simula-style programming model used by C++. The difference between these two concepts is in how the code referenced by the method or message name is executed. In a Simula-style language, the method name is in most cases bound to a section of code in the target class by the compiler. In Smalltalk and Objective-C, the target of a message is resolved at runtime, with the receiving object itself interpreting the message. A method is identified by a "selector" or — a unique identifier for each message name, often just a -terminated string representing its name — and resolved to a C method pointer implementing it: an . 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 raises an exception.
Sending the message to the object pointed to by the pointer would require the following code in C++:
obj->method(argument);
In Objective-C, this is written as follows:
[obj method:argument];
The "method" call is translated by the compiler to the family of runtime functions. Different implementations handle modern additions like . In GNU families this function is named , but it has been deprecated in favor of a modern lookup system under .
Both styles of programming have their strengths and weaknesses. Object-oriented programming in the Simula (C++) style allows multiple inheritance and faster execution by using compile-time binding whenever possible, but it does not support dynamic binding by default. It also forces all methods to have a corresponding implementation unless they are abstract. The Smalltalk-style programming as used in Objective-C 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. An implementation is still required for the method to be called in the derived object. (See the dynamic typing section below for more advantages of dynamic (late) binding.)
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 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.
This is analogous to class declarations as used in other object-oriented languages, such as C++ or Python.
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. would contain the interface for the class .
An interface declaration takes the form:
@interface classname : superclassname {
 // instance variables
+ classMethod1;
+ (return_type)classMethod2;
+ (return_type)classMethod3:(param1_type)param1_varName;
- (return_type)instanceMethod1With1Parameter:(param1_type)param1_varName;
- (return_type)instanceMethod2With2Parameters:(param1_type)param1_varName
 param2_callName:(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++ 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 instanceMethod1With1Parameter(param1_type param1_varName);
 return_type
 instanceMethod2With2Parameters(param1_type param1_varName,
 param2_type param2_varName = default);
Note that 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, a pointer to a specific type of object such as NSArray *, NSImage *, or NSString *, or a pointer to the class to which the method belongs (instancetype). The default return type is the generic Objective-C type .
Method arguments begin with a name labeling the argument that is part of the method name, followed by a colon followed by the expected argument type in parentheses and the argument name. The label can be omitted.
- (void)setRangeStart:(int)start end:(int)end;
- (void)importDocumentWithName:(NSString *)name
 withSpecifiedPreferences:(Preferences *)prefs
 beforePage:(int)insertPage;
A derivative of the interface definition is the "category", which allows one to add methods to existing classes.
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 codice_1, 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.
- (void)changeColorToRed:(float)red green:(float)green blue:(float)blue {
 //... Implementation ...
// Called like so:
[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 , instance method might be internally labeled . The 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 one line of code so that there is never an allocated object that hasn't undergone initialization (and because it is unwise to keep the intermediate result since codice_2 can return a different object than that on which it is called).
Instantiation with the default, no-parameter initializer:
MyObject *foo = ;
@end
@interface Integer (Display)
- (id) showstars;
- (id) showint;
@end
@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
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;
Notes.
Compilation is performed, for example, by:
 gcc -x objective-c main.m Integer.m Integer+Arithmetic.m Integer+Display.m -lobjc
One can experiment by leaving out the and lines and omitting in compilation. The program will still run. This means that it is possible to "mix-and-match" added categories if needed; if a category does not need to have some ability, it can simply not be compile in.
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.
Class posing was declared deprecated with Mac OS X v10.5, and is unavailable in the 64-bit runtime. Similar functionality can be achieved by using method swizzling in categories, that swaps one method's implementation with another's that have the same signature.
For the versions still supporting posing, all messages sent to the target class are instead received by the posing class. There are several restrictions:
Posing, similarly with categories, allows global augmentation of existing classes. Posing permits two features absent from categories:
For example,
@interface CustomNSApplication : NSApplication
@end
@implementation CustomNSApplication
- (void) setMainMenu: (NSMenu*) menu {
 // do something with menu
@end
class_poseAs ([CustomNSApplication class], [NSApplication class]);
This intercepts every invocation of setMainMenu to NSApplication.
#import.
In the C language, the codice_3 pre-compile directive always causes a file's contents to be inserted into the source at that point. Objective-C has the codice_4 directive, equivalent except that each file is included only once per compilation unit, obviating the need for include guards.
Linux gcc compilation.
// FILE: hello.m
int main (int argc, const char * argv[])
 /* my first program in Objective-C */
 NSLog(@"Hello, World! \n");
 return 0;
$ gcc \
 $(gnustep-config --objc-flags) \
 -o hello \
 hello.m \
 -L /GNUstep/System/Library/Libraries \
 -lobjc \
 -lgnustep-base
$ ./hello
Other features.
Objective-C's features often allow for flexible, and often easy, solutions to programming issues.
Language variants.
Objective-C++.
Objective-C++ is a language variant accepted by the front-end to the GNU Compiler Collection and Clang, which can compile source files that use a combination of C++ and Objective-C syntax. Objective-C++ adds to C++ the extensions that Objective-C adds to C. As nothing is done to unify the semantics behind the various language features, certain restrictions apply:
Objective-C 2.0.
At the 2006 Worldwide Developers Conference, 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, released in October 2007, included an Objective-C 2.0 compiler. GCC 4.6 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 GNU Objective-C runtime API.
The naming Objective-C 2.0 represents a break in the versioning system of the language, as the last Objective-C version for NeXT was "objc4". This project name was kept in the last release of legacy Objective-C runtime source code in Mac OS X Leopard (10.5).
Garbage collection.
Objective-C 2.0 provided an optional conservative, generational garbage collector. When run in backwards-compatible mode, the runtime turned reference counting operations such as "retain" and "release" into no-ops. All objects were subject to garbage collection when garbage collection was enabled. Regular C pointers could be qualified with "__strong" to also trigger the underlying write-barrier compiler intercepts and thus participate in garbage collection. A zero-ing weak subsystem was 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.
Garbage collection was deprecated in Mac OS X v10.8 in favor of Automatic Reference Counting (ARC). Objective-C on iOS 7 running on ARM64 uses 19 bits out of a 64-bit word to store the reference count, as a form of tagged pointers.
Properties.
Objective-C 2.0 introduces a new syntax to declare instance variables as properties, 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 codice_5, codice_6 or codice_7. By default, properties are considered codice_8, which results in a lock preventing multiple threads from accessing them at the same time. A property can be declared as codice_9, 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 codice_10 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 codice_11 keyword can be used to indicate that accessor methods will be provided by other means. When compiled using clang 3.1 or higher, all properties which are not explicitly declared with codice_11, marked codice_13 or have complete user-implemented getter and setter will be automatically implicitly codice_10'd.
@implementation Person
@synthesize name;
- (id)initWithAge:(int)initAge {
 self = [super init];
 if (self) {
 // NOTE: direct instance variable assignment, not property setter
 age = initAge; 
 return self;
- (int)age {
 return age;
@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 = [[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)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 [[Type introspection|introspected]].
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 code for 64-bit macOS, and all iOS). 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:
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 traits.
// 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.
Class extensions.
A class extension has the same syntax as a category declaration with no category name, and the methods and properties declared in it are added directly to the main class. It is mostly used as an alternative to a category to add methods to a class without advertising them in the public headers, with the advantage that for class extensions the compiler checks that all the privately declared methods are actually implemented.
Implications for Cocoa development.
All Objective-C applications developed for macOS 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 Mac OS X version 10.4 or earlier.
Blocks.
Blocks is a nonstandard extension for Objective-C (and [[C (programming language)|C]] and [[C++]]) that uses special syntax to create [[Closure (programming)|closures]]. Blocks are only supported in [[Mac OS X Snow Leopard|Mac OS X 10.6 "Snow Leopard"]] or later, [[iOS 4]] or later, and GNUstep with libobjc2 1.7 and compiling with [[clang]] 3.1 or later.
typedef int (^IntBlock)();
IntBlock MakeCounter(int start, int increment) {
 __block int i = start;
 return Block_copy( ^ {
 int ret = i;
 i += increment;
 return ret;
int main(void) {
 IntBlock mycounter = MakeCounter(5, 2);
 printf("First call: %d\n", mycounter());
 printf("Second call: %d\n", mycounter());
 printf("Third call: %d\n", mycounter());
 /* because it was copied, it must also be released */
 Block_release(mycounter);
 return 0;
/* Output:
 First call: 5
 Second call: 7
 Third call: 9
Modern Objective-C.
Apple has added some additional features to Objective 2.0 over time. The additions only apply to the "Apple [[LLVM]] compiler", i.e. clang frontend of the language. Confusingly, the versioning used by Apple differs from that of the LLVM upstream; refer to for a translation to open-source LLVM version numbers.
Automatic Reference Counting.
Automatic Reference Counting (ARC) is a compile-time feature that eliminates the need for programmers to manually manage retain counts using codice_7 and codice_16. Unlike [[garbage collection (computer science)|garbage collection]], which occurs at run time, ARC eliminates the overhead of a separate process managing retain counts. ARC and manual memory management are not mutually exclusive; programmers can continue to use non-ARC code in ARC-enabled projects by disabling ARC for individual code files. Xcode can also attempt to automatically upgrade a project to ARC.
ARC was introduced in LLVM 3.0. This translates to Xcode 4.2 (2011), or Apple LLVM compiler 3.0.
Literals.
NeXT and Apple Obj-C runtimes have long included a short-form way to create new strings, using the literal syntax codice_17, or drop to CoreFoundation constants codice_18 and codice_19 for codice_20 with Boolean values. Using this format saves the programmer from having to use the longer codice_21 or similar methods when doing certain operations.
When using Apple [[LLVM]] compiler 4.0 (Xcode 4.4) or later, arrays, dictionaries, and numbers (codice_22, codice_23, codice_20 classes) can also be created using literal syntax instead of methods. (Apple LLVM compiler 4.0 translates to open source LLVM and Clang 3.1.)
Example without literals:
NSArray *myArray = [NSArray arrayWithObjects:object1,object2,object3,nil];
NSDictionary *myDictionary1 = [NSDictionary dictionaryWithObject:someObject forKey:@"key"];
NSDictionary *myDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:object1, key1, object2, key2, nil];
NSNumber *myNumber = [NSNumber numberWithInt:myInt];
NSNumber *mySumNumber= [NSNumber numberWithInt:(2 + 3)];
NSNumber *myBoolNumber = [NSNumber numberWithBool:YES];
Example with literals:
NSArray *myArray = @[ object1, object2, object3 ];
NSDictionary *myDictionary1 = @{ @"key" : someObject };
NSDictionary *myDictionary2 = @{ key1: object1, key2: object2 };
NSNumber *myNumber = @(myInt);
NSNumber *mySumNumber = @(2+3);
NSNumber *myBoolNumber = @YES;
NSNumber *myIntegerNumber = @8;
However, different from [[string literal]]s, which compile to constants in the executable, these literals compile to code equivalent to the above method calls. In particular, under manually reference-counted memory management, these objects are autoreleased, which requires added care when e.g., used with function-static variables or other kinds of globals.
Subscripting.
When using Apple [[LLVM]] compiler 4.0 or later, arrays and dictionaries (codice_22 and codice_23 classes) can be manipulated using subscripting. Subscripting can be used to retrieve values from indexes (array) or keys (dictionary), and with mutable objects, can also be used to set objects to indexes or keys. In code, subscripting is represented using brackets codice_27.
Example without subscripting:
id object1 = [someArray objectAtIndex:0];
id object2 = [someDictionary objectForKey:@"key"];
[someMutableArray replaceObjectAtIndex:0 withObject:object3];
[someMutableDictionary setObject:object4 forKey:@"key"];
Example with subscripting:
id object1 = someArray[0];
id object2 = someDictionary[@"key"];
someMutableArray[0] = object3;
someMutableDictionary[@"key"] = object4;
"Modern" Objective-C syntax (1997).
After the purchase of NeXT by Apple, attempts were made to make the language more acceptable to programmers more familiar with [[Java (programming language)|Java]] than Smalltalk. One of these attempts was introducing what was dubbed "Modern Syntax" for Objective-C at the time (as opposed to the current, "classic" syntax). There was no change in behaviour, this was merely an alternative syntax. Instead of writing a method invocation like
 object = [[MyClass alloc] init];
 [object firstLabel: param1 secondLabel: param2];
It was instead written as
 object = (MyClass.alloc).init;
 object.labels ( param1, param2 );
Similarly, declarations went from the form
 -(void) firstLabel: (int)param1 secondLabel: (int)param2;
to
 -(void) labels ( int param1, int param2 );
This "modern" syntax is no longer supported in current dialects of the Objective-C language.
mulle-objc.
The mulle-objc project is another re-implementation of Objective-C. It supports [[GNU Compiler Collection|GCC]] or [[Clang]]/[[LLVM]] compilers as backends. It diverges from other runtimes in terms of syntax, semantics and ABI compatibility. It supports Linux, FreeBSD, and Windows.
Portable Object Compiler.
Besides the [[GNU Compiler Collection|GCC]]/[[NeXT]]/[[Apple Inc.|Apple]] implementation, which added several extensions to the original [[Stepstone]] implementation, another [[Free and open source software|free, open-source]] 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]]-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 [[GEOS (16-bit operating system)|PC GEOS]] 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]] compiler suite, part of the [[LLVM]] project, implements Objective-C and other languages. After GCC 4.3 (2008) switched to GPLv3, Apple abandoned it in favor of clang, a compiler it has more legal power to modify. As a result, many of the modern Objective-C language features are supported only by Clang.
Apple's versioning scheme for its clang-based "LLVM compiler" differs from the LLVM's open-source versioning. See for a translation
GNU, GNUstep, and WinObjC.
The GNU project has, for a long time, been interested in a platform to port NeXT and Obj-C programs to. The ChangeLog for the directory in GCC suggests that it existed before 1998 (GCC 2.95), and its README further points at a rewrite in 1993 (GCC 2.4).
The NeXT frontend source code was released since it was made as part of GCC, released [[GNU Public License]] which forces ones making derivative works to do so. Apple continued this tradition in releasing its fork of GCC up to 4.2.1, after which they abandoned the compiler. GCC maintainers took in the changes, but did not invest much in supporting newer features such as the Objective-C 2.0 language.
The GNUstep developers, interested in the new language, forked the GCC to a project independent of GCC called in 2009. They also arranged for the runtime to be used with Clang to take advantage of the new language syntax. GCC moved slowly at the same time, but at GCC 4.6.0 (2011) they have moved on to Objective-C 2.0 in their libobjc as well. GNUstep documentation suggest that the GCC implementation still lacks support for blocks, non-fragile variables, and the newer ARC.
[[Microsoft]] forked into a part of [[WinObjC]], the iOS bridge for [[Universal Windows Platform]], in 2015. Combined with its own implementation of [[Cocoa Touch]] and underlying APIs, the project allows the reuse of iOS Application code inside of UWP apps.
On Windows, Objective-C Development tools are provided for download on GNUStep's website. The GNUStep Development System consists of the following packages: GNUstep [[MinGW|MSYS]] System, GNUstep Core, GNUstep Devel, GNUstep Cairo, ProjectCenter IDE (Like Xcode, but not as complex), Gorm (Interface Builder Like Xcode NIB builder). These binary installers have not been updated since 2016, so it could be a better idea to just install by building under [[Cygwin]] or [[MSYS2]] instead.
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 (API)|Cocoa]], [[GNUstep]] or [[ObjFW]]. These libraries often come with the operating system: the GNUstep libraries often come with [[Linux]]-based distributions and Cocoa comes with macOS. The programmer is not forced to inherit functionality from the existing base class (NSObject / OFObject). 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.
More recently, package managers have started appearing, such as [[CocoaPods]], which aims to be both a package manager and a repository of packages. A lot of open-source Objective-C code that was written in the last few years can now be installed using CocoaPods.
Analysis of the language.
Objective-C implementations use a thin [[Run time system|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]] 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 is safe to remove unused methods or to inline calls.
Likewise, the language can be implemented atop extant C compilers (in [[GNU Compiler Collection|GCC]], 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 [[Adapter pattern|wrappers]] to provide an OO-style interface. In this aspect, it is similar to [[GObject]] library and [[Vala (programming language)|Vala]] language, which are widely used in development of [[GTK]] applications.
All of these practical changes lowered the [[Barriers to entry|barrier to entry]], likely the biggest problem for the widespread acceptance of Smalltalk in the 1980s.
A common criticism is that Objective-C does not have language support for [[namespaces]]. 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 macOS classes and functions in the [[Cocoa (software)|Cocoa]] programming environment are prefixed with "NS" (e.g. NSObject, NSButton) to identify them as belonging to the macOS or iOS core; the "NS" derives from the names of the classes as defined during the development of [[NeXTSTEP]].
Since Objective-C is a strict superset of C, it does not treat C primitive types as [[first-class object]]s.
Unlike [[C++]], Objective-C does not support [[operator overloading]]. Also unlike C++, Objective-C allows an object to directly inherit only from one class (forbidding [[multiple inheritance]]). However, in most cases, categories and protocols may be used as alternative ways 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.
Memory management.
The first versions of Objective-C did not support [[garbage collection (computer science)|garbage collection]]. At the time this decision was a matter of some debate, and many people considered long "dead times" (when Smalltalk performed collection) to render the entire system unusable. Some 3rd party implementations have added this feature (most notably GNUstep using [[Boehm garbage collector|Boehm]]), and Apple has implemented it as of [[Mac OS X v10.5]]. However, in more recent versions of macOS and iOS, garbage collection has been deprecated in favor of [[Automatic Reference Counting]] (ARC), introduced in 2011.
With ARC, the compiler inserts retain and release calls automatically into Objective-C code based on [[Static program analysis|static code analysis]]. The automation relieves the programmer of having to write in memory management code. ARC also adds weak references to the Objective-C language.
Philosophical differences between Objective-C and C++.
The design and implementation of [[C++]] and Objective-C represent fundamentally different approaches to extending C.
In addition to C's style of procedural programming, C++ directly supports certain forms of [[object-oriented programming]], [[generic programming]], and [[metaprogramming]]. C++ also comes with [[C++ standard library|a large standard library]] that includes [[Sequence container (C++)|several container classes]]. Similarly, Objective-C adds [[Polymorphism in object-oriented programming|object-oriented programming]], [[dynamic typing]], and [[reflection (computer science)|reflection]] 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]]-like library such as [[OPENSTEP]], [[Cocoa (API)|Cocoa]], or [[GNUstep]], which provides functionality similar to C++'s standard library.
One notable difference is that Objective-C provides runtime support for [[reflection (computer science)|reflective]] 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, e.g., 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 and 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 can be implemented in both languages using [[runtime polymorphism]]. In C++ this takes the form of [[virtual function]]s and [[runtime type identification]], while Objective-C offers dynamic typing and reflection. Both Objective-C and C++ support compile-time polymorphism ([[generic function]]s), with Objective-C only adding this feature in 2015.
External links.
[[Category:Objective-C| ]]
[[Category:C programming language family]]
[[Category:Class-based programming languages]]
[[Category:Dynamically typed programming languages]]
[[Category:GNUstep]]
[[Category:NeXT]]
[[Category:Object-oriented programming languages]]
[[Category:Programming languages created in 1986]]