fbpx
Wikipedia

Objective-C

Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C[3] programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Due to Apple macOS’s direct lineage from NeXTSTEP,[4] Objective-C was the standard programming language used, supported, and promoted by Apple for developing macOS and iOS applications (via their respective APIs, Cocoa and Cocoa Touch) until the introduction of the Swift programming language in 2014.[3]

Objective-C
FamilyC
Designed byTom Love and Brad Cox
First appeared1984; 39 years ago (1984)
Stable release
2.0[1]
Typing disciplineStatic, dynamic, weak
OSCross-platform
Filename extensions.h, .m, .mm, .M
Websitedeveloper.apple.com
Major implementations
Clang, GCC
Influenced by
C, Smalltalk
Influenced
Groovy, Java, Nu, Objective-J, TOM, Swift[2]
  • Objective-C Programming at Wikibooks

Objective-C programs developed for non-Apple operating systems or that are not dependent on Apple's APIs may also be compiled for any platform supported by GNU GCC or LLVM/Clang.

Objective-C source code 'messaging/implementation' program files usually have .m filename extensions, while Objective-C 'header/interface' files have .h extensions, the same as C header files. Objective-C++ files are denoted with a .mm 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).[5]

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.[6] 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.[7]

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.[8] 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.[9]

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.[10] 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.[citation needed] Thorup also worked at NeXT from 1993 to 1996.[11]

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.[12][13][14][15][16][17]

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 SEL — a unique identifier for each message name, often just a NUL-terminated string representing its name — and resolved to a C method pointer implementing it: an IMP.[18] 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.[19]

Sending the message method to the object pointed to by the pointer obj 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 objc_msgSend(id self, SEL op, ...) family of runtime functions. Different implementations handle modern additions like super.[20] In GNU families this function is named objc_msg_sendv, but it has been deprecated in favor of a modern lookup system under objc_msg_lookup.[21]

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. 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)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 instanceMethod2With2Parameters:param2_callName: 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 id.

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.[22]

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".[23]

@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 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 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 -init can return a different object than that on which it is called).

Instantiation with the default, no-parameter initializer:

MyObject *foo = [[MyObject alloc] init]; 

Instantiation with a custom initializer:

MyObject *foo = [[MyObject alloc] initWithString:myString]; 

In the case where no custom initialization is being performed, the "new" method can often be used in place of the alloc-init messages:

MyObject *foo = [MyObject new]; 

Also, some classes implement class method initializers. Like +new, they combine +alloc and -init, but unlike +new, they return an autoreleased instance. Some class method initializers take parameters:

MyObject *foo = [MyObject object]; MyObject *bar = [MyObject objectWithString:@"Wikipedia :)"]; 

The alloc message allocates enough memory to hold all the instance variables for an object, sets all the instance variables to zero values, and turns the memory into an instance of the class; at no point during the initialization is the memory an instance of the superclass.

The init message performs the set-up of the instance upon creation. The init method is often written as follows:

- (id)init {  self = [super init];  if (self) {  // perform initialization of object here  }  return self; } 

In the above example, notice the id return type. This type stands for "pointer to any object" in Objective-C (See the Dynamic typing section).

The initializer pattern is used to assure that the object is properly initialized by its superclass before the init method performs its initialization. It performs the following actions:

  • Line 2
    Sends the superclass instance an init message and assigns the result to self (pointer to the current object).
  • Line 3
    Checks if the returned object pointer is valid before performing any initialization.
  • Line 6
    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 "designated initializer") needs to follow this pattern; others should call the designated initializer instead of the superclass initializer.

Protocols

In other programming languages, these are called "interfaces".

Objective-C was extended at NeXT to introduce the concept of multiple inheritance of specification, but not implementation, through the introduction of protocols. This is a pattern achievable either as an abstract multiple inherited base class in C++, or as an "interface" (as in Java and C#). Objective-C makes use of ad hoc protocols called informal protocols and compiler-enforced protocols called formal protocols.

An informal protocol is a list of methods that a class can opt to implement. It is specified in the documentation, since it has no presence in the language. Informal protocols are implemented as a category (see below) on NSObject and often include optional methods, which, if implemented, can change the behavior of a class. For example, a text field class might have a delegate that implements an informal protocol with an optional method for performing auto-completion of user-typed text. The text field discovers whether the delegate implements that method (via reflection) and, if so, calls the delegate's method to support the auto-complete feature.

A formal protocol is similar to an interface in Java, C#, and Ada 2005. It is a list of methods that any class can declare itself to implement. Versions of Objective-C before 2.0 required that a class must implement all methods in a protocol it declares itself as adopting; the compiler will emit an error if the class does not implement every method from its declared protocols. Objective-C 2.0 added support for marking certain methods in a protocol optional, and the compiler will not enforce implementation of optional methods.

A class must be declared to implement that protocol to be said to conform to it. This is detectable at runtime. Formal protocols cannot provide any implementations; they simply assure callers that classes that conform to the protocol will provide implementations. In the NeXT/Apple library, protocols are frequently used by the Distributed Objects system to represent the abilities of an object executing on a remote system.

The syntax

@protocol NSLocking - (void)lock; - (void)unlock; @end 

denotes that there is the abstract idea of locking. By stating in the class definition that the protocol is implemented,

@interface NSLock : NSObject <NSLocking> // ... @end 

instances of NSLock claim that they will provide an implementation for the two instance methods.

Dynamic typing

Objective-C, like Smalltalk, can use dynamic typing: an object can be sent a message that is not specified in its interface. This can allow for increased flexibility, as it allows an object to "capture" a message and send the message to a different object that can respond to the message appropriately, or likewise send the message on to another object. This behavior is known as message forwarding or delegation (see below). Alternatively, an error handler can be used in case the message cannot be forwarded. If an object does not forward a message, respond to it, or handle an error, then the system will generate a runtime exception.[24] If messages are sent to nil (the null object pointer), they will be silently ignored or raise a generic exception, depending on compiler options.

Static typing information may also optionally be added to variables. This information is then checked at compile time. In the following four statements, increasingly specific type information is provided. The statements are equivalent at runtime, but the extra information allows the compiler to warn the programmer if the passed argument does not match the type specified.

- (void)setMyValue:(id)foo; 

In the above statement, foo may be of any class.

- (void)setMyValue:(id<NSCopying>)foo; 

In the above statement, foo may be an instance of any class that conforms to the NSCopying protocol.

- (void)setMyValue:(NSNumber *)foo; 

In the above statement, foo must be an instance of the NSNumber class.

- (void)setMyValue:(NSNumber<NSCopying> *)foo; 

In the above statement, foo must be an instance of the NSNumber class, and it must conform to the NSCopying protocol.

In Objective-C, all objects are represented as pointers, and static initialization is not allowed. The simplest object is the type that id (objc_obj *) points to, which only has an isa pointer describing its class. Other types from C, like values and structs, are unchanged because they are not part of the object system. This decision differs from the C++ object model, where structs and classes are united.

Forwarding

Objective-C permits the sending of a message to an object that may not respond. Rather than responding or simply dropping the message, an object can forward the message to an object that can respond. Forwarding can be used to simplify implementation of certain design patterns, such as the observer pattern or the proxy pattern.

The Objective-C runtime specifies a pair of methods in Object

  • forwarding methods:
    - (retval_t)forward:(SEL)sel args:(arglist_t)args; // with GCC - (id)forward:(SEL)sel args:(marg_list)args; // with NeXT/Apple systems 
  • action methods:
    - (retval_t)performv:(SEL)sel args:(arglist_t)args; // with GCC - (id)performv:(SEL)sel args:(marg_list)args; // with NeXT/Apple systems 

An object wishing to implement forwarding needs only to override the forwarding method with a new method to define the forwarding behavior. The action method performv:: need not be overridden, as this method merely performs an action based on the selector and arguments. Notice the SEL type, which is the type of messages in Objective-C.

Note: in OpenStep, Cocoa, and GNUstep, the commonly used frameworks of Objective-C, one does not use the Object class. The - (void)forwardInvocation:(NSInvocation *)anInvocation method of the NSObject class is used to do forwarding.

Example

Here is an example of a program that demonstrates the basics of forwarding.

Forwarder.h
#import <objc/Object.h> @interface Forwarder : Object {  id recipient; // The object we want to forward the message to. } // Accessor methods. - (id)recipient; - (id)setRecipient:(id)_recipient; @end 
Forwarder.m
#import "Forwarder.h" @implementation Forwarder - (retval_t)forward:(SEL)sel args:(arglist_t)args {  /*  * Check whether the recipient actually responds to the message.  * This may or may not be desirable, for example, if a recipient  * in turn does not respond to the message, it might do forwarding  * itself.  */  if ([recipient respondsToSelector:sel]) {  return [recipient performv:sel args:args];  } else {  return [self error:"Recipient does not respond"];  } } - (id)setRecipient:(id)_recipient {  [recipient autorelease];  recipient = [_recipient retain];  return self; } - (id)recipient {  return recipient; } @end 
Recipient.h
#import <objc/Object.h> // A simple Recipient object. @interface Recipient : Object - (id)hello; @end 
Recipient.m
#import "Recipient.h" @implementation Recipient - (id)hello {  printf("Recipient says hello!\n");  return self; } @end 
main.m
#import "Forwarder.h" #import "Recipient.h" int main(void) {  Forwarder *forwarder = [Forwarder new];  Recipient *recipient = [Recipient new];  [forwarder setRecipient:recipient]; // Set the recipient.  /*  * Observe forwarder does not respond to a hello message! It will  * be forwarded. All unrecognized methods will be forwarded to  * the recipient  * (if the recipient responds to them, as written in the Forwarder)  */  [forwarder hello];  [recipient release];  [forwarder release];  return 0; } 

Notes

When compiled using gcc, the compiler reports:

$ gcc -x objective-c -Wno-import Forwarder.m Recipient.m main.m -lobjc main.m: In function `main': main.m:12: warning: `Forwarder' does not respond to `hello' $ 

The compiler is reporting the point made earlier, that Forwarder does not respond to hello messages. In this circumstance, it is safe to ignore the warning since forwarding was implemented. Running the program produces this output:

$ ./a.out Recipient says hello! 

Categories

During the design of Objective-C, one of the main concerns was the maintainability of large code bases. Experience from the structured programming world had shown that one of the main ways to improve code was to break it down into smaller pieces. Objective-C borrowed and extended the concept of categories from Smalltalk implementations to help with this process.[25]

Furthermore, the methods within a category are added to a class at run-time. Thus, categories permit the programmer to add methods to an existing class - an open class - without the need to recompile that class or even have access to its source code. For example, if a system does not contain a spell checker in its String implementation, it could be added without modifying the String source code.

Methods within categories become indistinguishable from the methods in a class when the program is run. A category has full access to all of the instance variables within the class, including private variables.

If a category declares a method with the same method signature as an existing method in a class, the category's method is adopted. Thus categories can not only add methods to a class, but also replace existing methods. This feature can be used to fix bugs in other classes by rewriting their methods, or to cause a global change to a class's behavior within a program. If two categories have methods with the same name but different method signatures, it is undefined which category's method is adopted.

Other languages have attempted to add this feature in a variety of ways. TOM took the Objective-C system a step further and allowed for the addition of variables also. Other languages have used prototype-based solutions instead, the most notable being Self.

The C# and Visual Basic.NET languages implement superficially similar functionality in the form of extension methods, but these lack access to the private variables of the class.[26] Ruby and several other dynamic programming languages refer to the technique as "monkey patching".

Logtalk implements a concept of categories (as first-class entities) that subsumes Objective-C categories functionality (Logtalk categories can also be used as fine-grained units of composition when defining e.g. new classes or prototypes; in particular, a Logtalk category can be virtually imported by any number of classes and prototypes).

Example use of categories

This example builds up an Integer class, by defining first a basic class with only accessor methods implemented, and adding two categories, Arithmetic and Display, which extend the basic class. While categories can access the base class's private data members, it is often good practice to access these private data members through the accessor methods, which helps keep categories more independent from the base class. Implementing such accessors is one typical use of categories. Another is to use categories to add methods to the base class. However, it is not regarded as good practice to use categories for subclass overriding, also known as monkey patching. Informal protocols are implemented as a category on the base NSObject class. By convention, files containing categories that extend base classes will take the name BaseClass+ExtensionClass.h.

Integer.h
#import <objc/Object.h> @interface Integer : Object {  int integer; } - (int)integer; - (id)integer:(int)_integer; @end 
Integer.m
#import "Integer.h" @implementation Integer - (int) integer {  return integer; } - (id) integer: (int) _integer {  integer = _integer;  return self; } @end 
Integer+Arithmetic.h
#import "Integer.h" @interface Integer (Arithmetic) - (id) add: (Integer *) addend; - (id) sub: (Integer *) subtrahend; @end 
Integer+Arithmetic.m
#import "Integer+Arithmetic.h" @implementation Integer (Arithmetic) - (id) add: (Integer *) addend {  return [self integer: [self integer] + [addend integer]]; } - (id) sub: (Integer *) subtrahend {  return [self integer: [self integer] - [subtrahend integer]]; } @end 
Integer+Display.h
#import "Integer.h" @interface Integer (Display) - (id) showstars; - (id) showint; @end 
Integer+Display.m
# import "Integer+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
#import "Integer.h" #import "Integer+Arithmetic.h" #import "Integer+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; } 

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 #import "Integer+Arithmetic.h" (line 2) and [num1 add:num2] (line 21) and omitting Integer+Arithmetic.m 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:

  • 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.

#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 #import 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 #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) {  /* my first program in Objective-C */  NSLog(@"Hello, World! \n");  return 0; } 
$ # Compile Command Line for gcc and MinGW Compiler: $ 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.

  • Delegating methods to other objects and remote invocation can be easily implemented using categories and message forwarding.
  • Swizzling of the isa pointer allows for classes to change at runtime. Typically used for debugging 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 to create database faults.[citation needed] Swizzling is used today by Apple's Foundation Framework to implement Key-Value Observing.

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:

  • 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 lack a default constructor or that have one or more virtual methods,[citation needed] 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. As a result, object destructors are not run. This is mitigated in recent "Objective-C 2.0" runtimes as Objective-C exceptions are either replaced by C++ exceptions completely (Apple runtime), or partly when Objective-C++ library is linked (GNUstep libobjc2).[27]
  • Objective-C blocks and C++11 lambdas are distinct entities. However, a block is transparently generated on macOS when passing a lambda where a block is expected.[28]

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,[29] runtime performance improvements,[30] 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.[31]

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".[32] This project name was kept in the last release of legacy Objective-C runtime source code in Mac OS X Leopard (10.5).[33]

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.[34] 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.[35] 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.[36]

Garbage collection was deprecated in Mac OS X v10.8 in favor of Automatic Reference Counting (ARC).[37] 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.[38][39]

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 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. When compiled using clang 3.1 or higher, all properties which are not explicitly declared with @dynamic, marked readonly or have complete user-implemented getter and setter will be automatically implicitly @synthesize'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 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:

  • It eliminates the fragile binary interface problem; superclasses can change sizes without affecting binary compatibility.
  • It allows instance variables that provide the backing for properties to be synthesized at runtime without them being declared in the class's 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 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.[40]

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.[41]

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 and C++) that uses special syntax to create closures. Blocks are only supported in 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.[42]

#include <stdio.h> #include <Block.h> 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 Xcode § Toolchain versions for a translation to open-source LLVM version numbers.[43]

Automatic Reference Counting

Automatic Reference Counting (ARC) is a compile-time feature that eliminates the need for programmers to manually manage retain counts using retain and release.[44] Unlike 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.[45]

Literals

NeXT and Apple Obj-C runtimes have long included a short-form way to create new strings, using the literal syntax @"a new string", or drop to CoreFoundation constants kCFBooleanTrue and kCFBooleanFalse for NSNumber with Boolean values. Using this format saves the programmer from having to use the longer initWithString or similar methods when doing certain operations.

When using Apple LLVM compiler 4.0 (Xcode 4.4) or later, arrays, dictionaries, and numbers (NSArray, NSDictionary, NSNumber classes) can also be created using literal syntax instead of methods.[46] (Apple LLVM compiler 4.0 translates to open source LLVM and Clang 3.1.)[47]

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 literals, 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 (NSArray and NSDictionary classes) can be manipulated using subscripting.[46] 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 [ ].[48]

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 than Smalltalk. One of these attempts was introducing what was dubbed "Modern Syntax" for Objective-C at the time[49] (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 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 GCC/NeXT/Apple implementation, which added several extensions to the original Stepstone implementation, another free, open-source Objective-C implementation called the Portable Object Compiler also exists.[50] 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 PC GEOS system used a programming language known as GEOS Objective-C or goc;[51] 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 Xcode § Toolchain versions for a translation[43]

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 libobjc 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).[52]

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.[when?] 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.[32]: Which compiler 

The GNUstep developers, interested in the new language, forked the GCC libobjc to a project independent of GCC called libobjc2 in 2009. They also arranged for the runtime to be used with Clang to take advantage of the new language syntax.[32]: Which compiler  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.[31][53] GNUstep documentation suggest that the GCC implementation still lacks support for blocks, non-fragile variables, and the newer ARC.[32]: Which runtime 

Microsoft forked libobjc2 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.[54]

On Windows, Objective-C Development tools are provided for download on GNUStep's website. The GNUStep Development System consists of the following packages: GNUstep 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,[55] 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, 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 runtime system written in C[citation needed], 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 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 wrappers to provide an OO-style interface. In this aspect, it is similar to GObject library and Vala language, which are widely used in development of GTK applications.

All of these practical changes lowered the 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 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 objects.

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. 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), and Apple has implemented it as of Mac OS X v10.5.[56] 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 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.[57]

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 a large standard library that includes several container classes. Similarly, Objective-C adds object-oriented programming, dynamic typing, and 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, or GNUstep, which provides functionality similar to C++'s standard library.

