History
Objective-C was created primarily by Brad Cox and Tom Love in the early 1980s at their company Productivity Products International (PPI). Leading up to the creation of their company, both had been introduced to Smalltalk while atPopularization through NeXT
In 1988,Apple development and Swift
After acquiring NeXT in 1996,Syntax
Objective-C is a thin layer atop C and is a "strict superset" of C, meaning that it is possible to compile any C program with an Objective-C compiler and to freely include C language code within an Objective-C class. Objective-C derives its object syntax from Smalltalk. All of the syntax for non-object-oriented operations (including primitive variables, pre-processing, expressions, function declarations, and function calls) are identical to those of C, while the syntax for object-oriented features is an implementation of Smalltalk-style messaging.Messages
The Objective-C model of object-oriented programming is based onInterfaces and implementations
Objective-C requires that the interface and implementation of a class be in separately declared code blocks. By convention, developers place the interface in a header file and the implementation in a code file. The header files, normally suffixed .h, are similar to C header files while the implementation (method) files, normally suffixed .m, can be very similar to C code files.Interface
This is analogous to class declarations as used in other object-oriented languages, such as C++ or Python. The interface of a class is usually defined in a header file. A common convention is to name the header file after the name of the class, e.g. would contain the interface for the class . An interface declaration takes the form: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".
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:
+new
, they combine +alloc
and -init
, but unlike +new
, they return an autoreleased instance. Some class method initializers take parameters:
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 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 atDynamic 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. 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.NSCopying
'' protocol.
NSCopying
'' protocol.
In Objective-C, all objects are represented as pointers, and static initialization is not allowed. The simplest object is the type that () 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 certainSEL
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 class. The method of the class is used to do forwarding.
Example
Here is an example of a program that demonstrates the basics of forwarding. ; ''Forwarder.h''Notes
When compiled using gcc, the compiler reports: The compiler is reporting the point made earlier, that 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: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. 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 beingExample use of categories
This example builds up an class, by defining first a basic class with only accessor methods implemented, and adding two categories, and , 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 class. By convention, files containing categories that extend base classes will take the name BaseClass+ExtensionClass.h. ; ''Integer.h'' :Notes
Compilation is performed, for example, by: One can experiment by leaving out the (line 2) and (line 21) and omitting in compilation. The program will still run. This means that it is possible to ''mix-and-match'' added categories if needed; if a category does not need to have some ability, it can simply not be compile in.Posing
Objective-C permits a class to wholly replace another class within a program. The replacing class is said to "pose as" the target class. Class posing was declared deprecated with Mac OS X v10.5, and is unavailable in the 64-bit runtime. Similar functionality can be achieved by using method swizzling in categories, that swaps one method's implementation with another's that have the same signature. For the versions still supporting posing, all messages sent to the target class are instead received by the posing class. There are several restrictions: * 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,#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
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 forLanguage variants
Objective-C++
Objective-C++ is a language variant accepted by the front-end to theObjective-C 2.0
At the 2006 Worldwide Developers Conference, Apple announced the release of "Objective-C 2.0," a revision of the Objective-C language to include "modern garbage collection, syntax enhancements, runtime performance improvements, and 64-bit support". Mac OS X v10.5, released in October 2007, included an Objective-C 2.0 compiler. GCC 4.6 supports many new Objective-C features, such as declared and synthesized properties, dot syntax, fast enumeration, optional protocol methods, method/protocol/class attributes, class extensions, and a new GNU Objective-C runtime API. The naming Objective-C 2.0 represents a break in the versioning system of the language, as the last Objective-C version for NeXT was "objc4". This project name was kept in the last release of legacy Objective-C runtime source code in Mac OS X Leopard (10.5).Garbage collection
Objective-C 2.0 provided an optional conservative, generationalProperties
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 asassign
, 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.
@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.
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 theFast 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.Class extensions
A class extension has the same syntax as a category declaration with no category name, and the methods and properties declared in it are added directly to the main class. It is mostly used as an alternative to a category to add methods to a class without advertising them in the public headers, with the advantage that for class extensions the compiler checks that all the privately declared methods are actually implemented.Implications for Cocoa development
All Objective-C applications developed for macOS that make use of the above improvements for Objective-C 2.0 are incompatible with all operating systems prior to 10.5 (Leopard). Since fast enumeration does not generate exactly the same binaries as standard enumeration, its use will cause an application to crash on Mac OS X version 10.4 or earlier.Blocks
Blocks is a nonstandard extension for Objective-C (and C 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.Modern Objective-C
Apple has added some additional features to Objective 2.0 over time. The additions only apply to the "AppleAutomatic Reference Counting
Automatic Reference Counting (ARC) is a compile-time feature that eliminates the need for programmers to manually manage retain counts usingretain
and release
. Unlike 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 NSArray
, NSDictionary
, NSNumber
classes) can also be created using literal syntax instead of methods. (Apple LLVM compiler 4.0 translates to open source LLVM and Clang 3.1.)
Example without literals:
Subscripting
When using AppleNSArray
and NSDictionary
classes) can be manipulated using subscripting. Subscripting can be used to retrieve values from indexes (array) or keys (dictionary), and with mutable objects, can also be used to set objects to indexes or keys. In code, subscripting is represented using brackets /code>.
Example without subscripting:
id object1 = omeArray objectAtIndex:0
id object2 = omeDictionary objectForKey:@"key"
omeMutableArray replaceObjectAtIndex:0 withObject:object3
omeMutableDictionary setObject:object4 forKey:@"key"
Example with subscripting:
id object1 = someArray
id object2 = someDictionary "key"
someMutableArray = 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
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
than Smalltalk. One of these attempts was introducing what was dubbed "Modern Syntax" for Objective-C at the time (as opposed to the current, "classic" syntax). There was no change in behaviour, this was merely an alternative syntax. Instead of writing a method invocation like
object = MyClass allocinit];
bject 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
Th
mulle-objc
project is another re-implementation of Objective-C. It supports GCC or Clang/LLVM
LLVM is a set of compiler and toolchain technologies that can be used to develop a front end for any programming language and a back end for any instruction set architecture. LLVM is designed around a language-independent intermediate repre ...
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
Next may refer to:
Arts and entertainment Film
* ''Next'' (1990 film), an animated short about William Shakespeare
* ''Next'' (2007 film), a sci-fi film starring Nicolas Cage
* '' Next: A Primer on Urban Painting'', a 2005 documentary film
Lit ...
/Apple
An apple is an edible fruit produced by an apple tree (''Malus domestica''). Apple trees are cultivated worldwide and are the most widely grown species in the genus '' Malus''. The tree originated in Central Asia, where its wild ancest ...
implementation, which added several extensions to the original Stepstone
Next may refer to:
Arts and entertainment Film
* ''Next'' (1990 film), an animated short about William Shakespeare
* ''Next'' (2007 film), a sci-fi film starring Nicolas Cage
* '' Next: A Primer on Urban Painting'', a 2005 documentary film
Lit ...
implementation, another free, open-source Objective-C implementation called the Portable Object Compiler also exists. The set of extensions implemented by the Portable Object Compiler differs from the GCC/NeXT/Apple implementation; in particular, it includes Smalltalk-like blocks for Objective-C, while it lacks protocols and categories, two features used extensively in OpenStep and its derivatives and relatives. Overall, POC represents an older, pre-NeXT stage in the language's evolution, roughly conformant to Brad Cox's 1991 book.
It also includes a runtime library called ObjectPak, which is based on Cox's original ICPak101 library (which in turn derives from the Smalltalk-80 class library), and is quite radically different from the OpenStep FoundationKit.
GEOS Objective-C
The PC GEOS system used a programming language known as GEOS Objective-C or goc; despite the name similarity, the two languages are similar only in overall concept and the use of keywords prefixed with an @ sign.
Clang
The Clang compiler suite, part of the LLVM
LLVM is a set of compiler and toolchain technologies that can be used to develop a front end for any programming language and a back end for any instruction set architecture. LLVM is designed around a language-independent intermediate repre ...
project, implements Objective-C and other languages. After GCC 4.3 (2008) switched to GPLv3, Apple abandoned it in favor of clang, a compiler it has more legal power to modify. As a result, many of the modern Objective-C language features are supported only by Clang.
Apple's versioning scheme for its clang-based "LLVM compiler" differs from the LLVM's open-source versioning. See for a translation
GNU, GNUstep, and WinObjC
The GNU project has, for a long time, been interested in a platform to port NeXT and Obj-C programs to. The ChangeLog for the directory in GCC suggests that it existed before 1998 (GCC 2.95), and its README further points at a rewrite in 1993 (GCC 2.4).
The NeXT frontend source code was released since it was made as part of GCC, released GNU Public License which forces ones making derivative works to do so. Apple continued this tradition in releasing its fork of GCC up to 4.2.1, after which they abandoned the compiler. GCC maintainers took in the changes, but did not invest much in supporting newer features such as the Objective-C 2.0 language.
The GNUstep developers, interested in the new language, forked the GCC to a project independent of GCC called in 2009. They also arranged for the runtime to be used with Clang to take advantage of the new language syntax. GCC moved slowly at the same time, but at GCC 4.6.0 (2011) they have moved on to Objective-C 2.0 in their libobjc as well. GNUstep documentation suggest that the GCC implementation still lacks support for blocks, non-fragile variables, and the newer ARC.
Microsoft
Microsoft Corporation is an American multinational technology corporation producing computer software, consumer electronics, personal computers, and related services headquartered at the Microsoft Redmond campus located in Redmond, Washi ...
forked into a part of WinObjC, the iOS bridge for Universal Windows Platform, in 2015. Combined with its own implementation of Cocoa Touch
Cocoa Touch is the application development environment for building software programs to run on iOS for the iPhone and iPod Touch, iPadOS for the iPad, watchOS for the Apple Watch, and tvOS for the Apple TV, from Apple Inc.
Cocoa Touch ...
and underlying APIs, the project allows the reuse of iOS Application code inside of UWP apps.
On Windows, Objective-C Development tools are provided for download on GNUStep's website. The GNUStep Development System consists of the following packages: GNUstep MSYS System, GNUstep Core, GNUstep Devel, GNUstep Cairo, ProjectCenter IDE (Like Xcode, but not as complex), Gorm (Interface Builder Like Xcode NIB builder). These binary installers have not been updated since 2016, so it could be a better idea to just install by building under Cygwin
Cygwin ( ) is a POSIX-compatible programming and runtime environment that runs natively on Microsoft Windows. Under Cygwin, source code designed for Unix-like operating systems may be compiled with minimal modification and executed.
The Cygwin in ...
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
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter an ...
, GNUstep or ObjFW. These libraries often come with the operating system: the GNUstep libraries often come with Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, whi ...
-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
CocoaPods is an application level dependency manager for Objective-C, Swift and any other languages that run on the Objective-C runtime, such as RubyMotion, that provides a standard format for managing external libraries. It was developed by Elo ...
, 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, 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
In computing, a virtual machine (VM) is the virtualization/ emulation of a computer system. Virtual machines are based on computer architectures and provide functionality of a physical computer. Their implementations may involve specialized h ...
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
The GLib Object System, or GObject, is a free software library providing a portable object system and transparent cross-language interoperability. GObject is designed for use both directly in C programs to provide object-oriented C-based APIs ...
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
In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.
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
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter an ...
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
NeXTSTEP is a discontinued object-oriented, multitasking operating system based on the Mach kernel and the UNIX-derived BSD. It was developed by NeXT Computer in the late 1980s and early 1990s and was initially used for its range of propri ...
.
Since Objective-C is a strict superset of C, it does not treat C primitive types as first-class object
In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include ...
s.
Unlike C++, Objective-C does not support operator overloading. Also unlike C++, Objective-C allows an object to directly inherit only from one class (forbidding multiple inheritance). However, in most cases, categories and protocols may be used as alternative ways to achieve the same results.
Because Objective-C uses dynamic runtime typing and because all method calls are function calls (or, in some cases, syscalls), many common performance optimizations cannot be applied to Objective-C methods (for example: inlining, constant propagation, interprocedural optimizations, and scalar replacement of aggregates). This limits the performance of Objective-C abstractions relative to similar abstractions in languages such as C++ where such optimizations are possible.
Memory management
The first versions of Objective-C did not support garbage collection
Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclabl ...
. 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
Boehm () is a German surname, transliterated from Böhm (literally: Bohemian, from Bohemia) or reflective of a spelling adopted by a given family before the introduction of the umlaut diacritic. It may refer to:
* Aleksandra Ziółkowska-Boehm (bo ...
), and Apple has implemented it as of Mac OS X v10.5. However, in more recent versions of macOS and iOS, garbage collection has been deprecated in favor of Automatic Reference Counting (ARC), introduced in 2011.
With ARC, the compiler inserts retain and release calls automatically into Objective-C code based on static code analysis. The automation relieves the programmer of having to write in memory management code. ARC also adds weak references to the Objective-C language.
Philosophical differences between Objective-C and C++
The design and implementation of C++ and Objective-C represent fundamentally different approaches to extending C.
In addition to C's style of procedural programming, C++ directly supports certain forms of object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, generic programming, and metaprogramming. C++ also comes with a large standard library that includes several container classes. Similarly, Objective-C adds object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, 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
OpenStep is a defunct object-oriented application programming interface (API) specification for a legacy object-oriented operating system, with the basic goal of offering a NeXTSTEP-like environment on non-NeXTSTEP operating systems. OpenStep wa ...
-like library such as OPENSTEP
OpenStep is a defunct object-oriented application programming interface (API) specification for a legacy object-oriented operating system, with the basic goal of offering a NeXTSTEP-like environment on non-NeXTSTEP operating systems. OpenStep wa ...
, Cocoa
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter an ...
, or GNUstep, which provides functionality similar to C++'s standard library.
One notable difference is that Objective-C provides runtime support for reflective
Reflection is the change in direction of a wavefront at an interface between two different media so that the wavefront returns into the medium from which it originated. Common examples include the reflection of light, sound and water waves. The ' ...
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 computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
. 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 function
In computer programming, a generic function is a function defined for polymorphism.
In statically typed languages
In statically typed languages (such as C++ and Java), the term ''generic functions'' refers to a mechanism for ''compile-time p ...
s), with Objective-C only adding this feature in 2015.
See also
* C (programming language)
C (''pronounced like the letter c'') is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities ...
* C++
* Comparison of programming languages
* Comparison with COM, GObject, SOM, Windows Runtime, XPCOM
* Swift (programming language)
* Xcode
Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
* WinObjC (aka: Windows Bridge for iOS)
References
Further reading
*
External links
Programming with Objective-C
from Apple (2012-12-13)
*
', from Apple (2011-10-11)
*
', from Apple (2009-10-19)
Objective-C by Brad Cox
Objective-C FAQ
{{DEFAULTSORT:Objective-C
C programming language family
Class-based programming languages
Dynamically typed programming languages
GNUstep
NeXT
Object-oriented programming languages
Programming languages created in 1986