Objective-C

from Wikipedia, the free encyclopedia
Objective-C
Publishing year: 1984
Designer: Brad Cox
Developer: Brad Cox, Tom Love
Current  version 2.0
Typing : strong , static , explicit , dynamic
Influenced by: Smalltalk , C.
Affected: Swift
Operating system : NeXTSTEP / OPENSTEP ; macOS / iOS ; anyone using GNUstep
Developer documentation

Objective-C , also called ObjC for short , extends the C programming language with language elements for object-oriented programming . Objective-C is a strict superset of C, which means that any C program can be compiled with an Objective-C compiler . Objective-C is the primary language of Cocoa ( macOS ) and GNUstep .

The syntax and conception of the object-oriented extensions is based on Smalltalk and is strictly separated from the usual procedural C syntax. This separation allows the same extension concept to be applied to other imperative languages ; for example there is Objective Pascal and Objective-J . Objective-C ++ partially allows the mixture of Objective-C with C ++ code with the aim of being able to use older code.

Among the languages ​​recorded in the TIOBE index , Objective-C recorded the greatest growth in 2011 and 2012 and was therefore named Language of the Year twice in a row .

history

Objective-C was mainly developed by Brad Cox and Tom Love in the 1980s at PPI , later Stepstone , and later integrated into the GNU Compiler Collection by NeXT to serve as the basis for NeXTSTEP .

At the Worldwide Developers Conference 2006, Apple, which had meanwhile bought NeXT, announced the release of "Objective-C 2.0". This version jump was justified with numerous profound improvements, including a. modern memory management (garbage collection), syntax improvements, runtime performance improvements, and support for 64-bit platforms.

Essential properties

Key value observation

One of the guiding principles when designing Objective-C was to approximate the flexibility of Smalltalk, but to forego what could impair the runtime behavior. The most obvious waiver of small talk is the lack of blocks . An Objective-C program can therefore be fully compiled at compile time. (Insofar as blocks have been introduced as closures in the meantime, this does not change anything, since these are literals that have already been compiled.)

Many concepts are not specified in the language definition itself, but are only made possible by the framework, e.g. Cocoa or GNUStep. In particular, the entire runtime system is not implemented in the compiler, but consists of C functions. In Objective-C, for example, the C function is objc_msg_send()called when a message is sent to an object . Therefore, a representation without the corresponding runtime system is hardly conceivable and does not make sense. Original Objective-C keywords, however, can be recognized by the prefix @.

Dynamic binding

A notable feature of Objective-C is the dynamic binding of methods. In contrast to languages ​​based on Simula-67 , polymorphism is not only possible within a class hierarchy, but also beyond it. A method with a specific name (selector) can be executed by objects of any class that implement it. It is not necessary that the caller knows the class or that the methods have already been defined in a base class - even if only virtually.

Dynamic typing and typeless id

It is therefore not necessary for the sender to know the class of the recipient. Rather, there is a type idthat can stand for any instance object of any class. The same applies to the sending of messages to class objects through the typing Class. It should be mentioned, however, that the pointer to an instance object is not typed in order to enable later binding. However, the individual instances are always typed, i.e. they belong to exactly one class. Objective-C typed strictly, but dynamically.

news

In Objective-C there is a strict separation of messages and methods. In Objective-C, we don't actually talk about method calls. Rather, there is a news transmitter (sender) and a news receiver (receiver). The receiver alone decides which method is to be carried out based on the message. The first attempt is to find a method with the same name. There is a corresponding data type SEL(selector) that maps a message name. The parameters and the recipient are still missing for the complete message. It is also possible to create message names at runtime.

This results in the possibility of designing and connecting entire object graphs and user interfaces in an IDE without the need for the programmer or the IDE to enter the source code. Conversely, however, it is the "normal" procedure of the dispatcher, so that no attachment is required and the programmer retains control over the execution of each method at all times. In practice, this eliminates a large part of the programming work.

Categories

Categories are extensions of existing classes with additional methods. It should be emphasized here that the methods contained in the categories also extend instances that are generated by external code. This also applies if the foreign code does not even know the category.

In addition, this category is also added to instances that originate from existing code and therefore do not even know the category that was added later. If, for example, an instance of is NSNumbergenerated in a framework that was developed years ago and whose source code is not available , then this also has the aforementioned method. This makes it possible to add methods to completely foreign classes.

Logs

