Introduction to Interfaces in Objective C, the iPhone Programming Language

Introduction

Objective C is the primary language used for programming applications for Mac OS X and iPhone. The language is a hybrid mix of the Smalltalk and C programming languages. Simply summarized, Objective C adds object oriented concepts to the C programming language, but it has a dramatically different syntax than C++.

This article is a simple introduction to defining objects using Objective C. It approaches from a C++ viewpoint, assuming that you are already familiar with the concepts of C++.

Basic Vocabulary

Interface - An Objective C object. In C++ an interface would be called a class.
Method - A support routine for manipulating or retrieving information about an interface.
Message - A request that a method be performed on an interface.

The Differences Between C++ and Objective C

Both C++ and Objective C are based on the concept of objects, specialized data types that associate data with the the "verbs" or "methods" for manipulating or using the data.

The difference between C++ and Objective C begins with how the code interacts with the object. In C++, code interacts with an object by calling a special function that is attached to the class. This function is usually an integral part of the class, and must exist in some form for the code to run.

However, in Objective C, code does not "call" a method of an object. Rather it "sends a message." The difference between these techniques means that when C++ code is compiled, a function call such as:

myClass->classMethod(methodParameter);

is automatically converted into assembly code which calls a specific function stored at a specific location in memory. This obviously does not take into account the advanced concepts of runtime binding and polymorphism, but from the simple view, most class method calls are set up at compile time, not at run time.

In contrast, Objective C passes a message to the object such as:

[myClass classMethod:methodParameter];

The object "myClass" receives the message "classMethod" with the parameter "methodParameter." In Objective C the class myClass interprets the message at runtime, and if it is able to handle the message "classMethod" it responds by calling the method for handling that message, otherwise it returns null if that method is not set up.

The message passing system is therefore typefree. This means you can send any object the "classMethod" message even if the method for handling that message is not defined. Only the objects that can handle that message will respond. The others will simply return null, and this will not crash the program.

Polymorphism is built in, and each object is designed from the start to be part of a great object tree which can easily be expanded or extended with a minimum of effort. In this respect Objective C can make it easier for groups of programmers to work together on a large project. If the code for handling something isn't set up for an object yet, that is no problem. The programmer can still refer to interfaces using that message, and later another programmer can simply add code for handling that message to the interface.

There is a definite speed sacrifice though. According to some sources, an Objective C message has three times as much overhead as a virtual C++ function call.

Defining an Objective C Interface

In Objective C an object class is called an interface. The variables associated with the interface are contained within the parentheses, but the methods are declared outside of the parentheses, yet still inside the structure formed by an opening @interface and a closing @end.

@interface objectClass : parentClass
{
//instance variables associated with this class.
}

+method1;
+(return_type)method2;
+(return_type)method3:(param1_type)parameter_varName;

-(return_type)instanceMethod:(param1_type)param1_varName :(param2_type)param2_varName;
-(return_type)instanceMethodWithParameter:(param1_type)param1_varName andOtherParameter:(param2_type)param2_varName;
@end

There are two types of methods that can be defined for an Objective C instance. Methods defined using the plus sign (+) are class methods, meaning that they operate on all instances of the interface. Class methods therefore have no access to any specific instance variables defined in the interface. Methods defined using the negative sign (-) are instance methods, meaning that they operate on a specific instance of the interface. They have access to the variables associated to the instance of the interface they are a part of.

An equivalent C++ class representation of the above Objective C interface might be:
class objectClass : parentClass
{
//instance variables associated with this class.

static void method1();
static return_type method2();
static return_type method3(param1_type parameter_varName);

return_type instanceMethod(param1_type param1_varName, param2_type param2_varName);
return_type instanceMethodWithParameter(param1_type param1_varName, param2_type param2_varName);
};

Implementing the Methods of an Objective C Interface

Once the Objective C interface is defined you must flesh out the methods that will be used to respond to messages passed to the interface.

Implementation of an interface is very similar to defining the interface. All implementations are contained within an @implementation .... @end block. Before an interface can be implemented it must be imported. This is similar to including a header file that defines a C++ class.

