Objective-C

From Bauman National Library
This page was last modified on 1 June 2016, at 17:02.
Objective-C
Paradigm Reflective, object-oriented, class-based
Designed by Brad Cox and Tom Love
First appeared 1983
Typing discipline dynamic, static, weak
OS Cross-platform
Filename extensions .h, .m, .mm, .C
Website https://developer.apple.com/
Influenced by
C, Smalltalk
Influenced
Java, Nu, Objective-J, TOM, Swift

Objective-C - object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It is the main programming language used by Apple for the OS X and iOS operating systems, and their respective application programming interfaces, Cocoa and Cocoa Touch. Objective-C source code 'implementation' program files usually have .m filename extensions, while Objective-C 'header/interface' files have .h extensions, the same as C header files. Objective-C++ files are denoted with a .mm file extension.

Objective-C characteristics

  1. The class is defined in two different sections namely @interface and @implementation.
  2. Almost everything is in form of objects.
  3. Objects receive messages and objects are often referred as receivers.
  4. Objects contain instance variables.
  5. Objects and instance variables have scope.
  6. Classes hide an object's implementation.
  7. Properties are used to provide access to class instance variables in other classes.

Classes and Objects

The main purpose of Objective-C programming language is to add object orientation to the C programming language and classes are the central feature of Objective-C that support object-oriented programming and are often called user-defined types.

Class definitions

A class definition starts with the keyword @interface followed by the interface name; and the class body, enclosed by a pair of curly braces. In Objective-C, all classes are derived from the base class called NSObject. It is the superclass of all Objective-C classes. It provides basic methods like memory allocation and initialization. For example, we defined the Box data type using the keyword class as follows:

 @interface Box:NSObject
 {
     //Instance variables
     double m_length;   // Length of a box
     double m_breadth;  // Breadth of a box
 }
 @end

The instance variables are private and are only accessible inside the class implementation.

Method definition

The general form of a method definition in Objective-C programming language is as follows:

- (<return_type>) <method_name>:( <argumentType_1> )<argumentName1> 
<joiningArgument2_>:( <argumentType2> )<argumentName_2> 
... 
<joiningArgument_N>:( <argumentType_N> ) <argumentName_N> 
{
   <body of the function>
}

A method definition in Objective-C programming language consists of a method header and a method body. Here are all the parts of a method:

  1. Each method signature starts with either a dash (-) or a plus (+). Dashes are used for instance methods, which are methods you can call on instance variables
  2. Return Type: A method may return a value. The "return_type" is the data type of the value the function returns. Some methods perform the desired operations without returning a value. In this case, the "return_type" is the keyword "void".
  3. Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.
  4. Arguments: A argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method. Arguments are optional; that is, a method may contain no argument.
  5. Joining Argument: A joining argument is to make it easier to read and to make it clear while calling it.
  6. Method Body: The method body contains a collection of statements that define what the method does.

Following is the source code for a method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:

 @interface SampleClass:NSObject
 /* method declaration */
 - (int)max:(int)num1 andNum2:(int)num2;
 @end
 @implementation SampleClass
 - (int) max:(int) num1 secondNumber:(int) num2 
 {
    /* local variable declaration */
    int result;
    if (num1 > num2)
       result = num1;
    else
       result = num2;
    return result; 
 }
 @end

To call a method, you simply need to pass the required parameters along with method name, and if method returns a value, then you can store returned value. For example:

 int ret = [sampleClass max:150 andNum2:200];

Using Objective-C objects

Basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. The properties of objects of a class can be accessed using the direct member access operator (.). Following statements declare two objects of class Box:

 #import <Foundation/Foundation.h>
 @interface Box:NSObject
 {
     double length;   // Length of a box
     double breadth;  // Breadth of a box
     double height;   // Height of a box
 }
 @property(nonatomic, readwrite) double height; // Property
 -(double) volume;
 @end
 @implementation Box
 @synthesize height;
 -(id)init
 {
    self = [super init];
    length = 1.0;
    breadth = 1.0;
    return self;
 }
 -(double) volume
 {
    return length*breadth*height;
 }
 @end
 int main( )
 {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
    Box *box1 = [[Box alloc]init];    // Create box1 object of type Box
    Box *box2 = [[Box alloc]init];    // Create box2 object of type Box
    double volume = 0.0;     // Store the volume of a box here
    // box 1 specification
    box1.height = 5.0; 
    // box 2 specification
    box2.height = 10.0;
    // volume of box 1
    volume = [box1 volume];
    NSLog(@"Volume of Box1 : %f", volume);
    // volume of box 2
    volume = [box2 volume];
    NSLog(@"Volume of Box2 : %f", volume);
    [pool drain];
    return 0;
 }

