Objective-C

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

The syntax and design of object-oriented extensions is based on Smalltalk and strictly separated from ordinary procedural C syntax. This separation makes it possible to apply the same extension concept to other imperative languages ​​; so there are about Objective Pascal and Objective- J. Objective- C allows partially the mixture of Objective- C and C code with the aim of being able to use legacy code.

Among the languages ​​recognized in TIOBE index Objective- C was recorded in 2011 and 2012, the largest increase in the years and was granted the title twice in a row Language of the year.

  • 3.1 class definition 3.1.1 Class and Inheritance
  • 3.1.2 Instance Variables
  • 3.1.3 Properties (Properties)
  • 3.1.4 Method Declarations
  • 3.1.5 implementation
  • 6.1 Program Example
  • 8.1 Garbage Collection
  • 8.2 Properties
  • 8.3 dot notation
  • 8.4 Fast Enumeration
  • 9.1 C 9.1.1 Functionality Expansion

History

Objective- C was primarily by Brad Cox and Tom Love in PPI, later StepStone, developed in the 80s, and later integrated by NeXT in the GNU Compiler Collection to serve as a basis for NeXTStep.

At the Worldwide Developers Conference 2006 Apple announced the release of " Objective- C 2.0 " known. This version jump was based on numerous profound improvements, including a modern memory management (garbage collection ), syntax enhancements, runtime performance improvements, and support for 64- bit platforms.

Essential properties

One of the guiding principles in the design of Objective- C was to approach the flexibility of Smalltalk, but to give up what could degrade the run-time behavior. The most obvious waiver against Smalltalk is the lack of blocks. Therefore, an Objective- C program is already at compile-time completely compilable. ( Unless in the meantime blocks were introduced as closures, this does not change, since it is already compiled literals. )

Many concepts are not defined in the language definition itself, but only become by the framework, ie about Cocoa or GNUstep, allows. In particular, the entire runtime system is not implemented in the compiler, but consists of C functions. In Objective- C, the C function objc_msg_send () is called, for example, when sending a message to an object. Therefore, a representation without the corresponding run-time system is hardly conceivable, and not advisable. Primary Objective- C keywords can be seen, however, on which are prefixed with @.

Dynamic binding

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

Dynamic typing and type- loose id

It is therefore not necessary for the sender to know the class of the receiver. Rather, there exists a type id, which can stand for any object instance of each class. The same is true for sending messages to class objects by the typing class. It should be noted, however, that although the pointer is not on a typed object instance in order to allow late binding. The individual instances, however, are always typed exactly belong to a class. Objective- C typed so severe, but dynamic.

News

In Objective- C, there is a strict separation between messages and methods. It really speaks therefore in Objective- C not of method calls. Rather, there is a news station (transmitter) and a message receiver (receiver). Only the receiver decides on the basis of the message, which method is executed. Will first try to find a same method. There exists a data type corresponding to SEL (selector), which reflects a message name. For complete message then the parameters are still missing and the receiver. It is also possible to create message names until runtime.

This gives the opportunity to design in an IDE entire object graph and user interfaces and to connect without the input of source code by the programmer or by the IDE itself is required. Conversely, however, it is the "normal" procedure of the dispatcher, so that no essay for this is required, and the programmer at any time retains control over the execution of each method. In reality, eliminating much of the programming work.

Categories

Categories are extensions of existing classes to other methods. It should be emphasized that the methods contained in the categories expand instances that are generated by foreign code. This is true even if the foreign code does not know the category.

In addition, it behaves so that this category is also added to instances derived from existing code and therefore do not know the subsequently added category. Is therefore approximately in a framework, which has been developed in years and the source code does not exist, creates an instance of NSNumber, this also has the above-mentioned method. This makes it possible to add completely alien classes methods.

Protocols

Similar to Java with interfaces can be divided into sets of Objective-C methods in protocols summarized.

RTTI / Reflection