As in Java with interfaces, sets of methods can be combined in protocols in Objective-C.

RTTI / reflection

At runtime , a reference to its type, i.e. the class, is carried for each object using RTTI . The class also contains a description of all instance variables and implemented methods. The dispatcher in the receiver then decides which method to assign to the message. Conversely, the sender can ask which methods are implemented.

Class objects

In Objective-C there are not only instance objects (short: instances), but also class objects. The term “instance of a class” is therefore ambiguous in Objective-C. However, class objects cannot contain member variables and are always singletons . Class methods are indicated by a preceding one +. Since these are objects, they can be assigned. You have the type yourself Class. There is an instance method -classand a class method +classto get the class object.

What is remarkable in this context is the property that there is a selfpointer for these class objects that is accessible to polymorphism.

syntax

The Objective-C syntax extends the C syntax to include object-oriented elements. These syntax extensions are not based on the C syntax, but on that of the Smalltalk programming language . The background is that the object-oriented essay can basically also be combined with other programming languages, for example with Pascal to Objective-Pascal. All new keywords are marked with a preceding @.

Class definition

To create your own kind of objects, you have to describe them in a class . For this purpose, the class and its methods are defined in the @interfacepart - usually in a header file .

Class name and inheritance

@interface Bruch : NSObject <Protokoll0, Protokoll1>

Each class has a name which, according to the convention, begins with a capital letter and is continued in CamelCase . The identifiers follow the C rules, so in particular they must not contain umlauts. The base class is then given, separated by a colon. Finally, protocols whose implementation is promised can be specified in angle brackets. If there are several protocols, their names must be listed in brackets separated by commas.

Instance variables

The list of instance variables follows in curly brackets.

{
    NSInteger zaehler;
    NSInteger nenner;
}

These are created for each instance. The visibility can be controlled via sections with @public, @private, @protected and @package (only for 64-bit runtime systems). @public means that everyone can access this instance variable, @protected that this can only be done in the code of the same class or derived classes, @private that this can only be done in the same class and @package that this can only be done in classes of the framework may take place. The standard is @protected, which is actually almost always used because of other technologies. Therefore, the vast majority of class definitions do not contain any of the visibility keywords.

Properties

Since Objective-C 2 it has been possible to list properties (attributes or relationships) after the instance variables. The definition of a property has the form

@property( Attributliste ) Typ name;

The attributes can be differentiated in terms of write protection, reference model and atomicity.

  • The readonly and readwrite (default) attributes exist for write protection
  • Atomicity: The " nonatomic " attribute optimizes access to the property for single-thread use. By default, properties are safe for use in multithreaded environments; to set this property explicitly, the opposite attribute “ atomic ” is specified.
  • Referencing is via the words " assign " (default) as a pure assignment in the setter, even if the type of the property is an instance pointer, " retain " as a reference in the sense of reference counting (the parameter receives the message " retain ") and " copy ", if the setter should make a copy (the parameter receives the message " copy ").

If only default properties are used, the attribute list including brackets can be omitted:

@property NSInteger zaehler;

However, if the code with reference counting is compiled as a memory model and a property is only to be assigned using assign, this must be specified explicitly, although this is preset. Otherwise the compiler warns. It is generally advisable to explicitly specify the reference model for instance pointers, while it is superfluous for C types, since only assign makes sense.

@property NSInteger zaehler; // NSInteger ist ein C-Typ.
@property( copy ) NSString* name; // NSString* ist ein Instanzzeiger.

Method declarations

Next is a list of methods:

- (void) printLn;
- (float) floatValue;

Each individual method declaration begins with a +'' (class method) or -'' (instance method). This is followed by the type of return value in brackets, whereby, as in C, void is the keyword for no return value. This is followed by the method name, whereby the rules for C identifiers apply again.

If the method is to contain a parameter, the external description of the first parameter follows as part of the identifier, followed by a colon, the type in brackets and then an identifier. If further parameters follow, they are given a descriptive name after a space (which can also have 0 characters), which is again followed by a colon, the type in brackets and then an identifier:

- (id)initWithZaehler:(NSInteger)zaehler andNenner:(NSInteger)nenner;

The declaration ends with a semicolon.

The class definition is terminated with @end.

implementation

