Objective C 2.0 Programming Language. Final Exam C SC 520 (Principles of Programming Languages)

Similar documents
INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Object Oriented Programming and the Objective-C Programming Language 1.0. (Retired Document)

Java Interview Questions and Answers

iphone Objective-C Exercises

The C Programming Language course syllabus associate level

Objective C and iphone App

Objective-C and Cocoa User Guide and Reference Manual. Version 5.0

Glossary of Object Oriented Terms

Fundamentals of Java Programming

iphone SDK Enrolled students will be invited to developer program Login to Program Portal Request a Certificate Download and install the SDK

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Java CPD (I) Frans Coenen Department of Computer Science

History OOP languages Year Language 1967 Simula Smalltalk

Evolution of the Major Programming Languages

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

C++ INTERVIEW QUESTIONS

Description of Class Mutation Mutation Operators for Java

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 1. Dr. Chris Irwin Davis Phone: (972) Office: ECSS CS-4337 Organization of Programming Languages

MA-WA1920: Enterprise iphone and ipad Programming

Creating a Custom Class in Xcode

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Stack Allocation. Run-Time Data Structures. Static Structures

Inside Mac OS X. The Objective-C Programming Language

A Comparison of Programming Languages for Graphical User Interface Programming

CS 111 Classes I 1. Software Organization View to this point:

Introduction to Object-Oriented Programming

Building Applications Using Micro Focus COBOL

CS506 Web Design and Development Solved Online Quiz No. 01

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages

Introduction to Objective-C. Kevin Cathey

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Object Oriented Design

1. Overview of the Java Language

ios Development Tutorial Nikhil Yadav CSE 40816/60816: Pervasive Health 09/09/2011

UNIVERSITY OF CALIFORNIA BERKELEY Engineering 7 Department of Civil and Environmental Engineering. Object Oriented Programming and Classes in MATLAB 1

Java Programming Language

VB.NET - CLASSES & OBJECTS

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Jonathan Worthington Scarborough Linux User Group

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

OpenCL Static C++ Kernel Language Extension

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

C Compiler Targeting the Java Virtual Machine

Advanced compiler construction. General course information. Teacher & assistant. Course goals. Evaluation. Grading scheme. Michel Schinz

Approach of Unit testing with the help of JUnit

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Managing Variability in Software Architectures 1 Felix Bachmann*

Java Application Developer Certificate Program Competencies

Lab Experience 17. Programming Language Translation

PART IV Performance oriented design, Performance testing, Performance tuning & Performance solutions. Outline. Performance oriented design

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters

This documentation is made available before final release and is subject to change without notice and comes with no warranty express or implied.

An Introduction To UML Class Diagrams Classes

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

Moving from CS 61A Scheme to CS 61B Java

Java (12 Weeks) Introduction to Java Programming Language

In order to understand Perl objects, you first need to understand references in Perl. See perlref for details.

Chapter 1 Fundamentals of Java Programming

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Construction Principles and Design Patterns. Flyweight, Bridge, Builder

Brent A. Perdue. July 15, 2009

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

ios App Development for Everyone

Inheritance in Programming Languages

Part 1 Foundations of object orientation

Object Oriented Software Design II

Compile-time type versus run-time type. Consider the parameter to this function:

Cloud Computing. Up until now

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

The programming language C. sws1 1

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Introduction to Embedded Systems. Software Update Problem

Chapter 13 - Inheritance

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

Praktikum Entwicklung von Mediensystemen mit ios

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

Curriculum Map. Discipline: Computer Science Course: C++

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

A generic framework for game development

Syllabus for CS 134 Java Programming

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

CACHÉ: FLEXIBLE, HIGH-PERFORMANCE PERSISTENCE FOR JAVA APPLICATIONS

Friendship and Encapsulation in C++

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Implementation Aspects of OO-Languages

Transcription:

Objective C 2.0 Programming Language 1 Final Exam C SC 520 (Principles of Programming Languages) Report prepared by: Bhavin Mankad Karthik Ravichandra

2 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 12 13.Comparison with C++ 12 14.References 12