At runtime, for each object, using RTTI, a reference to its type, ie the class, carried. The class also contains a description of all the instance variables and methods implemented. This is followed, the dispatcher decides in the receiver, which method he assigns to the message. Conversely, ask what methods are implemented by the sender.

Class objects

Exist in Objective- C 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 can not contain member variables and are always singletons. Class methods are identified by the prefix . There are objects, they may be assigned. You have the type Class. There is an instance method, class and a class method class to get the class object.

Remarkable in this connection is the property that there is a self pointer to the class object that is accessible to the polymorphism.

Syntax

The syntax of Objective- C extends the C syntax for object-oriented elements. However, this syntax extensions do not lean against the C- syntax, but to the Smalltalk programming language. The background is that the object-oriented attachment can in principle be combined with other programming languages ​​, such as Pascal to Objective- Pascal. All of the new key words are marked with a preceding @.

Class definition

To create its own kind of objects, you have to describe them in a class. The class and its methods defined - is given in the @ interface section - usually in a header file.

Class and Inheritance

@ interface Fraction: NSObject < protocol > Each class has a name, which by convention begins with a capital letter and will continue in CamelCase. The identifiers follow the C rules, may thus in particular no umlauts. Separated by a colon, the base class is then specified. Finally, protocols can be enclosed in angle brackets, their implementation is promised. If it is multiple protocols, so their names are in the parentheses with commas listed separately.

Instance variables

It follows in braces, the list of instance variables.

{      NSInteger count;      NSInteger denominator; } These are created for each instance. The visibility can be controlled by sections with @ public, @ private, @ protected, and @ package (only for 64- bit runtime system ). @ public here means that everyone is allowed to access that instance variable, @ protected, that it should be done in code in the same class or derived classes @ private that it should be done in the same class and @ package that this is only in framework classes may take place. Default is @ protected, which is actually almost always used because of other technologies. Therefore, the vast majority of class definitions, none of keywords include visibility.

Properties (Properties)

After the instance variables it is possible since Objective- C 2, to list properties (attributes or relationships). The definition of a property has the form

@ property (attribute list) type name; The attributes can be in terms of write protection, different of the reference model and atomicity.

  • For the read-only attributes exist readonly and readwrite (default)
  • Atomicity: Through the attribute " nonatomic " access to the property for single-threaded usage is optimized. By default, properties are safe for use in multithreaded environments, for which there is no separate attribute.
  • Referencing is about the words "assign" (default ) as pure assignment in the setter, even if the type of the property is an instance pointer, " retain" as a reference within the meaning of Reference countings (the parameter receives the message " retain" ) and "copy " when the setter is to make a copy (the parameter receives the message " copy" ) is described.

Only default properties is used, the attribute list can be omitted together with the bracket:

@ property NSInteger count; However, if the code is compiled with reference counting as a storage model and should only be assigned to a property by assignment, this must be, although preset to be specified explicitly. Otherwise, the compiler warns. It offers itself generally to explicitly specify the reference model at instance pointers, while it is unnecessary in C types, as only assign is useful.

Next is a list of methods:

- (Void) println; - (Float ) float value; Each method declaration begins first with a ' ' ( class method ) or '-' (instance method). In parentheses After this the type of the return value, which stands as a keyword for no return value as in C void. This is followed by the method name, again, the rules for C identifiers.

If the method includes a parameter, it follows as part of the identifier, the outer description of the first parameter, it is a colon, in parentheses, the type and then an identifier. Follow other parameters, so what again a colon, in parentheses, the type and then an identifier are ( can also have the 0 mark ) this provided again after a space with a descriptive name, followed by:

The class definition is completed end with @.

Implementation

The implementation is usually in another file, which defaults to m ends ( mnemonic: implementation or modules). . It begins with @ implementation and ends with an @ end. In between, the methods are implemented - regardless of whether made ​​known in the interface or not. In this case, standard methods and synthesized methods (only Objective- C 2) for properties (see above) to distinguish standard methods correspond in their head the method declaration. However, takes the place of the semicolon (which remains optional, unusual! ) The statement list enclosed in braces:

- (Id) initWithZaehler: ( NSInteger ) count andNenner: ( NSInteger ) denominator {     / / Code here } It should be noted that the identifier of the formal parameters do not match those from the method declaration. Synthesized methods are the access methods for the properties:

@ synthesize count, denominator; There are then generated access methods for the interface specified in the attributes. By default, the compiler uses this same instance variables. The programmer it remains reserved, even to formulate these methods, which the name property and setEigenschaft have to wear (only for read write ):

- ( NSInteger ) count { return count; } - (Void) setZaehler: ( NSInteger ) value { counter = value; } A further possibility is that a property is referred to by dynamic @. In this case, the compiler no longer checks for the existence in the implementation. So you can simulate the appropriate methods at runtime or even add to the class:

Since Objective- C differs between message and method, no ajar to the C function call syntax is used for sending messages. Rather, the despatch of the form:

[ Receiver message] To be sent to a class object a message, so a class method is executed, so you just write the class as a receiver out:

Break break * = [ break alloc]; / / Alloc is a class method For messages to the instance method whose pointer is used: [ break initWithZaehler: 3 andNenner: 4]; As can be seen, while the parameters are used and by space, not comma separated. Messages can also be nested. For example,

NSString * string = @ " Hello World"; NSData * data = [ NSData data with bytes: [string cString ] length: [ string cStringLength ] ]; Creates a new object of class NSData is created. The bytes that are copied into the new object will be queried with [string cString ], the length of the block with [string cStringLength ].

The return values ​​of methods so it can be used. This is also the recipient, for example:

Break break * = [[ break alloc] init] The object that was created with [Class alloc ] init gets the message.

Locking

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

@ synchronized ( anInstance ) {     / / Exclusive code for the lock anInstance } exceptions

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

Raises an exception - directly with language resources - by using the keyword @ throw; By information of different classes can be determined both at the same level as in hierarchies, which class should be an exception that is caught. In the @ catch block, the exception can be thrown again and is then treated by an outer exception handler.

Class objects

Objective- C has so-called class objects. Not only the instances but also the classes are objects and can receive messages as above [Class alloc]. - Any additional language elements such as constructors and keywords are necessary to instantiate.

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

Any - - alloc not part of the language description, but is a method of the framework and therefore their own implementation available. However, to override the method is a good idea for experts only. Quite the contrary, the method initialize, which is called before using a class, empty by default and can be overridden on a class -related advance settings.

Type concept

Objective- C adds to the standard C data types, the data type id added. Id An object of the type is any object. What can be started with this object will only be determined at runtime. To this end, there are methods to learn something about the object. Important are:

  • [ obj class] / / determines the class
  • [ obj respondsToSelector: ] / / determines whether a method exists
  • [ obj conformsToProtocol: ] / / determines whether a protocol is implemented

The type concept also allows the typing of the general object or other objects through (formal ) protocols. They define a set of methods. Also, these protocols need not be uniform in a hierarchy tree, but are inherited.

The type of freedom allows the creation of general container, which may also type mixed ( heterogeneous) unlike generic containers in languages ​​such as C and Java.

Late binding

Objective- C binds a method call at runtime to a method. In principle, this is also written in C that. However, it must be ensured already at compile time in C 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 will be illustrated in a syntax - neutral example:

Class A     method ( )   Class B from class A     method ( )   class C     method ( )   ... For this purpose, Objective- C results at runtime with extensive information about an object, which goes beyond RTTI. For the same reason, ultimately it is also easily possible to first determine a method at run time. The method can be similarly located as in a method pointer in a variable, which is only occupied at runtime with a value.

Of this technique makes about Cocoa in binding interface elements of methods heavy use. The determination of the method can also be done by their real names.

Program Example

NSMutableDictionary * aDictionary = [[ NSMutableDictionary alloc] init];   [ aDictionary setObject: @ " foo" forKey: @ " Foo "]; [ aDictionary setObject: @ "bar" forKey: @ " bar "]; [ aDictionary setObject: @ " Hello world!" forKey: @ " Hello, world! "];   NSLog ( [ aDictionary objectForKey: @ " Hello, world! " ]);   [ aDictionary release]; Output: Hello world!