The implementation is usually in a further file that ends with .m by default (Eselsbrücke: iMplementation or Module). It starts with @implementation and ends with an @end. The methods are implemented in between - regardless of whether they are made known in the interface or not. A distinction must be made between standard methods and synthesized methods (Objective-C 2 only) for properties (see above); the head of the standard methods corresponds to the method declaration. However, instead of the semicolon (which remains optional, unusual!) The instruction list in curly brackets is used:

- (id)initWithZaehler:(NSInteger)zaehler andNenner:(NSInteger)nenner
{
   // Code hier
}

It should be noted that the identifiers of the formal parameters do not have to correspond to those from the method declaration. Synthesized methods are the access methods for the properties:

@synthesize zaehler, nenner;

Access methods are then generated for the attributes specified in the interface. By default, the compiler uses instance variables with the same name. The programmer reserves the right to formulate these methods himself, whereby these must be named property and set property (only with readwrite):

- (NSInteger)zaehler { return zaehler; }
- (void)setZaehler:(NSInteger)value { zaehler = value; }

Another possibility is to designate a property using @dynamic. In this case, the compiler no longer checks its existence in the implementation. So you can simulate the corresponding methods at runtime or add them to the class yourself:

@dynamic zaehler; // Zugriffsmethoden werden zur Laufzeit gehandhabt.

news

Since Objective-C differentiates between message and method, no syntax based on the C function call is used for sending messages. Rather, the dispatch takes place in the form:

[Empfänger Nachricht]

If a message is to be sent to a class object so that a class method is executed, you simply write the class as recipient:

Bruch* bruch = [Bruch alloc]; // +alloc ist Klassenmethode

In the case of messages to the instance method, its pointer is used: [bruch initWithZaehler:3 andNenner:4]; As can be seen, the parameters are inserted and separated by spaces, not commas. Messages can also be nested. E.g.

NSString *string = @"Hallo Welt";
NSData *data = [NSData dataWithBytes:[string cString] length:[string cStringLength]];

This NSDatacreates a new object of the class . The bytes that are copied into the new object are also [string cString]requested, the length of the block with [string cStringLength].

The return values ​​of the methods are used. This also applies to the recipient, for example:

Bruch* bruch = [[Bruch alloc] init]

The object that was created with [Klasse alloc]gets the message init.

Locking

Objective-C offers a syntax for locks in threading. For this purpose, a code section is introduced with the keyword @synchronized, which receives an object as a lock as a parameter:

@synchronized( anInstance ) {
   // Exklusiver Code für den Lock anInstance
}

Exceptions

Exception handling is done in Objective-C using @try, @catch, @finallyand @throw;

An exception is thrown - directly with language means - by means of the keyword @throw; By specifying different classes, it is possible to determine which class should be an exception that is caught, both on the same level and in hierarchies. The @catchexception can be thrown again in the block and is then handled by an external exception handler.

Class object

Objective-C has so-called class objects. Not only the instances but also the classes are objects and can receive messages, as above . - No additional language elements such as constructors and keywords are required for instantiation. [Klasse alloc]

In the class definition, class methods are marked with +'', instance methods with -''.

+allocis not part of the language description, but any - any - method of the framework and therefore accessible to your own implementation. Overriding the method is only a good idea for experts, however. In contrast, the method +initializethat is called before a class is used is empty by default and can be overridden for class-related preferences.

Type concept

Objective-C adds the data type id to the standard C data types. An object of type id is any object. What can be started with this object is only determined at runtime. There are methods for finding out something about the object. Are important:

[obj class]               // bestimmt die Klasse
[obj respondsToSelector:] // bestimmt, ob eine Methode vorhanden ist
[obj conformsToProtocol:] // bestimmt, ob ein Protokoll implementiert ist

The type concept also allows the general object or other objects to be typed using (formal) protocols. These define a set of methods. These protocols do not have to be uniform in a hierarchy tree either, but are inherited.

The freedom of type allows the creation of general containers which, in contrast to generic containers in languages ​​such as C ++ and Java, can also have mixed types (heterogeneous).

Late binding

Objective-C only binds a method call to a method at runtime. This is basically the same in C ++. In C ++, however, it must be ensured at compilation time that a method exists because it belongs to the class hierarchy. C ++ is only willing to bind late within a branch of a hierarchy, while Objective-C does this regardless of the position of a class in a hierarchy tree. This should be clarified using a syntax-neutral example:

 Klasse A
   methode()
 Klasse B von Klasse A
   methode()
 Klasse C
   methode()
 ...