One notable difference is that Objective-C provides runtime support for 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 functions and runtime type identification, while Objective-C offers dynamic typing and reflection. Both Objective-C and C++ support compile-time polymorphism (generic functions), with Objective-C only adding this feature in 2015.

See also

References

  1. ^ "Runtime Versions and Platforms". Developer.apple.com. from the original on July 20, 2016. Retrieved December 24, 2017.
  2. ^ Lattner, Chris (June 3, 2014). "Chris Lattner's Homepage". Chris Lattner. from the original on June 4, 2014. Retrieved June 3, 2014. The Swift language is the product of tireless effort from a team of language experts, documentation gurus, compiler optimization ninjas, and an incredibly important internal dogfooding group who provided feedback to help refine and battle-test ideas. Of course, it also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
  3. ^ a b "App Frameworks". Apple. June 2014. from the original on February 16, 2019. Retrieved February 13, 2019.
  4. ^ Singh, Amit (December 2003). "A Brief History of Mac OS X". Mac OS X Internals. from the original on May 14, 2012. Retrieved June 11, 2012.
  5. ^ Garling, Caleb. "iPhone Coding Language Now World's Third Most Popular". Wired. from the original on September 9, 2013. Retrieved May 20, 2013.
  6. ^ Wentk, Richard (2009). Cocoa: Volume 5 of Developer Reference Apple Developer Series. John Wiley and Sons. ISBN 978-0-470-49589-6. from the original on February 16, 2017. Retrieved July 22, 2016.
  7. ^ Biancuzzi, Federico; Warden, Shane (2009). Masterminds of Programming. O'Reilly Media, Inc. pp. 242–246. ISBN 978-0-596-51517-1. from the original on February 17, 2017. Retrieved July 22, 2016.
  8. ^ Cox, Brad (1983). "The object oriented pre-compiler: programming Smalltalk 80 methods in C language". ACM SIGPLAN Notices. New York, NY: ACM. 18 (1). doi:10.1145/948093.948095. S2CID 6975032. Retrieved February 17, 2011.
  9. ^ "Common Lisp and Readline". GitHub. from the original on September 6, 2014. Retrieved September 15, 2014. The issue first arose when NeXT proposed to distribute a modified GCC in two parts and let the user link them. Jobs asked me whether this was lawful. It seemed to me at the time that it was, following reasoning like what you are using; but since the result was very undesirable for free software, I said I would have to ask the lawyer. What the lawyer said surprised me; he said that judges would consider such schemes to be "subterfuges" and would be very harsh toward them. He said a judge would ask whether it is "really" one program, rather than how it is labeled. So I went back to Jobs and said we believed his plan was not allowed by the GPL. The direct result of this is that we now have an Objective C front end. They had wanted to distribute the Objective C parser as a separate proprietary package to link with the GCC back end, but since I didn't agree this was allowed, they made it free.
  10. ^ "GNUstep: Introduction". GNUstep developers/GNU Project. from the original on August 6, 2012. Retrieved July 29, 2012.
  11. ^ "Kresten Krab Thorup | LinkedIn". www.linkedin.com. from the original on July 15, 2014. Retrieved June 23, 2016.
  12. ^ "Write Objective-C Code". apple.com. April 23, 2013. from the original on December 24, 2013. Retrieved December 22, 2013.
  13. ^ "Objective-C Boot Camp". from the original on February 11, 2018. Retrieved February 11, 2018. Objective-C is a strict superset of ANSI C
  14. ^ "Examining Objective-C". from the original on September 4, 2014. Retrieved September 4, 2014. Objective-C is an object-oriented strict superset of C
  15. ^ Lee, Keith (September 3, 2013). Pro Objective-C. Apress. ISBN 9781430250500. from the original on May 14, 2018. Retrieved December 24, 2017 – via Google Books.
  16. ^ "Tags for Objective-C Headers". from the original on April 1, 2017. Retrieved February 11, 2018. Objective-C is a superset of C
  17. ^ "AppScan Source 8.7 now available". from the original on February 3, 2017. Retrieved February 11, 2018. The Objective-C programming language is a superset of the C programming language
  18. ^ Apple, Inc. (October 19, 2009). "Dynamic Method Resolution". Objective-C Runtime Programming Guide. from the original on September 7, 2010. Retrieved November 25, 2014.
  19. ^ Apple, Inc. (October 19, 2009). . The Objective-C Programming Language. Archived from the original on September 8, 2010.
  20. ^ "objc_msgSend - Objective-C Runtime". Apple Developer Documentation. Retrieved February 10, 2020.
  21. ^ "Messaging with the GNU Objective-C runtime". Using the GNU Compiler Collection (GCC). Retrieved February 10, 2020.
  22. ^ "Category". Apple Developer (Cocoa Core Competencies).
  23. ^ Dalrymple, Mark; Knaster, Scott (June 27, 2012). Learn Objective-C on the Mac. p. 9. ISBN 9781430241881. The .m extension originally stood for "messages" when Objective-C was first introduced, referring to a central feature of Objective-C
  24. ^ "Objective-C Runtime Programming Guide". Apple Inc. from the original on April 4, 2014. Retrieved October 21, 2013.
  25. ^ . Archived from the original on 15 April 2009. Retrieved 7 October 2008.
  26. ^ "Extension Methods (C# Programming Guide)". Microsoft. October 2010. from the original on July 11, 2011. Retrieved July 10, 2011.
  27. ^ . Mac OS X Reference Library. Archived from the original on September 5, 2010. Retrieved February 10, 2010.
  28. ^ "Clang Language Extensions — Clang 3.5 documentation". Clang.llvm.org. from the original on February 24, 2014. Retrieved April 16, 2014.
  29. ^ . Lists.apple.com. August 10, 2006. Archived from the original on June 18, 2009. Retrieved May 30, 2010.
  30. ^ . Lists.apple.com. Archived from the original on November 24, 2010. Retrieved May 30, 2010.
  31. ^ a b "GCC 4.6 Release Series — Changes, New Features, and Fixes : GNU Project : Free Software Foundation". Gcc.gnu.org. from the original on January 5, 2018. Retrieved December 24, 2017.
  32. ^ a b c d "ObjC2 FAQ". GNUstep. Retrieved January 6, 2020.
  33. ^ "Source Browser: objc4, 756.2". Apple Open Source. Retrieved January 6, 2020.
  34. ^ Garbage Collection Programming Guide: Garbage Collection API June 9, 2012, at the Wayback Machine (Apple developer website - search for "__strong")
  35. ^ "Garbage Collection Programming Guide: Introduction to Garbage Collection". Apple Inc. October 3, 2011. from the original on June 9, 2012. Retrieved December 23, 2011.
  36. ^ . Apple Inc. November 6, 2007. Archived from the original on July 24, 2010. Retrieved May 30, 2010.
  37. ^ "Transitioning to ARC Release Notes". Apple Inc. July 17, 2012. from the original on June 9, 2012. Retrieved August 26, 2012.
  38. ^ Mike Ash. "Friday Q&A 2013-09-27: ARM64 and You". mikeash.com. from the original on April 26, 2014. Retrieved April 27, 2014.
  39. ^ "Hamster Emporium: [objc explain]: Non-pointer isa". Sealiesoftware.com. September 24, 2013. from the original on June 3, 2014. Retrieved April 27, 2014.
  40. ^ Apple, Inc. (2009). "Fast Enumeration". apple.com. from the original on December 17, 2009. Retrieved December 31, 2009.
  41. ^ Free Software Foundation, Inc. (2011). "GCC 4.6 Release Series – Changes, New Features, and Fixes". Gcc.gnu.org. from the original on December 2, 2013. Retrieved November 27, 2013.
  42. ^ "Blocks Programming Topics – Mac Developer Library". Apple Inc. March 8, 2011. from the original on June 9, 2012. Retrieved November 28, 2012.
  43. ^ a b "Objective-C Automatic Reference Counting (ARC) — Clang 11 documentation". Clang documentation. Retrieved February 20, 2020. For now, it is sensible to version this document by the releases of its sole implementation (and its host project), clang. "LLVM X.Y" refers to an open-source release of clang from the LLVM project. "Apple X.Y" refers to an Apple-provided release of the Apple LLVM Compiler.
  44. ^ "Transitioning to ARC". Apple Inc. from the original on September 7, 2011. Retrieved October 8, 2012.
  45. ^ "LLVM 3.0 Release Notes". releases.llvm.org.
  46. ^ a b "Programming with Objective-C: Values and Collections". Apple Inc. from the original on September 7, 2011. Retrieved October 8, 2012.
  47. ^ "Clang 3.1 Release Notes". releases.llvm.org.
  48. ^ "Objective-C Literals — Clang 3.5 documentation". Clang.llvm.org. from the original on June 6, 2014. Retrieved April 16, 2014.
  49. ^ Rhapsody Developer's Guide, AP Professional, 1997, pp. 76–84
  50. ^ "Portable Object Compiler". Users.pandora.be. January 1, 1970. from the original on August 2, 2008. Retrieved May 30, 2010.
  51. ^ . Archived from the original on July 27, 2011. Retrieved December 8, 2010.
  52. ^ "gcc/libobjc". GitHub. gcc-mirror. January 6, 2020. Retrieved January 6, 2020. he runtime has been completely rewritten in gcc 2.4. The earlier runtime had several severe bugs and was rather incomplete.
  53. ^ "GNU Objective-C runtime API". Using GCC. Retrieved January 6, 2020.
  54. ^ "WinObjC on GitHub". GitHub. from the original on December 2, 2017. Retrieved February 13, 2018.
  55. ^ "GNUStep Installer". from the original on February 17, 2018. Retrieved February 14, 2018.
  56. ^ Apple, Inc. (August 22, 2006). . apple.com. Archived from the original on October 24, 2007. Retrieved August 22, 2006.
  57. ^ "Transitioning to ARC Release Notes". iOS Developer Library. Developer.apple.com. from the original on September 7, 2011. Retrieved April 16, 2014.

