Objective-C Programming Language
   HOME

TheInfoList



OR:

Objective-C is a
high-level High-level and low-level, as technical terms, are used to classify, describe and point to specific goals of a systematic operation; and are applied in a wide range of contexts, such as, for instance, in domains as widely varied as computer scienc ...
general-purpose,
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
that adds
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
-style
message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting ...
(messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by
NeXT NeXT, Inc. (later NeXT Computer, Inc. and NeXT Software, Inc.) was an American technology company headquartered in Redwood City, California that specialized in computer workstations for higher education and business markets, and later develope ...
for its
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, founded by Steve Jobs, in the late 1980s and early 1990s and was initially used for its ...
operating system An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs. Time-sharing operating systems scheduler (computing), schedule tasks for ...
. Due to
Apple An apple is a round, edible fruit produced by an apple tree (''Malus'' spp.). Fruit trees of the orchard or domestic apple (''Malus domestica''), the most widely grown in the genus, are agriculture, cultivated worldwide. The tree originated ...
macOS macOS, previously OS X and originally Mac OS X, is a Unix, Unix-based operating system developed and marketed by Apple Inc., Apple since 2001. It is the current operating system for Apple's Mac (computer), Mac computers. With ...
’s direct lineage from NeXTSTEP, Objective-C was the standard language used, supported, and promoted by Apple for developing
macOS macOS, previously OS X and originally Mac OS X, is a Unix, Unix-based operating system developed and marketed by Apple Inc., Apple since 2001. It is the current operating system for Apple's Mac (computer), Mac computers. With ...
and
iOS Ios, Io or Nio (, ; ; locally Nios, Νιός) is a Greek island in the Cyclades group in the Aegean Sea. Ios is a hilly island with cliffs down to the sea on most sides. It is situated halfway between Naxos and Santorini. It is about long an ...
applications (via their respective application programming interfaces (
API An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build ...
s),
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 and ...
and
Cocoa Touch UIKit is an application development environment and graphical user interface toolkit from Apple Inc. used to build apps for the iOS, iPadOS, watchOS, tvOS, and visionOS operating systems. UIKit provides an abstraction layer of iOS, the ...
) from 1997, when Apple purchased NeXT until the introduction of the
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIF ...
language in 2014. 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 Platform may refer to: Arts * Platform, an arts centre at The Bridge, Easterhouse, Glasgow * ''Platform'' (1993 film), a 1993 Bollywood action film * ''Platform'' (2000 film), a 2000 film by Jia Zhangke * '' The Platform'' (2019 film) * Pla ...
supported by
GNU GNU ( ) is an extensive collection of free software (394 packages ), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operating systems popu ...
GNU Compiler Collection The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
(GCC) or
LLVM LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
/
Clang Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
. Objective-C source code 'messaging/implementation' program files usually have filename extensions, while Objective-C 'header/interface' files have extensions, the same as C header files. Objective-C++ files are denoted with a filename extension.


History

Objective-C was created mainly by
Brad Cox Brad J. Cox (May 2, 1944 – January 2, 2021) was an American computer scientist who was known mostly for creating the Objective-C programming language with his business partner Tom Love and for his work in software engineering (specifically so ...
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 Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
while at
ITT Corporation ITT Inc., formerly ITT Corporation, is an American worldwide manufacturing company based in Stamford, Connecticut. The company produces specialty components for the aerospace, transportation, energy and industrial markets. ITT's three businesses ...
's Programming Technology Center in 1981. The earliest work on Objective-C traces back to around then. Cox was intrigued by problems of true reusability in
software design Software design is the process of conceptualizing how a software system will work before it is implemented or modified. Software design also refers to the direct result of the design process the concepts of how the software will work which co ...
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 In telecommunications and computing, backward compatibility (or backwards compatibility) is a property of an operating system, software, real-world product, or technology that allows for interoperability with an older legacy system, or with Input ...
with C was critically important in ITT's telecom engineering milieu. Cox began writing a pre-processor for C to add some of the abilities of
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
. He soon had a working implementation of an object-oriented extension to the C language, which he named Object-Oriented Pre-Compiler (OOPC). Love was hired by
Schlumberger Schlumberger (), doing business as SLB, is a global multinational oilfield services company. Founded in France in 1926, the company is now incorporated as Schlumberger NV in Willemstad, Curaçao, with principal executive offices in Houston ...
Research in 1982 and had the opportunity to acquire the first commercial copy of Smalltalk-80, which further influenced the development of their brainchild. To demonstrate that real progress could be made, Cox showed that making interchangeable
software component A software component is a modular unit of software that encapsulates specific functionality. The desired characteristics of a component are reusability and maintainability. Value Components allow software development to assemble software ...
s really needed only a few practical changes to existing tools. Specifically, they needed to support
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ai ...
in a flexible manner, come supplied with a usable set of
libraries A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
, and allow for the code (and any resources needed by the code) to be bundled into one
cross-platform Within computing, cross-platform software (also called multi-platform software, platform-agnostic software, or platform-independent software) is computer software that is designed to work in several Computing platform, computing platforms. Some ...
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 explain that there is more to the problem of reusability than just what Objective-C provides, the language was often compared feature for feature with other languages.


Popularization through NeXT

In 1988,
NeXT NeXT, Inc. (later NeXT Computer, Inc. and NeXT Software, Inc.) was an American technology company headquartered in Redwood City, California that specialized in computer workstations for higher education and business markets, and later develope ...
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
Application Kit AppKit (formally Application Kit) is a graphical user interface toolkit. It initially served as the UI framework for NeXTSTEP. Along with Foundation and Display PostScript, it became one of the core parts of the OpenStep specification of APIs ...
(AppKit) and
Foundation Kit The Foundation Kit, or just Foundation for short, is an Objective-C framework in the OpenStep specification described by NeXT Computer, Inc.. It provides basic classes such as wrapper classes and data structure classes. This framework uses the ...
libraries on which the
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, founded by Steve Jobs, in the late 1980s and early 1990s and was initially used for its ...
user interface In the industrial design field of human–computer interaction, a user interface (UI) is the space where interactions between humans and machines occur. The goal of this interaction is to allow effective operation and control of the machine fro ...
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. NeXT dropped hardware production and focused on software tools, selling NeXTSTEP (and OPENSTEP) as a platform for custom programming. To circumvent the terms of the
GPL The GNU General Public Licenses (GNU GPL or simply GPL) are a series of widely used free software licenses, or ''copyleft'' licenses, that guarantee end users the freedom to run, study, share, or modify the software. The GPL was the first c ...
, 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 Richard Matthew Stallman ( ; born March 16, 1953), also known by his initials, rms, is an American free software movement activist and programmer. He campaigns for software to be distributed in such a manner that its users have the freedom to ...
, this plan was rejected after Stallman consulted with GNU's lawyers and NeXT agreed to make Objective-C part of GCC. The work to extend
GNU Compiler Collection The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
(GCC) was led by Steve Naroff, who joined NeXT from StepStone. The compiler changes were made available as per
GNU General Public License The GNU General Public Licenses (GNU GPL or simply GPL) are a series of widely used free software licenses, or ''copyleft'' licenses, that guarantee end users the freedom to run, study, share, or modify the software. The GPL was the first ...
(GPL) 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 licenses. Later, Steve Naroff was also principal contributor to work at Apple to build the Objective-C frontend to
Clang Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
. The
GNU GNU ( ) is an extensive collection of free software (394 packages ), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operating systems popu ...
project started work on its free software implementation of
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 and ...
, named
GNUstep GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project. GNUst ...
, based on the
OpenStep OpenStep is an object-oriented application programming interface (API) specification developed by NeXT. It provides a framework for building graphical user interfaces (GUIs) and developing software applications. OpenStep was designed to be plat ...
standard. Dennis Glatting wrote the first GNU Objective-C runtime in 1992. The current GNU Objective-C runtime, in use since 1993, is the one developed by Kresten Krab Thorup while he was a university student in
Denmark Denmark is a Nordic countries, Nordic country in Northern Europe. It is the metropole and most populous constituent of the Kingdom of Denmark,, . also known as the Danish Realm, a constitutionally unitary state that includes the Autonomous a ...
. Thorup also worked at NeXT from 1993 to 1996.


Apple development and Swift

After acquiring NeXT in 1996,
Apple Computer Apple Inc. is an American multinational corporation and technology company headquartered in Cupertino, California, in Silicon Valley. It is best known for its consumer electronics, software, and services. Founded in 1976 as Apple Computer Co ...
used OpenStep in its then-new operating system,
Mac OS X macOS, previously OS X and originally Mac OS X, is a Unix, Unix-based operating system developed and marketed by Apple Inc., Apple since 2001. It is the current operating system for Apple's Mac (computer), Mac computers. With ...
. This included Objective-C, NeXT's Objective-C-based developer tool,
Project Builder Project Builder was an integrated development environment (IDE) originally developed by NeXT for version 3 of the NeXTSTEP operating system by separating out the code editing parts of Interface Builder into its own application. After Apple Compu ...
, and its interface design tool,
Interface Builder Interface Builder is a software development application for Apple's macOS operating system. It is part of Xcode (formerly Project Builder), the Apple Developer developer's toolset. Interface Builder allows Cocoa and Carbon developers to crea ...
. Both were later merged into one application,
Xcode Xcode is a suite of developer tools for building apps on Apple devices. It includes an integrated development environment (IDE) of the same name for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, tvOS, and visionOS. It w ...
. Most of Apple's current
Cocoa API Cocoa is Apple's native object-oriented application programming interface (API) for its desktop operating system macOS. Cocoa consists of the Foundation Kit, Application Kit, and Core Data frameworks, as included by the Cocoa.h header file, and ...
is based on OpenStep interface objects and is the most significant Objective-C environment being used for active development. At
WWDC The Worldwide Developers Conference (WWDC) is an information technology conference held annually by Apple Inc. The conference is currently held at Apple Park in California. The event is used to showcase new software and technologies in the macO ...
2014, Apple introduced a new language,
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIF ...
, which was characterized as "Objective-C without the C".


Syntax

Objective-C is a thin layer atop C and is a "strict
superset In mathematics, a set ''A'' is a subset of a set ''B'' if all elements of ''A'' are also elements of ''B''; ''B'' is then a superset of ''A''. It is possible for ''A'' and ''B'' to be equal; if they are unequal, then ''A'' is a proper subset ...
" 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 Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
. 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 In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting ...
to object instances. In Objective-C, one does not ''call a method''; one ''sends a message''. This is unlike the
Simula Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of AL ...
-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 Bound or bounds may refer to: Mathematics * Bound variable * Upper and lower bounds, observed limits of mathematical functions Physics * Bound state, a particle that has a tendency to remain localized in one or more regions of space Geography * ...
to a section of code in the target class by the compiler. In
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
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'' o

— a unique identifier for each message name, often just a -terminated string representing its name—and resolved to a C method pointer implementing it: a

A consequence of this is that the message-passing system has no type checking. The object to which the message is directed—the ''receiver''—is not guaranteed to respond to a message, and if it does not, it raises an exception. Sending the message to the object pointed to by the pointer would require the following code in C++: obj->method(argument); In Objective-C, this is written as follows: bj method:argument The "method" call is translated by the compiler to the family of runtime functions. Different implementations handle modern additions like . In GNU families, this function is named , but it has been deprecated in favor of a modern lookup system under . Both styles of programming have multiple strengths and weaknesses.
Object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
in the Simula ( C++) style allows
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object ...
and faster execution by using compile-time binding whenever possible, but it does not support
dynamic binding Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics), the study of forces and their effect on motion Brands and enter ...
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 In computer science, compile time (or compile-time) describes the time window during which a language's statements are converted into binary instructions for the processor to execute. The term is used as an adjective to describe concepts relat ...
. An implementation is still required for the method to be called in the derived object. (See the
dynamic typing In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
section below for more advantages of dynamic (late) binding.)


Interfaces and implementations

Objective-C requires that the
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Inter ...
and implementation of a class be in separately declared code blocks. By convention, developers place the interface in a
header file An include directive instructs a text file processor to replace the directive text with the content of a specified file. The act of including may be logical in nature. The processor may simply process the include file content at the location of ...
and the implementation in a code file. The header files, normally suffixed .h, are similar to C header files while the implementation (method) files, normally suffixed .m, can be very similar to C code files.


Interface

This is analogous to class declarations as used in other object-oriented languages, such as C++ or Python. The interface of a class is usually defined in a header file. A common convention is to name the header file after the name of the class, e.g. would contain the interface for the class . An interface declaration takes the form: @interface ClassName : SuperclassName + 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 method A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be us ...
s, or methods that can be called on the class itself (not on an instance), and minus signs denote
instance method A method in object-oriented programming (OOP) is a Procedure (computer science), procedure associated with an Object (computer science), object, and generally also a Message passing, message. An object consists of ''state data'' and ''behavior''; ...
s, which can only be called on a particular instance of the class. Class methods also have no access to
instance variable In class-based, object-oriented programming, an instance variable is a variable defined in a class (i.e., a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable has similari ...
s. The code above is roughly equivalent to the following C++ interface: class ClassName : public SuperclassName ; Note that demonstrates the interleaving of selector segments with argument expressions, for which there is no direct equivalent in C/C++. Return types can be any standard C type, a pointer to a generic Objective-C object, a pointer to a specific type of object such as NSArray *, NSImage *, or NSString *, or a pointer to the class to which the method belongs (instancetype). The default return type is the generic Objective-C type . Method arguments begin with a name labeling the argument that is part of the method name, followed by a colon followed by the expected argument type in parentheses and the argument name. The label can be omitted. - (void)setRangeStart:(int)start end:(int)end; - (void)importDocumentWithName:(NSString *)name withSpecifiedPreferences:(Preferences *)prefs beforePage:(int)insertPage; A derivative of the interface definition is the ''category'', which allows one to add methods to existing classes.


Implementation

The interface only declares the class interface and not the methods themselves: the actual code is written in the implementation file. Implementation (method) files normally have the file extension .m, which originally signified "messages". @implementation classname + (return_type)classMethod - (return_type)instanceMethod @end Methods are written using their interface declarations. Comparing Objective-C and C: - (int)method:(int)i int function(int i) The syntax allows pseudo- naming of arguments. - (void)changeColorToRed:(float)red green:(float)green blue:(float)blue // Called like so: yColor changeColorToRed:5.0 green:2.0 blue:6.0 Internal representations of a method vary between different implementations of Objective-C. If myColor is of the class , instance method might be internally labeled . The is to refer to an instance method, with the class and then method names appended and colons changed to underscores. As the order of parameters is part of the method name, it cannot be changed to suit coding style or expression as with true named parameters. However, internal names of the function are rarely used directly. Generally, messages are converted to function calls defined in the Objective-C runtime library. It is not necessarily known at link time which method will be called because the class of the receiver (the object being sent the message) need not be known until runtime.


Instantiation

Once an Objective-C class is written, it can be instantiated. This is done by first allocating an uninitialized instance of the class (an object) and then by initializing it. An object is not fully functional until both steps have been completed. These steps should be accomplished with one line of code so that there is never an allocated object that hasn't undergone initialization (and because it is unwise to keep the intermediate result since -init can return a different object than that on which it is called). Instantiation with the default, no-parameter initializer: MyObject *foo = MyObject allocinit]; Instantiation with a custom initializer: MyObject *foo = MyObject allocinitWithString: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 = yObject 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 = yObject object MyObject *bar = yObject 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 In the above example, notice the return type. This type stands for ''pointer to any object'' in Objective-C (See the
Dynamic typing In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
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 message and assigns the result to (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 ; conditional statements like 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 message to self, and return 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 NeXT, Inc. (later NeXT Computer, Inc. and NeXT Software, Inc.) was an American technology company headquartered in Redwood City, California that specialized in computer workstations for higher education and business markets, and later develope ...
to introduce the concept of
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object ...
of specification, but not implementation, through the introduction of
protocols Protocol may refer to: Sociology and politics * Protocol (politics), a formal agreement between nation states * Protocol (diplomacy), the etiquette of diplomacy and affairs of state * Etiquette, a code of personal behavior Science and technology ...
. 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 Category, plural categories, may refer to: General uses *Classification, the general act of allocating things to classes/categories Philosophy * Category of being * ''Categories'' (Aristotle) * Category (Kant) * Categories (Peirce) * 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
reflective programming In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior. Historical background The earliest computers were programmed in their native assembly lang ...
(reflection)) and, if so, calls the delegate's method to support the auto-complete feature. A formal protocol is similar to an
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Inter ...
in Java, C#, and Ada 2005. It is a list of methods that any class can declare itself to implement. Objective-C versions 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 // ... @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 In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
: 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. - (void)setMyValue:(id)foo; In the above statement, ''foo'' may be of any class. - (void)setMyValue:(id)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 *)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 () 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 ''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a fore ...
, such as the
observer pattern In software design and software engineering, the observer pattern is a software design pattern in which an object, called the ''subject'' (also known as ''event source'' or ''event stream''), maintains a list of its dependents, called observers (a ...
or the
proxy pattern In computer programming, the proxy pattern is a software design pattern. A ''proxy'', in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in ...
. The Objective-C runtime specifies a pair of methods in * 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 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 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'' #import @interface Forwarder : Object // 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 - (id)setRecipient:(id)_recipient - (id)recipient @end ; ''Recipient.h'' #import // A simple Recipient object. @interface Recipient : Object - (id)hello; @end ; ''Recipient.m'' #import "Recipient.h" @implementation Recipient - (id)hello @end ; ''main.m'' #import "Forwarder.h" #import "Recipient.h" int main(void)


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 Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection ( if/then/else) and repet ...
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 software, a spell checker (or spelling checker or spell check) is a software feature that checks for misspellings in a text. Spell-checking features are often embedded in software or services, such as a word processor, email client, electronic ...
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 In computer science, a type signature or type annotation defines the inputs and outputs of a function, subroutine or method. A type signature includes the number, types, and order of the function's arguments. One important use of a type signat ...
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 In philosophy, the self is an individual's own being, knowledge, and values, and the relationship between these attributes. The first-person perspective distinguishes selfhood from personal identity. Whereas "identity" is (literally) same ...
. The C# and Visual Basic (.NET) languages implement superficially similar function in the form of
extension method In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype, or a type. Extension methods are features of some object-o ...
s, but these lack access to the private variables of the class.
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
and several other dynamic programming languages refer to the technique as "
monkey patch In computer programming, monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. It is used to extend or modify the runtime code of dynamic programming language, dynamic languages such as Smalltalk, Ja ...
ing".
Logtalk Logtalk is an object-oriented logic programming language that extends and leverages the Prolog language with a feature set suitable for programming in the large.Paulo Moura (2003). Logtalk: Design of an Object-Oriented Logic Programming Language. ...
implements a concept of categories (as first-class entities) that subsumes Objective-C categories function (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 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 patch In computer programming, monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. It is used to extend or modify the runtime code of dynamic programming language, dynamic languages such as Smalltalk, Ja ...
ing. 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'' : #import @interface Integer : Object - (int)integer; - (id)integer:(int)_integer; @end ; ''Integer.m'' : #import "Integer.h" @implementation Integer - (int) integer - (id) integer: (int) _integer @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 - (id) sub: (Integer *) subtrahend @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 - (id) showint @end ; ''main.m'' : #import "Integer.h" #import "Integer+Arithmetic.h" #import "Integer+Display.h" int main(void)


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 compiled 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 Mac OS X Leopard (version 10.5) is the sixth major release of macOS, Apple's desktop and server operating system for Macintosh computers. Leopard was released on October 26, 2007, as the successor of Mac OS X Tiger, and is available in two ed ...
, and is unavailable in the
64-bit In computer architecture, 64-bit integers, memory addresses, or other data units are those that are 64 bits wide. Also, 64-bit central processing units (CPU) and arithmetic logic units (ALU) are those that are based on processor registers, a ...
runtime. Similar function 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 @end class_poseAs ( ustomNSApplication class SApplication 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 guard In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard or file guard, is a way to avoid the problem of ''double inclusion'' when dealing with the include directive. The C preprocessor processe ...
s. The Objective-C directive should not be confused with the C++ keyword import, which is used to import C++
modules Module, modular and modularity may refer to the concept of modularity. They may also refer to: Computer science and engineering * Modular design, the engineering discipline of designing complex devices using separately designed sub-components ...
(since
C++20 C20 or C-20 may refer to: Science and technology * Carbon-20 (C-20 or 20C), an isotope of carbon * C20, the smallest possible fullerene (a carbon molecule) * C20 (engineering), a mix of concrete that has a compressive strength of 20 newtons per squ ...
), and is not a preprocessor directive. It should also not be confused with the #import preprocessor directive in
Microsoft Visual C++ Microsoft Visual C++ (MSVC) is a compiler for the C, C++, C++/CLI and C++/CX programming languages by Microsoft. MSVC is proprietary software; it was originally a standalone product but later became a part of Visual Studio and made available i ...
(MSVC), which is non-standard and used to import type libraries.


Linux gcc compilation

// FILE: hello.m #import int main (int argc, const char * argv[]) $ # 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 In engineering, debugging is the process of finding the Root cause analysis, root cause, workarounds, and possible fixes for bug (engineering), bugs. For software, debugging tactics can involve interactive debugging, control flow analysis, Logf ...
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 The Enterprise Objects Framework, or simply EOF, was introduced by NeXT in 1994 as a pioneering object-relational mapping product for its NeXTSTEP and OpenStep development platforms. EOF abstracts the process of interacting with a relational databa ...
to create database faults. 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 The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
and
Clang Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
, which can compile source files that use a combination of C++ and Objective-C syntax. The term "Objective-C++" was once featured in the
Apple An apple is a round, edible fruit produced by an apple tree (''Malus'' spp.). Fruit trees of the orchard or domestic apple (''Malus domestica''), the most widely grown in the genus, are agriculture, cultivated worldwide. The tree originated ...
Documentation for their Objective-C compiler as well, but has since been removed. 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 Class, Classes, or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used d ...
cannot derive from an Objective-C class and vice versa. * C++
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 ...
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 Default may refer to: Law * Default (law), the failure to do something required by law ** Default (finance) In finance, default is failure to meet the legal obligations (or conditions) of a loan, for example when a home buyer fails to make ...
or that have one or more
virtual method In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part o ...
s, but
pointers Pointer may refer to: People with the name * Pointer (surname), a surname (including a list of people with the name) * Pointer Williams (born 1974), American former basketball player Arts, entertainment, and media * ''Pointer'' (journal), the ...
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 C, or c, is the third Letter (alphabet), letter of the Latin alphabet, used in the English alphabet, modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is English alphabet#L ...
declaration and vice versa. However, Objective-C types (e.g., ) can be used as C++ template parameters. * Objective-C and C++
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
are 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 GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project. GNUst ...
libobjc2). * 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.


Objective-C 2.0

At the 2006
Worldwide Developers Conference The Worldwide Developers Conference (WWDC) is an information technology conference held annually by Apple Inc. The conference is currently held at Apple Park in California. The event is used to showcase new software and technologies in the macO ...
, Apple announced the release of "Objective-C 2.0," a revision of the Objective-C language to include "modern garbage collection, syntax enhancements, runtime performance improvements, and 64-bit support".
Mac OS X v10.5 Mac OS X Leopard (version 10.5) is the sixth major release of macOS, Apple's desktop and server operating system for Macintosh computers. Leopard was released on October 26, 2007, as the successor of Mac OS X Tiger, and is available in two ed ...
, 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 Mac OS X Leopard (version 10.5) is the sixth software versioning, major release of macOS, Apple Inc., Apple's desktop and server operating system for Macintosh computers. Leopard was released on October 26, 2007, as the successor of Mac OS X Ti ...
(10.5).


Garbage collection

Objective-C 2.0 provided an optional conservative, generational
garbage collector A waste collector, also known as a garbage man, garbage collector, trashman (in the U.S), binman or dustman (in the UK), is a person employed by a public or private enterprise to collect and dispose of municipal solid waste (refuse) and recycla ...
. When run in
backwards-compatible In telecommunications and computing, backward compatibility (or backwards compatibility) is a property of an operating system, software, real-world product, or technology that allows for interoperability with an older legacy system, or with Input ...
mode, the runtime turned
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refere ...
operations such as "retain" and "release" into
no-op In computer science, a NOP, no-op, or NOOP (pronounced "no op"; short for no operation) is a machine language instruction and its assembly language mnemonic, programming language statement, or computer protocol command that does nothing. Mac ...
s. All objects were subject to garbage collection when garbage collection was enabled. Regular C pointers could be qualified with "__strong" to also trigger the underlying write-barrier compiler intercepts and thus participate in garbage collection. A zero-ing weak subsystem was also provided such that pointers marked as "__weak" are set to zero when the object (or more simply, GC memory) is collected. The garbage collector does not exist on the iOS implementation of Objective-C 2.0. Garbage collection in Objective-C runs on a low-priority background thread, and can halt on user events, with the intention of keeping the user experience responsive. Garbage collection was deprecated in Mac OS X v10.8 in favor of
Automatic Reference Counting Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift (programming language), Swift programming languages. At compile time, it inserts into the o ...
(ARC). Objective-C on
iOS 7 iOS 7 is the seventh major release of the iOS mobile operating system developed by Apple Inc., being the successor to iOS 6. It was announced at the company's Worldwide Developers Conference on June 10, 2013, and was released on September 18 ...
running on
ARM64 AArch64, also known as ARM64, is a 64-bit version of the ARM architecture family, a widely used set of computer processor designs. It was introduced in 2011 with the ARMv8 architecture and later became part of the ARMv9 series. AArch64 allows ...
uses 19 bits out of a 64-bit word to store the reference count, as a form of
tagged pointer In computer science, a tagged pointer is a pointer (concretely a memory address) with additional data associated with it, such as an indirection bit or reference count. This additional data is often "folded" into the pointer, meaning stored inlin ...
s.


Properties

Objective-C 2.0 introduces a new syntax to declare instance variables as
properties Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property. Property may also refer to: Philosophy and science * Property (philosophy), in philosophy and logic, an abstraction characterizing an ...
, 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 @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 - (int)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 A person (: people or persons, depending on context) is a being who has certain capacities or attributes such as reason, morality, consciousness or self-consciousness, and being a part of a culturally established form of social relations such as ...
initWithAge:53]; aPerson.name = @"Steve"; // NOTE: dot notation, uses synthesized setter, // equivalent to Person setName: @"Steve" NSLog(@"Access by message (%@), dot notation(%@), property name(% @) and " "direct instance variable access(% @) ",
Person name A given name (also known as a forename or first name) is the part of a personal name quoted in that identifies a person, potentially with a middle name as well, and differentiates that person from the other members of a group (typically a f ...
aPerson.name, Person valueForKey:@"name" aPerson -> name);
To use dot notation to invoke property accessors within an instance method, the keyword should be used: - (void)introduceMyselfWithProperties:(BOOL)useGetter A class or protocol's properties may be dynamically introspected. int i; int propertyCount = 0; objc_property_t *propertyList = class_copyPropertyList(
Person class A person (: people or persons, depending on context) is a being who has certain capacities or attributes such as reason, morality, consciousness or self-consciousness, and being a part of a culturally established form of social relations such as ...
&propertyCount); for (i = 0; i < propertyCount; i++)


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 = hePeople objectEnumerator Person *p; while ((p = numerator nextObject != nil) // Using indexes for (int i = 0; i < hePeople count i++) // Using fast enumeration for (Person *p in thePeople) Fast enumeration generates more efficient code than standard enumeration because method calls to enumerate over objects are replaced by pointer arithmetic using the NSFastEnumeration protocol.


Class extensions

A class extension has the same syntax as a category declaration with no category name, and the methods and properties declared in it are added directly to the main class. It is mostly used as an alternative to a category to add methods to a class without advertising them in the public headers, with the advantage that for class extensions the compiler checks that all the privately declared methods are actually implemented.


Implications for Cocoa development

All Objective-C applications developed for macOS that make use of the above improvements for Objective-C 2.0 are incompatible with all operating systems prior to 10.5 (Leopard). Since fast enumeration does not generate exactly the same binaries as standard enumeration, its use will cause an application to crash on Mac OS X version 10.4 or earlier.


Blocks

Blocks is a nonstandard extension for Objective-C (and C 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 iOS 4 is the fourth major release of the iOS mobile operating system developed by Apple Inc., being the successor to iPhone OS 3. It was announced at the Apple Special Event on April 8, 2010, and released on June 21, 2010. iOS 4 was the first ...
or later, and GNUstep with libobjc2 1.7 and compiling with
clang Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
3.1 or later. #include #include typedef int (^IntBlock)(); IntBlock MakeCounter(int start, int increment) int main(void) /* 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 LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
compiler", i.e. clang frontend of the language. Confusingly, the versioning used by Apple differs from that of the LLVM upstream; refer to for a translation to open-source LLVM version numbers.


Automatic Reference Counting

Automatic Reference Counting (ARC) is a compile-time feature that eliminates the need for programmers to manually manage retain counts using retain and release. Unlike
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 recyclable ...
, which occurs at run time, ARC eliminates the overhead of a separate process managing retain counts. ARC and manual memory management are not mutually exclusive; programmers can continue to use non-ARC code in ARC-enabled projects by disabling ARC for individual code files. Xcode can also attempt to automatically upgrade a project to ARC. ARC was introduced in LLVM 3.0. This translates to Xcode 4.2 (2011), or Apple LLVM compiler 3.0.


Literals

NeXT and Apple Obj-C runtimes have long included a short-form way to create new strings, using the literal syntax @"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 LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
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. (Apple LLVM compiler 4.0 translates to open source LLVM and Clang 3.1.) Example without literals: NSArray *myArray = SArray arrayWithObjects:object1,object2,object3,nil NSDictionary *myDictionary1 = SDictionary dictionaryWithObject:someObject forKey:@"key" NSDictionary *myDictionary2 = SDictionary dictionaryWithObjectsAndKeys:object1, key1, object2, key2, nil NSNumber *myNumber = SNumber numberWithInt:myInt NSNumber *mySumNumber= SNumber numberWithInt:(2 + 3) NSNumber *myBoolNumber = SNumber numberWithBool:YES Example with literals: NSArray *myArray = @ object1, object2, object3 NSDictionary *myDictionary1 = @; NSDictionary *myDictionary2 = @; NSNumber *myNumber = @(myInt); NSNumber *mySumNumber = @(2+3); NSNumber *myBoolNumber = @YES; NSNumber *myIntegerNumber = @8; In Xcode versions before 13, unlike string literals, array, dictionary, and number literals were compiled into code equivalent to the above method calls. In particular, under manually reference-counted memory management, these objects were autoreleased, which required added care when, for example, used with function-static variables or other kinds of globals. In Xcode 13 (clang version 13.0.0 ) and later, array, dictionary, and number literals can also be embedded into the binary at compile time, just like string literals. This feature is enabled by default on Apple platforms and can be controlled with the -fno-objc-constant-literals and related compiler flags.


Subscripting

When using Apple
LLVM LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
compiler 4.0 or later, arrays and dictionaries (NSArray 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 is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
than Smalltalk. One of these attempts was introducing what was termed "Modern Syntax" for Objective-C at the time (in contrast 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 Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
/
LLVM LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
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, Inc. (later NeXT Computer, Inc. and NeXT Software, Inc.) was an American technology company headquartered in Redwood City, California that specialized in computer workstations for higher education and business markets, and later develope ...
/
Apple An apple is a round, edible fruit produced by an apple tree (''Malus'' spp.). Fruit trees of the orchard or domestic apple (''Malus domestica''), the most widely grown in the genus, are agriculture, cultivated worldwide. The tree originated ...
implementation, which added several extensions to the original Stepstone 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 Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
-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 Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
compiler suite, part of the
LLVM LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
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 General Public License The GNU General Public Licenses (GNU GPL or simply GPL) are a series of widely used free software licenses, or ''copyleft'' licenses, that guarantee end users the freedom to run, study, share, or modify the software. The GPL was the first ...
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 corporation and technology company, technology conglomerate headquartered in Redmond, Washington. Founded in 1975, the company became influential in the History of personal computers#The ear ...
forked ObjFW's runtime into a part of
WinObjC Universal Windows Platform (UWP) is a computing platform created by Microsoft and introduced in Windows 10. The purpose of this platform is to help develop universal apps that run on Windows 10, Windows 10 Mobile (discontinued), Windows 11, Xbox ...
, the iOS bridge for
Universal Windows Platform Universal Windows Platform (UWP) is a computing platform created by Microsoft and introduced in Windows 10. The purpose of this platform is to help develop universal apps that run on Windows 10, Windows 10 Mobile (discontinued), Windows 11, Xbox ...
, in 2015, though switched to a fork of in 2016. Combined with its own implementation of
Cocoa Touch UIKit is an application development environment and graphical user interface toolkit from Apple Inc. used to build apps for the iOS, iPadOS, watchOS, tvOS, and visionOS operating systems. UIKit provides an abstraction layer of iOS, the ...
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 MinGW ("Minimalist GNU for Windows"), formerly mingw32, is a free and open source software development environment to create Microsoft Windows applications. MinGW includes a port of the GNU Compiler Collection (GCC), GNU Binutils for Windows ...
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 free and open-source Unix-like environment and command-line interface (CLI) for Microsoft Windows. The project also provides a software repository containing open-source packages. Cygwin allows source code for Unix-like operati ...
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 and ...
,
GNUstep GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project. GNUst ...
or ObjFW. These libraries often come with the operating system: the GNUstep libraries often come with
Linux Linux ( ) is a family of open source Unix-like operating systems based on the Linux kernel, an kernel (operating system), operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically package manager, pac ...
-based distributions and Cocoa comes with macOS. The programmer is not forced to inherit functions from the existing base class (NSObject – OFObject). Objective-C allows for the declaration of new root classes that do not inherit any existing function. 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 Eloy ...
, 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 In computer programming, a runtime system or runtime environment is a sub-system that exists in the computer where a program is created, as well as in the computers where the program is intended to be run. The name comes from the compile time ...
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 or emulator, emulation of a computer system. Virtual machines are based on computer architectures and provide the functionality of a physical computer. Their implementations may involve ...
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, free software library providing a portable object system and transparent cross-language interoperability. GObject is designed for use both directly in C (programming language), C programs ...
library and
Vala Vala or VALA may refer to: Religion and mythology * Vala (Vedic), a demon or a stone cavern in the Hindu scriptures * Völva, also spelled Vala, a priestess in Norse mythology and Norse paganism Fiction * Vala (Middle-earth), an angelic being in ...
language, which are widely used in development of
GTK GTK (formerly GIMP ToolKit and GTK+) is a free software cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License, allowing both Free software, free and ...
applications. All of these practical changes lowered the
barrier to entry In theories of competition in economics, a barrier to entry, or an economic barrier to entry, is a fixed cost that must be incurred by a new entrant, regardless of production or sales activities, into a market that incumbents do not have or hav ...
, 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 and ...
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, founded by Steve Jobs, in the late 1980s and early 1990s and was initially used for its ...
. Since Objective-C is a strict superset of C, it does not treat C primitive types as
first-class object In a given programming language design, a first-class citizen is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and ass ...
s. Unlike C++, Objective-C does not support
operator overloading In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading ...
. Also unlike C++, Objective-C allows an object to directly inherit from only one class (forbidding
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object ...
). 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 recyclable ...
. 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 Mac OS X Leopard (version 10.5) is the sixth major release of macOS, Apple's desktop and server operating system for Macintosh computers. Leopard was released on October 26, 2007, as the successor of Mac OS X Tiger, and is available in two ed ...
. However, in more recent versions of macOS and iOS, garbage collection has been deprecated in favor of
Automatic Reference Counting Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift (programming language), Swift programming languages. At compile time, it inserts into the o ...
(ARC), introduced in 2011. With ARC, the compiler inserts retain and release calls automatically into Objective-C code based on
static code analysis In computer science, static program analysis (also known as static analysis or static simulation) is the analysis of computer programs performed without executing them, in contrast with dynamic program analysis, which is performed on programs duri ...
. 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''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
,
generic programming Generic programming is a style of computer programming in which algorithms are written in terms of data types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneer ...
, and
metaprogramming Metaprogramming is a computer programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyse, or transform other programs, and even modi ...
. 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''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
,
dynamic typing In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
, and
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, mirror-like reflection of waves from a surface *** Mirror image, a reflection in a mirror or in water ** Diffuse r ...
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 an object-oriented application programming interface (API) specification developed by NeXT. It provides a framework for building graphical user interfaces (GUIs) and developing software applications. OpenStep was designed to be plat ...
-like library such as
OPENSTEP OpenStep is an object-oriented application programming interface (API) specification developed by NeXT. It provides a framework for building graphical user interfaces (GUIs) and developing software applications. OpenStep was designed to be plat ...
,
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 and ...
, or
GNUstep GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project. GNUst ...
, which provides functions similar to C++'s standard library. One notable difference is that Objective-C provides runtime support for
reflective programming In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior. Historical background The earliest computers were programmed in their native assembly lang ...
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 favors run-time decisions while C++ favors 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 Generic programming is a style of computer programming in which algorithms are written in terms of data types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneer ...
and metaprogramming can be implemented in both languages using runtime polymorphism (
dynamic dispatch 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 function In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part ...
s 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 adding this feature in 2015.


See also

*
C (programming language) C (''pronounced'' '' – like the letter c'') is a general-purpose 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 of ...
* C++ *
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 Eloy ...
*
Comparison of programming languages Programming languages are used for controlling the behavior of a machine (often a computer). Like natural languages, programming languages follow rules for syntax and semantics. There are thousands of programming languages and new ones are creat ...
*
GNUStep GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project. GNUst ...
* Comparison with COM, GObject, SOM, Windows Runtime, XPCOM *
Swift (programming language) Swift is a High-level programming language, high-level general-purpose programming language, general-purpose, multi-paradigm programming language, multi-paradigm, compiled language, compiled programming language created by Chris Lattner in 2010 ...
*
Xcode Xcode is a suite of developer tools for building apps on Apple devices. It includes an integrated development environment (IDE) of the same name for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, tvOS, and visionOS. It w ...
*
WinObjC Universal Windows Platform (UWP) is a computing platform created by Microsoft and introduced in Windows 10. The purpose of this platform is to help develop universal apps that run on Windows 10, Windows 10 Mobile (discontinued), Windows 11, Xbox ...
(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

Objective-C Example
() {{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 Articles with example Objective-C code