Properties

Properties are introduced in Objective-C to ensure that the instance variable of the class can be accessed outside the class. The various parts are the property declaration are as follows.

  1. Properties begin with @property, which is a keyword
  2. It is followed with access specifiers, which are nonatomic or atomic, readwrite or readonly and strong, unsafe_unretained or weak. This varies based on the type of the variable. For any pointer type, we can use strong, unsafe_unretained or weak. Similarly for other types we can use readwrite or readonly.
  3. This is followed by the datatype of the variable.
  4. Finally, we have the property name terminated by a semicolon.

Inheritance

Objective-C obviously implements the notion of inheritance, but does not support multiple inheritance.

С++:

 class Foo : public Bar, protected Wiz
 {
 }

Objective-C:

 @interface Foo : Bar 
 {
 }
 @end

An alternative technique must be used to also "inherit" from class Wiz. In C++, a class can be derived from one or several other classes, using public, protected or private mode. In the methods, one can reference a superclass using the scope resolution operator :: (Bar::, Wiz::). In Objective-C, one can derive from one class only, using public mode. A method can reference the superclass with the keyword super, like in Java.

Formal protocol

A formal protocol is a set of methods that must be implemented in any conforming class. A class can conform to an unlimited number of protocols.

C++:

 class MouseListener
 {
     public:
          virtual bool mousePressed(void) = 0; //pure virtual method
          virtual bool mouseClicked(void) = 0; //pure virtual method
 };
 class KeyboardListener
 {
      public:
           virtual bool keyPressed(void) = 0; //pure virtual method
 };
 class Foo : public MouseListener, public KeyboardListener 
 {
      ...
 }

In C++, a protocol is implemented by an abstract class and pure virtual methods. The abstract class in C++ is more powerful than the Objective-C protocol since it can contain data.

Objective-C:

 @protocol MouseListener
      -(BOOL) mousePressed;
      -(BOOL) mouseClicked;
 @end
 @protocol KeyboardListener
      -(BOOL) keyPressed;
 @end
 @interface Foo : NSObject <MouseListener, KeyboardListener>
 {
     ...
 }
 @end

Foo must implement mousePressed, mouseClicked and keyPressed. It can then be used as an event listener for the mouse and the keyboard. In Objective-C, the protocol is a specific concept. The syntax using angular brackets <...> is not linked to the C++ templates, a feature that does not exist in Objective-C.

Advantages and Disadvantages

In C++, a few modifiers can be added to the prototype of a function. None of them exist in Objective-C. Here is the list:

  • const: a method cannot be set const
  • static: making the difference between an instance method and a class method is done through the use of “-” or “+” in front of the prototype
  • virtual: Objective-C methods are virtual, so the keyword is useless. Pure virtual methods are implemented with a formal protocol
  • throw: in C++, one can restrict a method to transmit some exceptions only. This is not possible in Objective-C.
  • friend: There is no friend notion in Objective-C. Indeed, this is rather useful in C++ for the efficiency of overloaded operators, that are not present in Objective-C.
  • References: References (&) do not exist in Objective-C.
  • Inlining: Objective-C does not implement inlining. However, inlining would be very useful for utility functions written in simple C, like max(), min()... This is a problem that Objective-C++ solved.
  • Templates: Objective-C does not implement templates.
  • Operator overloading: Objective-C does not implement operator overloading.

References

  1. Programming with Objective-C
  2. Learn Objective-C in 30 minutes
  3. Pierre Chatelier, From C++ to Objective-C
  4. Objective-C