Objective-C

Objective- C is a front end to the GNU Compiler Collection, which can translate sources that both C - use as well as Objective- C syntax. Objective- C does not attempt to unify the different concepts of the two languages. Rather, it merely extends C to the extensions that adds Objective- C to C. This leads to certain restrictions:

  • C classes can not inherit from Objective- C classes.
  • Conversely, Objective- C classes can not inherit from C classes also.
  • Within an Objective- C declaration can not declare a C namespaces.
  • C classes that do not have a default constructor, or have the virtual functions can not be used as instance variables of an Objective- C class. But we can certainly use pointers to such classes.
  • Objective- C objects can not be used as a parameter value, since they are accessible only via pointers.
  • Objective- C declarations may not be used in C template declarations, and vice versa. However, Objective- C types can be used (such as class name *) as a C template parameters.
  • The exception handling mechanisms of Objective-C and C are independent of each other; An Objective -C exception handler can catch no C exceptions and vice versa. However, this is no longer true for the " modern runtime" Objective- C 2.0 (iOS or 64-bit Mac), since the Exception concept was acquired by C .
  • Requires special care, the fact that the conventions for calling destructors are not compatible. For example, a C destructor is not called if the scope of the C object is exited by means of an Objective- C exception. However, this is no longer true for the " modern runtime" Objective- C 2.0 (iOS or 64-bit Mac), since the Exception concept was acquired by C .

A typical application of Objective-C , for example using a C library in an Objective- C application.

Objective- C 2.0

In October 2007, Apple shipped with Mac OS X 10.5 Objective- C 2.0, an extension of Objective- C, the "modern garbage collection, syntax enhancements, including improvements to the runtime performance and 64 -bit support ".

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

Garbage Collection

GNUstep has supported in old versions of the garbage collector by Hans Boehm, but it 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 one can declare instance variables as properties. The syntax supports optional attributes that define the access methods in more detail: A property can be declared as read only, and can be provided with different rules of behavior for memory management such as assign, copy or retain.

Properties are implemented using the @ synthesize keyword, which generates getter and setter methods according to the property declaration. Alternatively, you can also use the keyword @ dynamic to indicate that implements these methods themselves. In the case of the following example, however, it is optional, as the compiler notes the implementation of accessors. More important is the keyword @ dynamic if the accessors are generated at runtime. For here the compiler would miss a definition and issue a warning. This is the case, the create runtime accessors from the loaded structure description in the entity about managed objects.

Dot notation

On accessors, whether explicitly defined or created on a property that can be accessed using the dot notation known from other languages.

Here, however, is no uncontrolled access to the instance variable, but the accessors and set - property property will be used.

To use the dot notation within an instance method, one uses the keyword self. On the properties of an instance can be accessed dynamically via reflection.

Fast enumeration

From Objective-C 2.0 provides the " for-in " syntax available to ( go through it ) by a collection to iterate.

/ Iterate / old NSEnumerator * enumerator = [ thepeople objectEnumerator ]; Person * p;   while (( p = [ enumerator next object] )! = nil ) {   NSLog (@ " % @ is% i years old. " [ P name], [ p age] ); } / Iterate / alternative for (int i = 0; i < [ thepeople count]; i ) {   Person * p = [ thepeople objectAtIndex: i];   NSLog (@ " % @ is% i years old. " [ P name], [ p age] ); } / New iterate / for ( Person * p in thepeople ) {   NSLog (@ " % @ is% i years old. " [ P name], [ p age] ); } Compared to other programming

C

Although both languages ​​in C have a common ancestor, resulting in particular from the late-binding and the possibility of classes and messages at run time to create, significant conceptual differences.

Functionality expansion

Objective- C offers classes at a possible solution. This subsequently the methods set is expanded to a class.

613258
de