Further reading

  • Cox, Brad J. (1991). Object Oriented Programming: An Evolutionary Approach. Addison Wesley. ISBN 0-201-54834-8.

External links

  • Programming with Objective-C, from Apple (2012-12-13)
  • The Objective-C Programming Language, from Apple (2011-10-11)
  • Objective-C Runtime Programming Guide, from Apple (2009-10-19)
  • Objective-C GNUstep Base Programming Manual
  • Objective-C FAQ

objective, high, level, general, purpose, object, oriented, programming, language, that, adds, smalltalk, style, messaging, programming, language, originally, developed, brad, love, early, 1980s, selected, next, nextstep, operating, system, apple, macos, direc. Objective C is a high level general purpose object oriented programming language that adds Smalltalk style messaging to the C 3 programming language Originally developed by Brad Cox and Tom Love in the early 1980s it was selected by NeXT for its NeXTSTEP operating system Due to Apple macOS s direct lineage from NeXTSTEP 4 Objective C was the standard programming language used supported and promoted by Apple for developing macOS and iOS applications via their respective APIs Cocoa and Cocoa Touch until the introduction of the Swift programming language in 2014 3 Objective CFamilyCDesigned byTom Love and Brad CoxFirst appeared1984 39 years ago 1984 Stable release2 0 1 Typing disciplineStatic dynamic weakOSCross platformFilename extensions h m mm MWebsitedeveloper apple comMajor implementationsClang GCCInfluenced byC SmalltalkInfluencedGroovy Java Nu Objective J TOM Swift 2 Objective C Programming at WikibooksObjective C programs developed for non Apple operating systems or that are not dependent on Apple s APIs may also be compiled for any platform supported by GNU GCC or LLVM Clang Objective C source code messaging implementation program files usually have m filename extensions while Objective C header interface files have h extensions the same as C header files Objective C files are denoted with a mm file extension Contents 1 History 1 1 Popularization through NeXT 1 2 Apple development and Swift 2 Syntax 2 1 Messages 2 2 Interfaces and implementations 2 2 1 Interface 2 2 2 Implementation 2 2 3 Instantiation 2 3 Protocols 2 4 Dynamic typing 2 5 Forwarding 2 5 1 Example 2 5 2 Notes 2 6 Categories 2 6 1 Example use of categories 2 6 2 Notes 2 7 Posing 2 8 import 2 9 Linux gcc compilation 3 Other features 4 Language variants 4 1 Objective C 4 2 Objective C 2 0 4 2 1 Garbage collection 4 2 2 Properties 4 2 3 Non fragile instance variables 4 2 4 Fast enumeration 4 2 5 Class extensions 4 2 6 Implications for Cocoa development 4 3 Blocks 4 4 Modern Objective C 4 4 1 Automatic Reference Counting 4 4 2 Literals 4 4 3 Subscripting 4 5 Modern Objective C syntax 1997 4 6 mulle objc 4 7 Portable Object Compiler 4 8 GEOS Objective C 4 9 Clang 4 10 GNU GNUstep and WinObjC 5 Library use 6 Analysis of the language 6 1 Memory management 6 2 Philosophical differences between Objective C and C 7 See also 8 References 9 Further reading 10 External linksHistory EditObjective C was created primarily by Brad Cox and Tom Love in the early 1980s at their company Productivity Products International PPI 5 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 6 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 7 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 8 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 Edit 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 9 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 10 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 citation needed Thorup also worked at NeXT from 1993 to 1996 11 Apple development and Swift Edit 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 EditObjective 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 12 13 14 15 16 17 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 Edit 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 SEL a unique identifier for each message name often just a NUL terminated string representing its name and resolved to a C method pointer implementing it an IMP 18 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 19 Sending the message method to the object pointed to by the pointer obj would require the following code in C obj gt method argument In Objective C this is written as follows obj method argument The method call is translated by the compiler to the objc msgSend id self SEL op family of runtime functions Different implementations handle modern additions like super 20 In GNU families this function is named objc msg sendv but it has been deprecated in favor of a modern lookup system under objc msg lookup 21 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 Edit 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 Edit 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 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 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 instanceMethod2With2Parameters param2 callName 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 id 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 22 Implementation Edit 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 23 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 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 Edit 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 init can return a different object than that on which it is called Instantiation with the default no parameter initializer MyObject foo MyObject alloc init Instantiation with a custom initializer MyObject foo MyObject alloc initWithString myString In the case where no custom initialization is being performed the new method can often be used in place of the alloc init messages MyObject foo MyObject new Also some classes implement class method initializers Like new they combine alloc and init but unlike new they return an autoreleased instance Some class method initializers take parameters MyObject foo MyObject object MyObject bar MyObject objectWithString Wikipedia The alloc message allocates enough memory to hold all the instance variables for an object sets all the instance variables to zero values and turns the memory into an instance of the class at no point during the initialization is the memory an instance of the superclass The init message performs the set up of the instance upon creation The init method is often written as follows id init self super init if self perform initialization of object here return self In the above example notice the id return type This type stands for pointer to any object in Objective C See the Dynamic typing section The initializer pattern is used to assure that the object is properly initialized by its superclass before the init method performs its initialization It performs the following actions Line 2 Sends the superclass instance an init message and assigns the result to self pointer to the current object Line 3 Checks if the returned object pointer is valid before performing any initialization Line 6 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 designated initializer needs to follow this pattern others should call the designated initializer instead of the superclass initializer Protocols Edit In other programming languages these are called interfaces Objective C was extended at NeXT to introduce the concept of multiple inheritance of specification but not implementation through the introduction of protocols This is a pattern achievable either as an abstract multiple inherited base class in C or as an interface as in Java and C Objective C makes use of ad hoc protocols called informal protocols and compiler enforced protocols called formal protocols An informal protocol is a list of methods that a class can opt to implement It is specified in the documentation since it has no presence in the language Informal protocols are implemented as a category see below on NSObject and often include optional methods which if implemented can change the behavior of a class For example a text field class might have a delegate that implements an informal protocol with an optional method for performing auto completion of user typed text The text field discovers whether the delegate implements that method via reflection and if so calls the delegate s method to support the auto complete feature A formal protocol is similar to an interface in Java C and Ada 2005 It is a list of methods that any class can declare itself to implement Versions of Objective C before 2 0 required that a class must implement all methods in a protocol it declares itself as adopting the compiler will emit an error if the class does not implement every method from its declared protocols Objective C 2 0 added support for marking certain methods in a protocol optional and the compiler will not enforce implementation of optional methods A class must be declared to implement that protocol to be said to conform to it This is detectable at runtime Formal protocols cannot provide any implementations they simply assure callers that classes that conform to the protocol will provide implementations In the NeXT Apple library protocols are frequently used by the Distributed Objects system to represent the abilities of an object executing on a remote system The syntax protocol NSLocking void lock void unlock end denotes that there is the abstract idea of locking By stating in the class definition that the protocol is implemented interface NSLock NSObject lt NSLocking gt end instances of NSLock claim that they will provide an implementation for the two instance methods Dynamic typing Edit Objective C like Smalltalk can use dynamic typing an object can be sent a message that is not specified in its interface This can allow for increased flexibility as it allows an object to capture a message and send the message to a different object that can respond to the message appropriately or likewise send the message on to another object This behavior is known as message forwarding or delegation see below Alternatively an error handler can be used in case the message cannot be forwarded If an object does not forward a message respond to it or handle an error then the system will generate a runtime exception 24 If messages are sent to nil the null object pointer they will be silently ignored or raise a generic exception depending on compiler options Static typing information may also optionally be added to variables This information is then checked at compile time In the following four statements increasingly specific type information is provided The statements are equivalent at runtime but the extra information allows the compiler to warn the programmer if the passed argument does not match the type specified void setMyValue id foo In the above statement foo may be of any class void setMyValue id lt NSCopying gt foo In the above statement foo may be an instance of any class that conforms to the NSCopying protocol void setMyValue NSNumber foo In the above statement foo must be an instance of the NSNumber class void setMyValue NSNumber lt NSCopying gt foo In the above statement foo must be an instance of the NSNumber class and it must conform to the NSCopying protocol In Objective C all objects are represented as pointers and static initialization is not allowed The simplest object is the type that id objc obj points to which only has an isa pointer describing its class Other types from C like values and structs are unchanged because they are not part of the object system This decision differs from the C object model where structs and classes are united Forwarding Edit Objective C permits the sending of a message to an object that may not respond Rather than responding or simply dropping the message an object can forward the message to an object that can respond Forwarding can be used to simplify implementation of certain design patterns such as the observer pattern or the proxy pattern The Objective C runtime specifies a pair of methods in Object forwarding methods retval t forward SEL sel args arglist t args with GCC id forward SEL sel args marg list args with NeXT Apple systems action methods retval t performv SEL sel args arglist t args with GCC id performv SEL sel args marg list args with NeXT Apple systemsAn object wishing to implement forwarding needs only to override the forwarding method with a new method to define the forwarding behavior The action method performv need not be overridden as this method merely performs an action based on the selector and arguments Notice the SEL type which is the type of messages in Objective C Note in OpenStep Cocoa and GNUstep the commonly used frameworks of Objective C one does not use the Object class The span class p span span class p span span class kt void span span class p span span class nf forwardInvocation span span class p span span class bp NSInvocation span span class w span span class o span span class p span span class nv anInvocation span span class w span method of the NSObject class is used to do forwarding Example Edit Here is an example of a program that demonstrates the basics of forwarding Forwarder h import lt objc Object h gt interface Forwarder Object id recipient The object we want to forward the message to Accessor methods id recipient id setRecipient id recipient end Forwarder m import Forwarder h implementation Forwarder retval t forward SEL sel args arglist t args Check whether the recipient actually responds to the message This may or may not be desirable for example if a recipient in turn does not respond to the message it might do forwarding itself if recipient respondsToSelector sel return recipient performv sel args args else return self error Recipient does not respond id setRecipient id recipient recipient autorelease recipient recipient retain return self id recipient return recipient end Recipient h import lt objc Object h gt A simple Recipient object interface Recipient Object id hello end Recipient m import Recipient h implementation Recipient id hello printf Recipient says hello n return self end main m import Forwarder h import Recipient h int main void Forwarder forwarder Forwarder new Recipient recipient Recipient new forwarder setRecipient recipient Set the recipient Observe forwarder does not respond to a hello message It will be forwarded All unrecognized methods will be forwarded to the recipient if the recipient responds to them as written in the Forwarder forwarder hello recipient release forwarder release return 0 Notes Edit When compiled using gcc the compiler reports gcc x objective c Wno import Forwarder m Recipient m main m lobjc main m In function main main m 12 warning Forwarder does not respond to hello The compiler is reporting the point made earlier that Forwarder does not respond to hello messages In this circumstance it is safe to ignore the warning since forwarding was implemented Running the program produces this output a out Recipient says hello Categories Edit During the design of Objective C one of the main concerns was the maintainability of large code bases Experience from the structured programming world had shown that one of the main ways to improve code was to break it down into smaller pieces Objective C borrowed and extended the concept of categories from Smalltalk implementations to help with this process 25 Furthermore the methods within a category are added to a class at run time Thus categories permit the programmer to add methods to an existing class an open class without the need to recompile that class or even have access to its source code For example if a system does not contain a spell checker in its String implementation it could be added without modifying the String source code Methods within categories become indistinguishable from the methods in a class when the program is run A category has full access to all of the instance variables within the class including private variables If a category declares a method with the same method signature as an existing method in a class the category s method is adopted Thus categories can not only add methods to a class but also replace existing methods This feature can be used to fix bugs in other classes by rewriting their methods or to cause a global change to a class s behavior within a program If two categories have methods with the same name but different method signatures it is undefined which category s method is adopted Other languages have attempted to add this feature in a variety of ways TOM took the Objective C system a step further and allowed for the addition of variables also Other languages have used prototype based solutions instead the most notable being Self The C and Visual Basic NET languages implement superficially similar functionality in the form of extension methods but these lack access to the private variables of the class 26 Ruby and several other dynamic programming languages refer to the technique as monkey patching Logtalk implements a concept of categories as first class entities that subsumes Objective C categories functionality Logtalk categories can also be used as fine grained units of composition when defining e g new classes or prototypes in particular a Logtalk category can be virtually imported by any number of classes and prototypes Example use of categories Edit This example builds up an Integer class by defining first a basic class with only accessor methods implemented and adding two categories Arithmetic and Display which extend the basic class While categories can access the base class s private data members it is often good practice to access these private data members through the accessor methods which helps keep categories more independent from the base class Implementing such accessors is one typical use of categories Another is to use categories to add methods to the base class However it is not regarded as good practice to use categories for subclass overriding also known as monkey patching Informal protocols are implemented as a category on the base NSObject class By convention files containing categories that extend base classes will take the name BaseClass ExtensionClass h Integer h import lt objc Object h gt interface Integer Object int integer int integer id integer int integer endInteger m import Integer h implementation Integer int integer return integer id integer int integer integer integer return self endInteger Arithmetic h import Integer h interface Integer Arithmetic id add Integer addend id sub Integer subtrahend endInteger Arithmetic m import Integer Arithmetic h implementation Integer Arithmetic id add Integer addend return self integer self integer addend integer id sub Integer subtrahend return self integer self integer subtrahend integer endInteger Display h import Integer h interface Integer Display id showstars id showint endInteger Display m import Integer Display h implementation Integer Display id showstars int i x self integer for i 0 i lt x i printf printf n return self id showint printf d n self integer return self endmain m import Integer h import Integer Arithmetic h import Integer Display h int main void Integer num1 Integer new num2 Integer new int x printf Enter an integer scanf d amp x num1 integer x num1 showstars printf Enter an integer scanf d amp x num2 integer x num2 showstars num1 add num2 num1 showint return 0 Notes Edit 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 span class cp import Integer Arithmetic h span line 2 and span class p span span class n num1 span span class w span span class n add span span class o span span class n num2 span span class p span span class w span line 21 and omitting Integer Arithmetic m 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 Edit 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 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 import Edit 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 import directive equivalent except that each file is included only once per compilation unit obviating the need for include guards Linux gcc compilation Edit FILE hello m import lt Foundation Foundation h gt int main int argc const char argv my first program in Objective C NSLog Hello World n return 0 Compile Command Line for gcc and MinGW Compiler gcc gnustep config objc flags o hello hello m L GNUstep System Library Libraries lobjc lgnustep base helloOther features EditObjective C s features often allow for flexible and often easy solutions to programming issues Delegating methods to other objects and remote invocation can be easily implemented using categories and message forwarding Swizzling of the isa pointer allows for classes to change at runtime Typically used for debugging 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 to create database faults citation needed Swizzling is used today by Apple s Foundation Framework to implement Key Value Observing Language variants EditObjective C Edit 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 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 lack a default constructor or that have one or more virtual methods citation needed 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 As a result object destructors are not run This is mitigated in recent Objective C 2 0 runtimes as Objective C exceptions are either replaced by C exceptions completely Apple runtime or partly when Objective C library is linked GNUstep libobjc2 27 Objective C blocks and C 11 lambdas are distinct entities However a block is transparently generated on macOS when passing a lambda where a block is expected 28 Objective C 2 0 Edit 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 29 runtime performance improvements 30 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 31 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 32 This project name was kept in the last release of legacy Objective C runtime source code in Mac OS X Leopard 10 5 33 Garbage collection Edit 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 34 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 35 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 36 Garbage collection was deprecated in Mac OS X v10 8 in favor of Automatic Reference Counting ARC 37 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 38 39 Properties Edit 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 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 When compiled using clang 3 1 or higher all properties which are not explicitly declared with dynamic marked readonly or have complete user implemented getter and setter will be automatically implicitly synthesize 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 gt 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 int i int propertyCount 0 objc property t propertyList class copyPropertyList aPerson class amp propertyCount for i 0 i lt 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 Edit 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 It eliminates the fragile binary interface problem superclasses can change sizes without affecting binary compatibility It allows instance variables that provide the backing for properties to be synthesized at runtime without them being declared in the class s interface Fast enumeration Edit 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 lt 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 40 Class extensions Edit 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 41 Implications for Cocoa development Edit This section does not cite any sources Please help improve this section by adding citations to reliable sources Unsourced material may be challenged and removed November 2012 Learn how and when to remove this template message 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 Edit Main article Blocks C language extension Blocks is a nonstandard extension for Objective C and C and C that uses special syntax to create closures Blocks are only supported in 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 42 include lt stdio h gt include lt Block h gt 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 Edit 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 Xcode Toolchain versions for a translation to open source LLVM version numbers 43 Automatic Reference Counting Edit Main article Automatic Reference Counting Automatic Reference Counting ARC is a compile time feature that eliminates the need for programmers to manually manage retain counts using retain and release 44 Unlike 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 45 Literals Edit NeXT and Apple Obj C runtimes have long included a short form way to create new strings using the literal syntax a new string or drop to CoreFoundation constants kCFBooleanTrue and kCFBooleanFalse for NSNumber with Boolean values Using this format saves the programmer from having to use the longer initWithString or similar methods when doing certain operations When using Apple LLVM compiler 4 0 Xcode 4 4 or later arrays dictionaries and numbers NSArray NSDictionary NSNumber classes can also be created using literal syntax instead of methods 46 Apple LLVM compiler 4 0 translates to open source LLVM and Clang 3 1 47 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 literals 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 Edit When using Apple LLVM compiler 4 0 or later arrays and dictionaries NSArray and NSDictionary classes can be manipulated using subscripting 46 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 48 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 Edit After the purchase of NeXT by Apple attempts were made to make the language more acceptable to programmers more familiar with Java than Smalltalk One of these attempts was introducing what was dubbed Modern Syntax for Objective C at the time 49 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 Edit The mulle objc project is another re implementation of Objective C It supports 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 Edit Besides the GCC NeXT Apple implementation which added several extensions to the original Stepstone implementation another free open source Objective C implementation called the Portable Object Compiler also exists 50 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 Edit The PC GEOS system used a programming language known as GEOS Objective C or goc 51 despite the name similarity the two languages are similar only in overall concept and the use of keywords prefixed with an sign Clang Edit 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 Xcode Toolchain versions for a translation 43 GNU GNUstep and WinObjC Edit 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 libobjc 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 52 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 when 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 32 Which compiler The GNUstep developers interested in the new language forked the GCC libobjc to a project independent of GCC called libobjc2 in 2009 They also arranged for the runtime to be used with Clang to take advantage of the new language syntax 32 Which compiler 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 31 53 GNUstep documentation suggest that the GCC implementation still lacks support for blocks non fragile variables and the newer ARC 32 Which runtime Microsoft forked libobjc2 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 54 On Windows Objective C Development tools are provided for download on GNUStep s website The GNUStep Development System consists of the following packages GNUstep 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 55 so it could be a better idea to just install by building under Cygwin or MSYS2 instead Library use EditObjective C today is often used in tandem with a fixed library of standard objects often known as a kit or framework such as 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 EditThis section needs additional citations for verification Please help improve this article by adding citations to reliable sources Unsourced material may be challenged and removed December 2011 Learn how and when to remove this template message Objective C implementations use a thin runtime system written in C citation needed 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 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 wrappers to provide an OO style interface In this aspect it is similar to GObject library and Vala language which are widely used in development of GTK applications All of these practical changes lowered the 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 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 objects 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 Edit The first versions of Objective C did not support 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 and Apple has implemented it as of Mac OS X v10 5 56 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 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 57 Philosophical differences between Objective C and C Edit 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 a large standard library that includes several container classes Similarly Objective C adds object oriented programming dynamic typing and 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 or GNUstep which provides functionality similar to C s standard library One notable difference is that Objective C provides runtime support for 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 functions and runtime type identification while Objective C offers dynamic typing and reflection Both Objective C and C support compile time polymorphism generic functions with Objective C only adding this feature in 2015 See also EditC programming language C Comparison of programming languages Comparison with COM GObject SOM Windows Runtime XPCOM Swift programming language Xcode WinObjC aka Windows Bridge for iOS References Edit Runtime Versions and Platforms Developer apple com Archived from the original on July 20 2016 Retrieved December 24 2017 Lattner Chris June 3 2014 Chris Lattner s Homepage Chris Lattner Archived from the original on June 4 2014 Retrieved June 3 2014 The Swift language is the product of tireless effort from a team of language experts documentation gurus compiler optimization ninjas and an incredibly important internal dogfooding group who provided feedback to help refine and battle test ideas Of course it also greatly benefited from the experiences hard won by many other languages in the field drawing ideas from Objective C Rust Haskell Ruby Python C CLU and far too many others to list a b App Frameworks Apple June 2014 Archived from the original on February 16 2019 Retrieved February 13 2019 Singh Amit December 2003 A Brief History of Mac OS X Mac OS X Internals Archived from the original on May 14 2012 Retrieved June 11 2012 Garling Caleb iPhone Coding Language Now World s Third Most Popular Wired Archived from the original on September 9 2013 Retrieved May 20 2013 Wentk Richard 2009 Cocoa Volume 5 of Developer Reference Apple Developer Series John Wiley and Sons ISBN 978 0 470 49589 6 Archived from the original on February 16 2017 Retrieved July 22 2016 Biancuzzi Federico Warden Shane 2009 Masterminds of Programming O Reilly Media Inc pp 242 246 ISBN 978 0 596 51517 1 Archived from the original on February 17 2017 Retrieved July 22 2016 Cox Brad 1983 The object oriented pre compiler programming Smalltalk 80 methods in C language ACM SIGPLAN Notices New York NY ACM 18 1 doi 10 1145 948093 948095 S2CID 6975032 Retrieved February 17 2011 Common Lisp and Readline GitHub Archived from the original on September 6 2014 Retrieved September 15 2014 The issue first arose when NeXT proposed to distribute a modified GCC in two parts and let the user link them Jobs asked me whether this was lawful It seemed to me at the time that it was following reasoning like what you are using but since the result was very undesirable for free software I said I would have to ask the lawyer What the lawyer said surprised me he said that judges would consider such schemes to be subterfuges and would be very harsh toward them He said a judge would ask whether it is really one program rather than how it is labeled So I went back to Jobs and said we believed his plan was not allowed by the GPL The direct result of this is that we now have an Objective C front end They had wanted to distribute the Objective C parser as a separate proprietary package to link with the GCC back end but since I didn t agree this was allowed they made it free GNUstep Introduction GNUstep developers GNU Project Archived from the original on August 6 2012 Retrieved July 29 2012 Kresten Krab Thorup LinkedIn www linkedin com Archived from the original on July 15 2014 Retrieved June 23 2016 Write Objective C Code apple com April 23 2013 Archived from the original on December 24 2013 Retrieved December 22 2013 Objective C Boot Camp Archived from the original on February 11 2018 Retrieved February 11 2018 Objective C is a strict superset of ANSI C Examining Objective C Archived from the original on September 4 2014 Retrieved September 4 2014 Objective C is an object oriented strict superset of C Lee Keith September 3 2013 Pro Objective C Apress ISBN 9781430250500 Archived from the original on May 14 2018 Retrieved December 24 2017 via Google Books Tags for Objective C Headers Archived from the original on April 1 2017 Retrieved February 11 2018 Objective C is a superset of C AppScan Source 8 7 now available Archived from the original on February 3 2017 Retrieved February 11 2018 The Objective C programming language is a superset of the C programming language Apple Inc October 19 2009 Dynamic Method Resolution Objective C Runtime Programming Guide Archived from the original on September 7 2010 Retrieved November 25 2014 Apple Inc October 19 2009 Avoiding Messaging Errors The Objective C Programming Language Archived from the original on September 8 2010 objc msgSend Objective C Runtime Apple Developer Documentation Retrieved February 10 2020 Messaging with the GNU Objective C runtime Using the GNU Compiler Collection GCC Retrieved February 10 2020 Category Apple Developer Cocoa Core Competencies Dalrymple Mark Knaster Scott June 27 2012 Learn Objective C on the Mac p 9 ISBN 9781430241881 The m extension originally stood for messages when Objective C was first introduced referring to a central feature of Objective C Objective C Runtime Programming Guide Apple Inc Archived from the original on April 4 2014 Retrieved October 21 2013 ACM SIGGRAPH 1983 Issue 8 Smalltalk Archived from the original on 15 April 2009 Retrieved 7 October 2008 Extension Methods C Programming Guide Microsoft October 2010 Archived from the original on July 11 2011 Retrieved July 10 2011 Using C With Objective C Mac OS X Reference Library Archived from the original on September 5 2010 Retrieved February 10 2010 Clang Language Extensions Clang 3 5 documentation Clang llvm org Archived from the original on February 24 2014 Retrieved April 16 2014 Objective C 2 0 more clues Lists apple com August 10 2006 Archived from the original on June 18 2009 Retrieved May 30 2010 Re Objective C 2 0 Lists apple com Archived from the original on November 24 2010 Retrieved May 30 2010 a b GCC 4 6 Release Series Changes New Features and Fixes GNU Project Free Software Foundation Gcc gnu org Archived from the original on January 5 2018 Retrieved December 24 2017 a b c d ObjC2 FAQ GNUstep Retrieved January 6 2020 Source Browser objc4 756 2 Apple Open Source Retrieved January 6 2020 Garbage Collection Programming Guide Garbage Collection API Archived June 9 2012 at the Wayback Machine Apple developer website search for strong Garbage Collection Programming Guide Introduction to Garbage Collection Apple Inc October 3 2011 Archived from the original on June 9 2012 Retrieved December 23 2011 Leopard Technology Series for Developers Objective C 2 0 Overview Apple Inc November 6 2007 Archived from the original on July 24 2010 Retrieved May 30 2010 Transitioning to ARC Release Notes Apple Inc July 17 2012 Archived from the original on June 9 2012 Retrieved August 26 2012 Mike Ash Friday Q amp A 2013 09 27 ARM64 and You mikeash com Archived from the original on April 26 2014 Retrieved April 27 2014 Hamster Emporium objc explain Non pointer isa Sealiesoftware com September 24 2013 Archived from the original on June 3 2014 Retrieved April 27 2014 Apple Inc 2009 Fast Enumeration apple com Archived from the original on December 17 2009 Retrieved December 31 2009 Free Software Foundation Inc 2011 GCC 4 6 Release Series Changes New Features and Fixes Gcc gnu org Archived from the original on December 2 2013 Retrieved November 27 2013 Blocks Programming Topics Mac Developer Library Apple Inc March 8 2011 Archived from the original on June 9 2012 Retrieved November 28 2012 a b Objective C Automatic Reference Counting ARC Clang 11 documentation Clang documentation Retrieved February 20 2020 For now it is sensible to version this document by the releases of its sole implementation and its host project clang LLVM X Y refers to an open source release of clang from the LLVM project Apple X Y refers to an Apple provided release of the Apple LLVM Compiler Transitioning to ARC Apple Inc Archived from the original on September 7 2011 Retrieved October 8 2012 LLVM 3 0 Release Notes releases llvm org a b Programming with Objective C Values and Collections Apple Inc Archived from the original on September 7 2011 Retrieved October 8 2012 Clang 3 1 Release Notes releases llvm org Objective C Literals Clang 3 5 documentation Clang llvm org Archived from the original on June 6 2014 Retrieved April 16 2014 Rhapsody Developer s Guide AP Professional 1997 pp 76 84 Portable Object Compiler Users pandora be January 1 1970 Archived from the original on August 2 2008 Retrieved May 30 2010 Breadbox Computer Company LLC homepage Archived from the original on July 27 2011 Retrieved December 8 2010 gcc libobjc GitHub gcc mirror January 6 2020 Retrieved January 6 2020 he runtime has been completely rewritten in gcc 2 4 The earlier runtime had several severe bugs and was rather incomplete GNU Objective C runtime API Using GCC Retrieved January 6 2020 WinObjC on GitHub GitHub Archived from the original on December 2 2017 Retrieved February 13 2018 GNUStep Installer Archived from the original on February 17 2018 Retrieved February 14 2018 Apple Inc August 22 2006 Mac OS X Leopard Xcode 3 0 apple com Archived from the original on October 24 2007 Retrieved August 22 2006 Transitioning to ARC Release Notes iOS Developer Library Developer apple com Archived from the original on September 7 2011 Retrieved April 16 2014 Further reading EditCox Brad J 1991 Object Oriented Programming An Evolutionary Approach Addison Wesley ISBN 0 201 54834 8 External links Edit Wikibooks has a book on the topic of Objective C Programming Programming with Objective C from Apple 2012 12 13 The Objective C Programming Language from Apple 2011 10 11 Objective C Runtime Programming Guide from Apple 2009 10 19 Objective C GNUstep Base Programming Manual Objective C by Brad Cox Objective C FAQ Retrieved from https en wikipedia org w index php title Objective C amp oldid 1140300996, wikipedia, wiki, book, books, library,

article

, read, download, free, free download, mp3, video, mp4, 3gp, jpg, jpeg, gif, png, picture, music, song, movie, book, game, games.