For this purpose, Objective-C carries extensive information about an object at runtime, which goes beyond RTTI . For the same reason, it is also easily possible to first determine a method at runtime. Similar to a method pointer, the method can be located in a variable that is not assigned a value until runtime.

Cocoa, for example, makes extensive use of this technique when linking interface elements to methods. The method can also be determined by its real name.

Sample program

NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] init];

[aDictionary setObject: @"foo" forKey: @"Foo"];
[aDictionary setObject: @"bar" forKey: @"Bar"];
[aDictionary setObject: @"Hallo Welt!" forKey: @"Hello, world!"];

NSLog([aDictionary objectForKey: @"Hello, world!"]);

[aDictionary release];

Output: Hallo Welt!

Objective-C ++

Objective-C ++ is a front end of the GNU Compiler Collection that can translate sources that use both C ++ and Objective-C syntax. Objective-C ++ does not attempt to standardize the different concepts of the two languages. Rather, it just extends C ++ with the extensions that Objective-C adds to C. This leads to certain limitations:

  • C ++ classes cannot inherit from Objective-C classes.
  • Conversely, Objective-C classes cannot inherit from C ++ classes either.
  • You cannot declare any C ++ namespaces within an Objective-C declaration .
  • C ++ classes that do not have a default constructor or that have virtual functions cannot be used as instance variables of an Objective-C class. But you can use pointers to such classes.
  • Objective-C objects cannot be used as value parameters because they can only be addressed via pointers.
  • Objective-C declarations cannot be used in C ++ template declarations, and vice versa. However, Objective-C types (such as class name *) can be used as C ++ template parameters.
  • The exception handling mechanisms of Objective-C and C ++ are independent of each other; An Objective-C exception handler cannot catch C ++ exceptions and vice versa. However, this no longer applies to the "modern runtime" of Objective-C 2.0 (iOS or 64-bit Mac), as the exception concept from C ++ was adopted here.
  • The fact that the conventions for calling destructors are not compatible requires special care. For example, a C ++ destructor is not called if the scope of the C ++ object is exceeded using an Objective-C exception. However, this no longer applies to the "modern runtime" of Objective-C 2.0 (iOS or 64-bit Mac), as the exception concept from C ++ was adopted here.

A typical use of Objective-C ++ is, for example, the use of a C ++ library in an Objective-C application.

Objective-C 2.0

In October 2007, Apple shipped Mac OS X Leopard Objective-C 2.0 , an extension of Objective-C that "includes modern garbage collection, syntax extensions, runtime performance improvements and 64-bit support."

The GNU runtime environment for Objective-C supports these extensions since GCC 4.6.

Garbage collection

GNUstep supported Hans Boehm's garbage collector in old versions, but this is incompatible with Apple's implementation. Leopard and GNUstep include an optional conservative garbage collector for Objective-C 2.0.

Properties

Objective-C 2.0 introduces a new syntax with which instance variables can be declared as properties . The syntax supports optional attributes, which define the access methods in more detail: A property can be readonlydeclared as, and can be provided with different behavior rules for memory management such as assign, copyor retain.

Properties are @synthesizeimplemented with the keyword , which generates getter and setter methods according to the property declaration. Alternatively, you can use the keyword @dynamicto indicate that you are implementing these methods yourself. In the case of the following example, however, it is optional because the compiler notices the implementation of the accessors. The keyword is more important @dynamicif the accessors are not created until runtime. Because here the compiler would miss a corresponding definition and issue a warning. This is the case with managed objects , for example , which generate accessors from the loaded description structure of the entity at runtime.

Dot notation

Accessors, regardless of whether they are explicitly defined or created via a property, can be accessed using the dot notation known from other languages.

However, there is no uncontrolled access to the instance variable, but the accessor property and set property are used.

To use dot notation within an instance method, use the self keyword . The properties of an instance can also be accessed dynamically by reflection .

Fast enumeration

As of 2.0, Objective-C provides the “ for-in ” syntax to iterate through a collection (iterate through it).

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

while ((p = [enumerator nextObject]) != nil) {
 NSLog(@"%@ is %i years old.", [p name], [p age]);
}
// alternativ iterieren
for (int i = 0; i < [thePeople count]; i++) {
 Person *p = [thePeople objectAtIndex:i];
 NSLog(@"%@ is %i years old.", [p name], [p age]);
}
// neu iterieren
for (Person *p in thePeople) {
 NSLog(@"%@ is %i years old.", [p name], [p age]);
}

