Objective C 2.0 Programming Language Final Exam CSC520 (Principles of Programming Languages)
Objective C 2.0 Programming Language Final Exam CSC520 (Principles of Programming Languages)
Objective C 2.0
Programming Language
Final Exam
C SC 520
(Principles of Programming Languages)
Table of Content
Page #
1. History 3
2. Design Objectives 3
a. Object Orientation
b. Simple Extension to C, Strict Superset of C
c. Light Weight
d. Flexibility to switch between Structural and Object Oriented
Programming
e. Dynamic Binding
f. Reflection
3. Interface and Implementation 4
4. Class and Object 5
5. Inheritance 6
6. Dynamic Behavior 7
7. Messaging 8
8. Exception Handling 9
9. Categories 9
10.Properties 10
11.Memory Management 10
12.Interesting Facts about Objective-C 12
13.Comparison with C++ 12
14.References 12
With languages like Simula and SmallTalk, the importance of Object Oriented
Programming was becoming apparent in early 1980s. Object Oriented
Programming made development and maintenance of large scale projects a
lot easier as compared to Structured Programming. Also, thinking in Object
Oriented terms was closer to real world situations. Brad Cox, working in a
company called StepStone was much interested in Software Reuse and
Object Oriented development and was greatly influenced by simplicity and
Object Oriented features of SmallTalk. In early 1980s, while working at
StepStone, he incorporated SmallTalk like Object Oriented features to C
compiler and developed a new language called Objective-C. In 1986, Cox put
much of the description of his new language in a book named ‘Object
Oriented Programming, An evolutionary approach’.
Work on GNU’s version of NeXTstep clone started in 1992 and it was given
the name ‘GNUstep’. The first compiler written by Dennis Glatting in 1992
was followed by another version written by Richard Stallman.
After NeXT was acquired by Apple, the OpenStep was used in their operating
system Mac OS-X. Apple’s one of the most important frameworks Cocoa is
developed in OpenStep interface objects. Thus Apple is the single most
influential force behind existence of Objective-C in the market place today.
2. Design Objectives
d. Flexibility
As Objective-C is a strict superset of C, it can support pure structural
programming as well. This gives flexibility to programmers who may want
to use structural programming like C for systems level code and OO
programming for application development.
e. Dynamic Behavior
Objective C is the most dynamic of all OO languages. It defers most of the
decisions till run time. It supports Dynamic Typing, Dynamic Binding and
Dynamic Loading. These concepts are further explained in section 6.
f. Reflection
Objective C supports reflection. It can observe and modify its structure at
runtime using the ‘Class’ object methods and also paradigms like
‘selector’. The concept is similar to Reflection APIs in Java.
Interface
• This declares a class named Rectangle which inherits from the class
Shape
• length and width are instance variables. Instance variables are
declared within {}
• Methods are declared outside the { }
• In Method declaration, (+) means it’s a class method and (–) means it
is an instance method. First ( ) declares return type of the method. For
example (void) or (float). Then comes the method name followed by ‘:’
incase the method has arguments. Arguments follow the ‘:’ with types
given in ( )
Rectangle.h
Implementation
• Implementation file contains definition of methods for the Rectangle
class
• Similar to the interface, (+) shows it is a class method and (–) shows
that it is an instance method
Rectangle.m
#import “Rectangle.h”
@implementation Rectangle
+ alloc
{
implementation
}
Class
These are the building blocks of any Object Oriented language. Objective C
defines classes in the interface header files as explained in the previous
section. For example in the previous section, Rectangle.h file defines a class
named Rectangle. Each class can have instance and class variables and
methods.
#import is different from #include in that it does not import the content of
the header file again if it is already imported unlike include which does not
put such a check
Objects
Classes are instantiated as objects. This is when memory for instance
variables is allocated. Objects are declared either with dynamic or static type.
For example
if (rectangle)
rectangle = [rectangle init];
The code given above shows two important steps in instantiation of objects.
The first line declares an object of type Rectangle class. The next line
allocates memory for this object – in other words actual instantiation
happens here. We send ‘alloc’ message (a method call in other words) to
Rectangle class and it returns a pointer to an object of its type. This object is
then passed a message (message passing explained in later sections) ‘init’
which initializes the instance variables.
5. Inheritance
As figure below shows, Rectangle is the class which inherits from the class
Shape. It provides convenient way of reusing code. All the public and
protected member variables and methods of Shape are now part of Rectangle
too. A class can override a method that belongs to the parent class by
providing its own implementation.
Multiple inheritance is not allowed in this language just like Java and unlike
C++. A class can only inherit from one class. NSObject is the root class of all
the classes. In other words, any class that a user defines, normally derives
from NSObject. It is a base implementation for all objects and provides
important instance variables and methods useful for all the classes that
derive from it. The most basic functionality of NSObject class is to allocate
instances and connecting instances to their classes.
NSObject defines the ‘isa’ instance variable that connects every object with
its class. When an object is allocated, its ‘isa’ is made to point to its class
CS 520: Final Project Report Objective-C
7
template. This template defines the offsets of variables and methods into
memory and code section of a program respectively.
rectangle isa
6. Dynamic Behavior
In languages like C++ and C, many decisions related to types and method
calls are taken at compile time. In Objective-C most of these decisions are
taken dynamically at runtime. This gives a lot of flexibility to programs.
There are mainly three types of dynamic behavior in Objective-C.
Dynamic typing
The class (type) of an object is decided at runtime. The compiler does not
associate an object variable with its class type statically. There are two types
of dynamic typing available. One displayed by Dynamic Polymorphism and
the other displayed by a type called ‘id’. Dynamic polymorphism allows a
variable, at runtime, to point to any object of its own type or any of its
subclass types as shown in the first line in the code below. The second line in
the code shows id type. Here obj is defined as of type ‘id’ and at runtime, it
can point to an object of any class type.
Dynamic binding
Dynamic loading
7. Messaging
Forwarding
Because there is no check at compile time whether an object can respond to
a message passed to it, it is runtime’s responsibility to deal with a situation
when an object is passed a message it doesn’t respond to. In such cases, the
runtime gives an object a chance to decide what to do with such a message
that it has received. It sends the object a forwardInvocation: message with
an NSInvocation object as its argument The NSInvocation object
encapsulates the original message and the arguments.
Exception Handling in Objective C is very similar to C++ and Java. There are
4 compiler directives, @try, @catch, @throw, @finally, which form the crux
of exception handling in Objective-C. Code that could possibly raise an
exception is enclosed in the @try block. The @catch is used to handle the
exception generated in @try block. The @finally block is used for cleanup
immaterial of an exception being raised or not. The @throw block is used to
throw back an exception which can be caught in subsequent @catch blocks.
Since the exception handling is very similar to Java and C++, we will not
discuss this in detail in this report.
9. Categories
Categories are an easy way to add methods to a class, even to the ones to
which you don't have the source. They are a powerful feature of extending
the functionality of a class. In other words, categories can sometimes be a
good alternative to sub-classing, and can avoid sub-classing when it is done
just for the sake of extending a class with new methods. It is important to
note that, you can only add new "methods" to a class. No new instance
variables can be added to a class. The syntax for declaring a Category is:
#import "ClassName.h"
// method declarations
@end
#import "CategoryName.h"
// method definitions
@end
Once new methods are added to a class through categories, all the sub-
classes can now access the new methods as if they were part of the
original class interface.
Categories can also be used to split the implementation of a single huge class
across many source files, and may simplify code management.
Another big advantage of Categories is that, the base class code doesn’t have
to be re-compiled at all. Since, we are only adding new methods to an
CS 520: Final Project Report Objective-C
10
existing class, the only ones to be recompiled are those new methods that
we added.
10. Properties
Properties are declared with the help of the @property compiler directive.
With @synthesize, the compiler will generate the setter and getter methods
for the property. With @dynamic, the programmer will have to supply the
getter and setter methods with the help of getter= and setter= attributes.
The above piece of code, declares "size" as a property, and directs the
compiler to generate the getter and setter methods automatically. Further,
the size variable can now be accessed as
Objective-C provides two options for memory management. Until the 2.0
version, the memory had to be managed manually by the programmer.
Objective-C has compiler directives like "release", "retain", "autorelease" that
we will discuss below, to help the programmer manage memory. With
Objective-C 2.0, the concept of a garbage collector was introduced, which
automates the task of memory management. Garbage Collection uses the
concept of Generation-based collection.
[rect release]
In the above example, the 10 instances of Rectangle are released only when
the pool is released.
One of the biggest disadvantages of reference counting mechanism is the
problem of reference cycles. Consider the example below
Object tmpA has a reference to tmpB, and vice-versa. Hence the retainCount
on both these objects is 1. However, neither of these objects can be reached
CS 520: Final Project Report Objective-C
12
from the root set. So, ideally these objects must be released. But the
reference counting mechanism fails to address this scenario.
14. References