1. History 3 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. In 1986, Cox put much of the description of his new language in a book named Object Oriented Programming, An evolutionary approach. The company started by Steve Jobs, NeXT, licensed from StepStone and released their own version of compiler and APIs in 1988. NeXTStep, their Object Oriented multi-tasking operating system was based on. OpenStep was developed by NeXT in partnership with Sun Microsystems. 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 in the market place today. 2. Design Objectives a. Object Oriented Programming The primary design goal of was Object Oriented Programming. The Object Oriented syntax is much influenced by SmallTalk. b. Simple extension to C The language is a strict super-set of C. Thus it is backward compatible with C. It was designed to add Object Oriented support to C. Only those Object Oriented concepts which were absolutely essential were added into the language. This has made the language much simpler to learn and program in. c. Light Weight The language does not need any run-time platform like Virtual Machine for Java. Language Pre-processor translates this syntax into C source code. The language just adds a SmallTalk style messaging and some syntactical sugar for defining and working with objects in C language s environment. This keeps the language light weight at run time. The language does not have additional syntactical and conceptual quirks like virtual functions, friend functions, templates, multiple inheritance etc in C++.

4 d. Flexibility As 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. 3. Interface and Implementation In Objective C, the code is organized in two types of source files. Interface files declare a class with its instance variables and methods. Implementation files contain the implementation of these methods. The objective behind this separation is to achieve Data Abstraction an important concept in Object Oriented Programming. Interface describes contract for the given class stating which methods (messages) this class is responsible for responding to and what data it holds. This hides the implementation details and exposes only the contract to other classes which use this class. The users of this class don t have to worry about implementation. Thus any updates in a class method s implementation will not affect the user classes. 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 @interface Rectangle : Shape { float length; float width; } + (void)alloc; -(float) setlength: (int)len andwidth: (float) width; @end

5 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 } - (float) setlength: (int)len andwidth: (float) width { // implementation } @end 4. Class and Object 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. Method definitions for a class are provided in an implementation file such as Rectangle.m shown above. Implementation file imports the header file with the statement #import Rectangle.h #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 Instance and Class variables By default, the class has access to all its instances variables. No special access specifiers like a. or is needed. Class variables are declared as static variables. Static variables can not be inherited by sub-classes. These variables retain their values across multiple objects and they can be manipulated by class level methods. Scope of Instance Variables Instance variables have scope of either private, public or protected. They have exactly the same meaning as in other OO languages like Java. Private variables can be accessed only from within the class that defines it, protected

variables by the class it defines and its subclasses and the public variables can be accessed by any class 6 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 id rectangle; //declares a variable called rectangle which can point to an //instance of any class at run time Rectangle *rectangle; //declares a variable called rectangle //which can point to only the //objects of class Rectangle or its subclasses Allocation and Initialization Rectangle *rectangle; rectangle = [Rectangle alloc]; 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 Another important concept of OO programming is implemented using keyword extends as shown in the example below. 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

template. This template defines the offsets of variables and methods into memory and code section of a program respectively. 7 @ interface Rectangle : Shape @end //declarations here Rectangle class template Method 1 Offset Method2 Offset Method3 Offset 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 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. 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. Parent *parent = [[Child alloc] init]; id obj = [[SomeClass alloc] init]; Dynamic binding Dynamic typing facilitates binding of methods with the objects at runtime. A variable can point to any object at run time and therefore a method is bound to the class only at run time. As shown in example below a receiver can be of any class type at runtime and therefore which amethod to invoke is decided only at runtime. [receiver amethod] Dynamic loading runtime can dynamically load classes while a program is running. It is possible to create methods on the fly and load them to the program at runtime. These features adds flexibility to programs. All the modules do not have to be statically loaded at compile time. Modules can be loaded as and

when needed. Also, a developer need not have classes written by other developers at compile time. The interface can be negotiated between developers and classes can be loaded at runtime when needed. 7. Messaging In Objective C s terminology, methods belonging to classes are called messages and calling methods is termed as passing messages. 8 [rectangle init] [rectangle initwithlength: 80 andwidth: 90]; //No arguments //With two arguments As shown in figure 7, we are passing init message to a rectangle object. In the first case, the message is passed without any arguments. In the second case message is passed with two arguments; Length and width. The name of the implemented method in Rectangle class is - (void) initwithlength: (float) len andwidth: (float) width; Dynamic Binding of method The messages are bound to the objects at runtime. Internally, message passing is converted into a call to a routine named objc_msgsend (receiver, selector, ). This routine is called at runtime with at least two arguments. receiver is the object that is passed the message to and selector is the name of the message (method). Implementation detail of message passing When a message is sent to an object, it follows isa field of the object to locate the class template. Once it has the correct class template it locates the current message in the method offset table and finds its offset into the code section. It then moves the program counter to that instruction and starts executing the method. 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. Program can implement a forwardinvocation: method to give a default response to the message, or to avoid the error in some other way. As its name implies; forwardinvocation: is commonly used to forward the message to another object if the receiver object does not want to handle that message.

8. Exception Handling 9 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. 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" @interface ClassName ( CategoryName ) // method declarations @end As we see above, the declaration of a category is very similar to a class interface declaration, except that a "Category name" is listed after the class name. Once declared, the implementation is defined as: #import "CategoryName.h" @implementation ClassName ( CategoryName ) // method definitions @end Once new methods are added to a class through categories, all the subclasses 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

existing class, the only ones to be recompiled are those new methods that we added. 10. Properties Properties is another useful feature that was introduced as part of Objective- C 2.0. As we have seen earlier, the standard way of accessing class variable is through messages. Properties provide a concise means of accessing class variables. Properties can be accessed using the dot-syntax. There are 2 parts to using Properties - Declaration and Implementation. Properties are declared with the help of the @property compiler directive. The property implementation uses the @synthesize and @dynamic directives to tell the compiler how to handle the actions associated with a property. 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. Properties also allow the programmer to associate readwrite and readonly attributes with a class variable. Below is an example, which illustrates the use of Properties in. @interface Square : NSObject{... @property(readwrite) int size;... } @implementation Square : NSObject... @synthesize size; } 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 Square*sq = [[Square alloc] init]; sq.size = 10; // This is the equivalent of saying [sq setsize: 10] 11. Memory Management provides two options for memory management. Until the 2.0 version, the memory had to be managed manually by the programmer. has compiler directives like "release", "retain", "autorelease" that we will discuss below, to help the programmer manage memory. With 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. 10