Compared to other programming languages

C ++

Although both languages ​​share a common ancestor in C, there are significant conceptual differences, particularly due to late binding and the ability to create classes and messages at runtime.

Functionality expansion

Objective-C offers categories as a possible solution. The method set of a class is subsequently expanded.

See also

literature

  • NeXT Computer, Inc. (Ed.): Object-Oriented Programming and the Objective C Language, NeXTSTEP Developers Library Release 3. Addison-Wesley, Reading, Mass. 1993, ISBN 0-201-63251-9 .
  • Brad J. Cox, Andrew J. Novobilski: Object-Oriented Programming: an evolutionary approach. 2nd Edition. Addison-Wesley, Reading, Mass. 1991, ISBN 0-201-54834-8 . (Introduction by the author of this language).
  • Stephen Kochan: Programming in Objective-C. Sams, 2003, ISBN 0-672-32586-1 (English).
  • Aaron Hillegass: Cocoa: Programming for Mac OS X. 3rd Edition. Mitp-Verlag, Heidelberg 2008, ISBN 978-3-8266-5960-7 .
  • Stephen G. Kochan: Objective-C 2.0: Developing Applications for Mac and iPhone . Pearson Germany, 2009, ISBN 978-3-8273-2746-8 ( books.google.com ).
  • Sebastian Meyer, Torben Wichers: Objective-C 2.0: [programming for Mac OS X and iPhone; Objects, classes, messages, categories, properties, protocols, exception handling; foundation framework, memory management, threading, bundles; design patterns for Objective-C] . 1st edition. mitp, Heidelberg / Munich / Landsberg / Frechen / Hamburg 2009, ISBN 978-3-8266-5966-9 .
  • Amin Negm-Awad, Christian Kienle: Xcode, Objective-C and Cocoa . In: Horst-Dieter Radke (Hrsg.): Automation and application development on the Mac - introductions . 1st edition. SmartBooks Publishing AG, 2009, ISBN 978-3-908497-98-1 .
  • Amin Negm-Awad, Christian Kienle: Objective-C and Cocoa . 1st edition. tape 2 : advanced . SmartBooks Verlag, 2010, ISBN 978-3-908497-84-4 .
  • Holger Hinzberg: Mac programming for kids . 2nd Edition. mitp-Verlag, Frechen 2011, ISBN 978-3-8266-8684-9 .
  • Amin Negm-Awad: Objective-C and Cocoa . 3rd / 5th Edition. tape 1 : Basics . SmartBooks Verlag, 2012, ISBN 978-3-908498-08-7 .
  • Holger Hinzberg: Modern Objective-C and Cocoa Practical introduction: Programming for Mac OS X and iPhone . 3. Edition. mitp-Verlag, Frechen 2014, ISBN 978-3-8266-9701-2 .
  • Matt Galloway: Programming Objective-C 2.0 Effectively 52 professional solutions for better iOS and OS-X programming. Dpunkt.verlag, Heidelberg 2014, ISBN 978-3-944165-71-4 .

Web links

Individual evidence

  1. developer.apple.com . (accessed on September 2, 2019).
  2. Alexander Neumann: Objective-C named language of the year. heise online , January 9, 2012, accessed on January 21, 2012 .
  3. ^ Heise Zeitschriften Verlag: Objective-C is TIOBE's programming language of the year 2012 . Jan. 7, 2013 (accessed Feb. 12, 2013)
  4. ^ Objective-C 2.0: more clues. (No longer available online.) Lists.apple.com, August 10, 2006, archived from the original on June 18, 2009 ; Retrieved May 30, 2010 . Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. @1@ 2Template: Webachiv / IABot / lists.apple.com
  5. ^ Re: Objective-C 2.0. (No longer available online.) Lists.apple.com, archived from the original on November 24, 2010 ; Retrieved May 30, 2010 . Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. @1@ 2Template: Webachiv / IABot / lists.apple.com
  6. Sample video from Apple ( Memento from June 7, 2011 in the Internet Archive )
  7. Declared Properties. In: The Objective-C Programming Language. Apple , October 12, 2011, accessed January 21, 2012 .
  8. Apple - Objective-C 2.0 Overview ( Memento from July 24, 2010 in the Internet Archive )