For example, if the above Objective C interface definition was contained in the file "objectClass.h" then implementing the interface objectClass from the source code file would take the following basic structure:
#import "objectClass.h"

@implementation objectClass : parentClass

+method1
{
   //Code statements omitted.
}

+(return_type)method2
{
//Code statements omitted.
}

-(return_type)instanceMethod:(param1_type)param1_varName :(param2_type)param2_varName
{
//Code statements omitted.
}

@end

Messaging an Objective C Interface

Once an Objective C interface is defined and implemented it is ready to be used. Requesting that a method be performed on an interface is just that, a request. Because of dynamic typing, mentioned earlier, there is no guarantee that sending a message to an interface will result in the method being called. If the method is not defined the program will not crash, it simply won't do anything.

Messages are sent to the interface using the code structure:

[myClass instanceMethod:parameter1 :parameter2];

In this example the instanceMethod method defined earlier is called. It has two parameters which are included.

A more complicated example of sending a message to an interface:

[myClass instanceMethodWithParameter:parameter1 andOtherParameter:parameter2];

In this example the message involves two parameters, and there are two parts to the message. It is as if a C++ method function name is broken up, and the parameters are inserted in descriptive locations within the function name.

For example, a practical example might be:

[databaseRecord storeUsersName:nameValue andTelephoneNumber:telephoneValue];

In this way Objective C code has the potential to be much more readable. Sending messages can be much more self-explanatory than a C++ method function call in which it may be hard to remember what each parameter is.

Conclusion

This is only a basic, introductory look at how to define an interface in Objective C. However, this should be enough to help you to read Objective C code and understand what is going on. Do you have any thoughts about the code listed here? Are there any errors or inadequacies that you notice? Please feel free to share your thoughts.

More Helpful Resources on Object C, the iPhone Programming Language:



13 comments:

  1. Note that Objective-C can use C++ too, if you create .mm files instead of .m.

    ReplyDelete
  2. Yes, you are correct. In fact, you can even use C++ classes, calling them from the Objective C code, and vice versa.

    ReplyDelete
  3. nice article , it is easy to understand for newbie

    ReplyDelete
  4. Interfaces aren't Objective-C classes, they only give information about the class. ;-)

    ReplyDelete
  5. Nice one for any beginner like me

    ReplyDelete
  6. good one for begineer :)

    ReplyDelete
  7. Excellent and beginner-friendly article!

    ReplyDelete
  8. This is a GREAT article! Very helpful, i just +1ed it on google ;D

    ReplyDelete
  9. Every time you purchase an iphone 5 on launch date you are telling Apple that you don’t care they are making workers work themselves to death. coques iphone 4

    ReplyDelete
  10. Regarding the speed of Obj-C message sends, Mike Ash tested this (circa 2008) and found that while indeed message sends were slower than C++ virtual methods (sending a message takes ~2x as long as an integer division), IMP-cached message sends were faster; in fact, they're essentially the same cost as a traditional C function call.

    So what is an IMP-cached message? Well, the first time you send a message, the Obj-C runtime has to go through the object hierarchy and find the appropriate reciever, at which point it gets cached (in a per-class table). Essentially you have to pay a higher upfront cost the first time you call a method on a per-class basis, but there is no (reasonably measurable) performance cost over a C function after that initial message send.

    Of course, lets not forget that Obj-C compiles exactly the same as C; all the functionality is provided by the runtime. Every class you write is converted into a struct and every method a regular C function. The runtime just provides a nice way to link everything together.

    Of course, since 2008, both Apple's and GCC's ObjC runtimes have been completely overhauled, so they're likely even faster.

    As a final note, many people seem to confuse Apple's Cocoa framework with Obj-C itself. They're essentially the equivalent of the .NET framework; you must use some of it for certain OS functionality, but there's nothing stopping you from writing your own equivalents or using someone else's. In fact, I develop in Obj-C on Windows, without a single bit of Apple's or GNUSteps frameworks.

    Mike Ash's performance tests: http://www.mikeash.com/pyblog/performance-comparisons-of-common-operations-leopard-edition.html

    ReplyDelete