11 uses a reference counting mechanism to keep track of the liveness of an object. This count is called the retaincount. When an object is allocated, using the alloc method, the retaincount is set to 1. A release method is used to decrement the retaincount by 1. When the retaincount reaches 0, the object is dealloced. If the object is referenced in the program, the programmer can indicate this to the compiler using the retain message. The retain message will increment the retaincount by 1. Consider the example below: Rectange *rect = [[Rectangle alloc] init]; // retaincount is 1. Rectangle *tmprect = rect; [rect retain] // Now there is another reference to rect. // So we increment the retaincount [rect release] [tmprect release] // the retaincount is now 0 and dealloc is called. The retaincount of an object can be obtained by passing it a "retaincount" message. The autorelease message is similar to release, except that it defers the release of the object to a later point in time. autorelease is generally used in conjunction with Autorelease Pools. These pools contain other objects that have received an "autorelease" message. Thus sending an autorelease to an object instead of a release extends the lifetime of the object till the Pool itself is released. An autorelease pool is created as an instance of a NSAutoreleasePool Object. Consider the example below: NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; Rectangle *rect; for (i=0;i <10; ++i){ rect = [[Rectangle alloc] init]; [rect autorelease]; } [pool 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 [[tmpa setnext] tmpb] // tmpa->next = tmpb [tmpb retain] // increment number of references to B. [[tmpb setnext] tmpa] // tmpb->next = tmpa [tmpa retain] // increment number of references to A. 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

from the root set. So, ideally these objects must be released. But the reference counting mechanism fails to address this scenario. 12 12. Interesting Facts about Interest in is still very much alive due to Apple s endorsement of the language. Games like NuclearAttack and Quake are developed in. Today there are four major compilers: Stepstone, GNU, Apple and Portable Object Compiler (POC). o Stepstone and POC are preprocessors that that generate C code which is then compiled. o GNU and Apple act like compilers by creating intermediate code for the GNU code generator directly from the source. An class allows a method and a variable with the exact same name. The language also allows same name for a class and an instance method. 13. Comparison with C++ Features Objective C C++ Binding Dynamic Static Modifying a Class Subclassing and Categories Only Subclassing Operator Overloading No Yes Templates Not Needed because of Dynamic Yes Binding Namespace No Yes Inheritance Single Multiple Language Complexity Only a few syntactical additions to C Lot of additions to C like virtual and friend functions, templates etc. Reflection In-built support for reflection No in-built support Typing Dynamic Static Influenced By SmallTalk and C Simula and C Compiler Pre-processed or Compiled Compiled 14. References a. The Programming Language 2.0. Cocoa framework from Apple Inc. http://developer.apple.com/documentation/cocoa/conceptual/objectivec/ob jc.pdf b. Memory Management Guide for. Cocoa Guide http://developer.apple.com/documentation/cocoa/conceptual/memorymgmt/ MemoryMgmt.pdf c. Beginner s Guide to http://www.otierney.net/objective-c.html d. Wikipedia Article http://en.wikipedia.org/wiki/