Objective-C Object Oriented Programming By Shashank Chaturvedi   IIIT-B
History It was created primarily by  Brad Cox  and  Tom Love in early 80’s at company name StepStone.  Both had been introduced to SmallTalk while at ITT Corporation Programming Technology Center in 1981. Brad  and  Tom  Recognized that SmallTalk would be invaluable in building Development environment for system developer at ITT’s. Backward Compatibility with C was critically important in ITT’s  Telecom Engg.
History  (Continued…) Love  joined Schlumberger Research and in 1982 he acquire the first commercial copy of SmartTalk-80 in the company . Love  and  Cox  later formed new venture to commercialize their product which coupled Objective-C compiler with class libraries. In between  Steve Jobs  left Apple Inc. and started the company NexT in 1988 and Licensed Objecive-C from StepStone. NexT was later acquired by Apple Inc. in 1996, And used Objective-C in their new OS name  MAC OS X
Why Objective-C? C is a procedural language, functions and data are separate. C is also called static language. All functions have to exist before you call. All the variable have to be of specific type. There is no Runtime Checking.
Basic – C Language C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972.  It was designed and written by a man named Dennis Ritchie. C had the seeds of Object Oriented concept with structure.  Each structure definition is a template for a certain kind of thing.
Basic – C Language  (Continued…) Structure Definition # include <  stdio.h  >  Struct  xyz { char*  title; int  length; }  x1 ; Void main() { x1 .length =10; x1 .title = “ Hello World ”; }
What is Objective-C? Objective-C is implemented as set of extensions to the C language. Objective-C incorporates C, you get all the benefits of C when working within Objective-C.  It's designed to give C a full capability for object-oriented programming, and to do so in a simple and straightforward way. Its additions to C are few and are mostly based on Smalltalk, one of the first object-oriented programming languages. Objective-C is the most dynamic of the object-oriented languages based on C. Most decisions are made at run time
What is Object Oriented ? Object-oriented programs are built around  objects .  An object associates data with the particular operations that can use or affect that data.  In Objective-C, these operations are known as the object’s methods; the data they affect are its instance variables  An object bundles a data structure (instance variables) and a group of procedures (methods) into a self-contained programming unit.
Object Oriented Concepts  CLASS DEFINATION Done in two files. First file have Class Declaration also known as Interface, and saved with “ .h ” extension. Second file have class methods implementation known as Implementation, saved with “ .m ” extension. Three access mechanism is permitted “ Public, Private, Protected ” By default everything is  protected.
Object Oriented Concepts  (Continued…) Class Declaration (  xyz. h  ) # import < Cocoa/Cocoa.h> @ interface  XYZ  : NSobject { id test; int test1; } - ( void )  InstanceMethod; + ( void )  ClassMethod; @ end
Object Oriented Concepts  (Continued…) Class Implementation (  xyz .m  ) # import “ xyz.h ” @ Implementation  XYZ + ( void )  ClassMethod { printf ( “I am ClassMethod” );  } - ( void )  InstanceMethod { printf ( “Hello World” );   } @ end
Object Oriented Concepts  (Continued…)   Program Execution  Main.m # import “ xyz.h ” #  import  < stdio.h > void main(int argc, const char*argv[]) {  xyz* Myobject = [xyz new]; [Myobject InstanceMethod];  [xyz ClassMethod]; }
Creating Class Object ClassName*   ObjectName  = [ ClassName  new];  for e.g : -  NSString*   mystring  = [  NSString  new]; NSString*   mystring  =@”  Hello World ”; ClassName*   ObjectName  =  [ ClassName alloc ]   ; ClassName*   ObjectName  = [  [ ClassName alloc ]   init ]; Where “  init  ” is default constructor inherited from root class . &quot; new &quot; is not a keyword in Objective-C, but NSObject implements a class method  &quot; new &quot; which simply calls &quot;alloc&quot; and &quot;init&quot;  We can call methods on classes too, for creating objects. NSString*   mystring  = [  NSString  string];  //  this is more convenient automatic style, Autorelease object created.
Object lifetime / Memory management In any program, it is important to ensure that objects are deallocated when they are no longer needed, otherwise your application’s memory footprint becomes larger than necessary. Objective-C offers two mechanisms for memory management that allow you to meet these goals. Reference counting :-   where you are ultimately responsible for determining the lifetime of objects, Each part of the application keeps track of only its own references for an object rather than total use throughout the entire application. Objective-C and most other object oriented languages always has an initialization method. Initialization method is created to setup default values for things.  For example :- -init {  if ( self = [ super init ] ) title = “Untitled Photo” return self; }
Object lifetime / Memory management The counterpart to initialization method is a “cleanup” method  which is created to cleanup memory for any data or to display  message on console.  For example :- - dealloc {  [ super dealloc ];  [ Object release ] ;   printf ( “Deallocating Photo\n” );    } . Every Object has retain count, which counts how many other objects want to keep that object. Retain count must be maintained in the code. [ Object  retain  ];   //  increment count [ Object  release  ];   //  decrement count Objective-C runtime takes responsibility for freeing the memory when all of the references are released i.e. retain count reaches to Zero.
Object lifetime / Memory management NSString*   mystring  = [  NSString  alloc ] init ];  //  memory allocation, increase the retain count by +1 [ mystring release ];  //  releasing the references, Decrease the retain count by -1 We can use autorelease to save manual retain release of object. ClassName*   ObjectName  =  [  [ ClassName alloc ]  autorelease ] ; num of alloc + retains = num of release + autorelease Garbage collection :-   where you pass responsibility for determining the lifetime of objects to an automatic “collector.”  NSString*   mystring  = [  NSString  string];
Class constructor/Destructor Constructors in Objective-C are technically just &quot;init&quot; methods, they aren't a special construct like they are in C++ and Java.  The default constructor is -(id)  init   { self = [super init]; return self; } ;  Similar to Java, Objective-C only has one parent class.  Accessing it's super constructor is done through [super init]  and this is required for proper inheritance.  This returns an instance which you assign to another new keyword, self. Self is similar to this in Java and C++.  If ( self ) is the same as if ( self != nil ) to make sure that the super constructor successfully returned a new object. nil is Objective-C's form of NULL from C/C++. This is gotten from including NSObject.
Constructor/Destructor declaration   User define constructor should be declared in “ .h ” file as -( XYZ  * ) initWithNumerator:  (int) n  denominator:  (int) d ;  Constructor defination is in “ .m ” file as   -( XYZ  * ) initWithNumerator:  (int) n  denominator:  (int) d {  self  = [super init];  if ( self ) {  [ self  setNumerator: n andDenominator: d];  }  return  self ;  }  Destructor method is called when object is deleted. It releases all the instance variables of the class. - dealloc {  [ super dealloc ];  [ Object release ] ;   printf ( “Deallocating Photo\n” );    }
Types of Methods Two types of Methods are there  Class Methods  and  Instance Method . Class Method :  Begin with  “+”  operator, it called on  class itself.  +(void) Init for e.g. :-  [ClassName Method]  // Method call [ XYZ  init  ]   Instance Method :  Begin with  “-”  operator, it called on class object instance. –(void) Display for e.g. :-  ClassName*   ObjectName  = [ ClassName  new];   [ ObjectName  Display ];  // Method call
Types of Methods   (Continued…) Method can have multiple parameter / inputs for e.g. :-  -(void)  WritetoFile :  (NSString*) Str   Automatically :  (BOOL) flag  ); // calling this  method [MyObject  WritetoFile :  “Hello World ”   Automatically :  true ]; Method can return value for e.g. :-   Mydigit  = [  MyObject   Method ];
Inheritance Root class is NSObject, Every class inherit from this class. Like java, Objective-C also doesn’t permit multiple Inheritance. # import  “  xyz.h  “ @ interface  ABC  :  XYZ {   int test2; // test1, test  ( inherited version ) }   - ( void )  Display; //  - ( void )  InstanceMethod  ( inherited version) @ end
Inheritance  (Continued…) Instance Variables:   The object of class  ABC  contains not only the instance variables that were defined for its class, but also the instance variables defined for its Superclass  XYZ , all the way back to the root class NSObject. Methods:   An object has access not only to the methods that were defined for its class, but also to methods defined for its Superclass. Method Overriding:   Implement a new method with the same name as one defined in a class farther up the hierarchy. The new method overrides the original; instances of the new class will perform it rather than the original.
Polymorphism Each object has define its own method but for different class, they can have the same method name which has totally different meaning. The two different object can respond differently to the same message. Together with dynamic binding, it permits you to write code that might apply to any number of different kinds of objects, without your having to choose at the time you write the code what kinds of objects they might be.
Threading Objective-C supports multithreading in applications. Objective-C provides support for thread synchronization. The @synchronized()directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the @synchronized() block.  The @synchronized() directive takes as its only argument any Objective-C object, including self. This object is known as a  mutual exclusion semaphore  or  mutex . It allows a thread to lock a section of code to prevent its use by other threads
Exception Handling The Objective-C language has an exception-handling syntax similar to that of Java and C++. An exception is a special condition that interrupts the normal flow of program execution.  Objective-C exception support involves four compiler directives:  @try, @catch, @throw, and @finally :  1)  Code that can potentially throw an exception is enclosed in a @try{} block.  2)  A @catch{} block contains exception-handling logic for exceptions thrown in a  @try{} block. You can have multiple @catch{} blocks to catch different types of  exception. (For a code example, see  “Catching Different Types of Exception.” ) 3)  You use the @throw directive to throw an exception, which is essentially an  Objective-C object. You typically use an NSException object, but you are not  required to. 4)  A @finally{} block contains code that must be executed whether an exception is  thrown or not.
Exception Handling  (Continued…) Cup *cup = [[Cup alloc] init]; @try  { [cup fill]; } @catch  (NSException *exception) { NSLog(@&quot;main: Caught %@: %@&quot;, [exception name],  [exception reason]); } @finally  { [cup release]; } Throwing Exceptions NSException  *exception = [ NSException  exceptionWithName: @&quot;HotTeaException&quot;   reason: @&quot;The tea is too hot&quot;userInfo: nil]; @throw  exception;
Objective-C  Vs  C++ C++ supports multiple Inheritance, where as Objective-C doesn’t. By default C++ supports Compile time binding, where as Objective-C supports runtime binding. In C++ there is no Root Class concept. In C++ we issue order while calling Methods, Where as in  Object . Method() ; Objective-C we pass requesting message to Methods.  [ Object  Method  ]
Example access.h #import <Foundation/NSObject.h> @interface Access: NSObject  {  @public int publicVar;  @private int privateVar;    int privateVar2;  @protected int protectedVar;  }  @end
Example  (Continued…) access.m   #import &quot;Access.h&quot;  @implementation Access  { } @end
Example  (Continued…) main.m #import &quot;Access.h&quot;  #import <stdio.h>  int main( int argc, const char *argv[] )  {  Access *a = [ Access new ];  // works a->publicVar = 5;  printf( &quot;public var: %i\n&quot;, a->publicVar );  //  doesn't compile  //  a->privateVar = 10;  //  printf( &quot;private var: %i\n&quot;, a->privateVar );  [a release];  return 0;  }
References www.wikipedia.org   www.apple.com http://www.otierney.net/objective-c.html
THANK YOU !!!

Objective c

  • 1.
    Objective-C Object OrientedProgramming By Shashank Chaturvedi IIIT-B
  • 2.
    History It wascreated primarily by Brad Cox and Tom Love in early 80’s at company name StepStone. Both had been introduced to SmallTalk while at ITT Corporation Programming Technology Center in 1981. Brad and Tom Recognized that SmallTalk would be invaluable in building Development environment for system developer at ITT’s. Backward Compatibility with C was critically important in ITT’s Telecom Engg.
  • 3.
    History (Continued…)Love joined Schlumberger Research and in 1982 he acquire the first commercial copy of SmartTalk-80 in the company . Love and Cox later formed new venture to commercialize their product which coupled Objective-C compiler with class libraries. In between Steve Jobs left Apple Inc. and started the company NexT in 1988 and Licensed Objecive-C from StepStone. NexT was later acquired by Apple Inc. in 1996, And used Objective-C in their new OS name MAC OS X
  • 4.
    Why Objective-C? Cis a procedural language, functions and data are separate. C is also called static language. All functions have to exist before you call. All the variable have to be of specific type. There is no Runtime Checking.
  • 5.
    Basic – CLanguage C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. C had the seeds of Object Oriented concept with structure. Each structure definition is a template for a certain kind of thing.
  • 6.
    Basic – CLanguage (Continued…) Structure Definition # include < stdio.h > Struct xyz { char* title; int length; } x1 ; Void main() { x1 .length =10; x1 .title = “ Hello World ”; }
  • 7.
    What is Objective-C?Objective-C is implemented as set of extensions to the C language. Objective-C incorporates C, you get all the benefits of C when working within Objective-C. It's designed to give C a full capability for object-oriented programming, and to do so in a simple and straightforward way. Its additions to C are few and are mostly based on Smalltalk, one of the first object-oriented programming languages. Objective-C is the most dynamic of the object-oriented languages based on C. Most decisions are made at run time
  • 8.
    What is ObjectOriented ? Object-oriented programs are built around objects . An object associates data with the particular operations that can use or affect that data. In Objective-C, these operations are known as the object’s methods; the data they affect are its instance variables An object bundles a data structure (instance variables) and a group of procedures (methods) into a self-contained programming unit.
  • 9.
    Object Oriented Concepts CLASS DEFINATION Done in two files. First file have Class Declaration also known as Interface, and saved with “ .h ” extension. Second file have class methods implementation known as Implementation, saved with “ .m ” extension. Three access mechanism is permitted “ Public, Private, Protected ” By default everything is protected.
  • 10.
    Object Oriented Concepts (Continued…) Class Declaration ( xyz. h ) # import < Cocoa/Cocoa.h> @ interface XYZ : NSobject { id test; int test1; } - ( void ) InstanceMethod; + ( void ) ClassMethod; @ end
  • 11.
    Object Oriented Concepts (Continued…) Class Implementation ( xyz .m ) # import “ xyz.h ” @ Implementation XYZ + ( void ) ClassMethod { printf ( “I am ClassMethod” ); } - ( void ) InstanceMethod { printf ( “Hello World” ); } @ end
  • 12.
    Object Oriented Concepts (Continued…) Program Execution Main.m # import “ xyz.h ” # import < stdio.h > void main(int argc, const char*argv[]) { xyz* Myobject = [xyz new]; [Myobject InstanceMethod]; [xyz ClassMethod]; }
  • 13.
    Creating Class ObjectClassName* ObjectName = [ ClassName new]; for e.g : - NSString* mystring = [ NSString new]; NSString* mystring =@” Hello World ”; ClassName* ObjectName = [ ClassName alloc ] ; ClassName* ObjectName = [ [ ClassName alloc ] init ]; Where “ init ” is default constructor inherited from root class . &quot; new &quot; is not a keyword in Objective-C, but NSObject implements a class method &quot; new &quot; which simply calls &quot;alloc&quot; and &quot;init&quot; We can call methods on classes too, for creating objects. NSString* mystring = [ NSString string]; // this is more convenient automatic style, Autorelease object created.
  • 14.
    Object lifetime /Memory management In any program, it is important to ensure that objects are deallocated when they are no longer needed, otherwise your application’s memory footprint becomes larger than necessary. Objective-C offers two mechanisms for memory management that allow you to meet these goals. Reference counting :- where you are ultimately responsible for determining the lifetime of objects, Each part of the application keeps track of only its own references for an object rather than total use throughout the entire application. Objective-C and most other object oriented languages always has an initialization method. Initialization method is created to setup default values for things. For example :- -init { if ( self = [ super init ] ) title = “Untitled Photo” return self; }
  • 15.
    Object lifetime /Memory management The counterpart to initialization method is a “cleanup” method which is created to cleanup memory for any data or to display message on console. For example :- - dealloc { [ super dealloc ]; [ Object release ] ; printf ( “Deallocating Photo\n” ); } . Every Object has retain count, which counts how many other objects want to keep that object. Retain count must be maintained in the code. [ Object retain ]; // increment count [ Object release ]; // decrement count Objective-C runtime takes responsibility for freeing the memory when all of the references are released i.e. retain count reaches to Zero.
  • 16.
    Object lifetime /Memory management NSString* mystring = [ NSString alloc ] init ]; // memory allocation, increase the retain count by +1 [ mystring release ]; // releasing the references, Decrease the retain count by -1 We can use autorelease to save manual retain release of object. ClassName* ObjectName = [ [ ClassName alloc ] autorelease ] ; num of alloc + retains = num of release + autorelease Garbage collection :- where you pass responsibility for determining the lifetime of objects to an automatic “collector.” NSString* mystring = [ NSString string];
  • 17.
    Class constructor/Destructor Constructorsin Objective-C are technically just &quot;init&quot; methods, they aren't a special construct like they are in C++ and Java. The default constructor is -(id) init { self = [super init]; return self; } ; Similar to Java, Objective-C only has one parent class. Accessing it's super constructor is done through [super init] and this is required for proper inheritance. This returns an instance which you assign to another new keyword, self. Self is similar to this in Java and C++. If ( self ) is the same as if ( self != nil ) to make sure that the super constructor successfully returned a new object. nil is Objective-C's form of NULL from C/C++. This is gotten from including NSObject.
  • 18.
    Constructor/Destructor declaration User define constructor should be declared in “ .h ” file as -( XYZ * ) initWithNumerator: (int) n denominator: (int) d ; Constructor defination is in “ .m ” file as -( XYZ * ) initWithNumerator: (int) n denominator: (int) d { self = [super init]; if ( self ) { [ self setNumerator: n andDenominator: d]; } return self ; } Destructor method is called when object is deleted. It releases all the instance variables of the class. - dealloc { [ super dealloc ]; [ Object release ] ; printf ( “Deallocating Photo\n” ); }
  • 19.
    Types of MethodsTwo types of Methods are there Class Methods and Instance Method . Class Method : Begin with “+” operator, it called on class itself. +(void) Init for e.g. :- [ClassName Method] // Method call [ XYZ init ] Instance Method : Begin with “-” operator, it called on class object instance. –(void) Display for e.g. :- ClassName* ObjectName = [ ClassName new]; [ ObjectName Display ]; // Method call
  • 20.
    Types of Methods (Continued…) Method can have multiple parameter / inputs for e.g. :- -(void) WritetoFile : (NSString*) Str Automatically : (BOOL) flag ); // calling this method [MyObject WritetoFile : “Hello World ” Automatically : true ]; Method can return value for e.g. :- Mydigit = [ MyObject Method ];
  • 21.
    Inheritance Root classis NSObject, Every class inherit from this class. Like java, Objective-C also doesn’t permit multiple Inheritance. # import “ xyz.h “ @ interface ABC : XYZ { int test2; // test1, test ( inherited version ) } - ( void ) Display; // - ( void ) InstanceMethod ( inherited version) @ end
  • 22.
    Inheritance (Continued…)Instance Variables: The object of class ABC contains not only the instance variables that were defined for its class, but also the instance variables defined for its Superclass XYZ , all the way back to the root class NSObject. Methods: An object has access not only to the methods that were defined for its class, but also to methods defined for its Superclass. Method Overriding: Implement a new method with the same name as one defined in a class farther up the hierarchy. The new method overrides the original; instances of the new class will perform it rather than the original.
  • 23.
    Polymorphism Each objecthas define its own method but for different class, they can have the same method name which has totally different meaning. The two different object can respond differently to the same message. Together with dynamic binding, it permits you to write code that might apply to any number of different kinds of objects, without your having to choose at the time you write the code what kinds of objects they might be.
  • 24.
    Threading Objective-C supportsmultithreading in applications. Objective-C provides support for thread synchronization. The @synchronized()directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the @synchronized() block. The @synchronized() directive takes as its only argument any Objective-C object, including self. This object is known as a mutual exclusion semaphore or mutex . It allows a thread to lock a section of code to prevent its use by other threads
  • 25.
    Exception Handling TheObjective-C language has an exception-handling syntax similar to that of Java and C++. An exception is a special condition that interrupts the normal flow of program execution. Objective-C exception support involves four compiler directives: @try, @catch, @throw, and @finally : 1) Code that can potentially throw an exception is enclosed in a @try{} block. 2) A @catch{} block contains exception-handling logic for exceptions thrown in a @try{} block. You can have multiple @catch{} blocks to catch different types of exception. (For a code example, see “Catching Different Types of Exception.” ) 3) You use the @throw directive to throw an exception, which is essentially an Objective-C object. You typically use an NSException object, but you are not required to. 4) A @finally{} block contains code that must be executed whether an exception is thrown or not.
  • 26.
    Exception Handling (Continued…) Cup *cup = [[Cup alloc] init]; @try { [cup fill]; } @catch (NSException *exception) { NSLog(@&quot;main: Caught %@: %@&quot;, [exception name], [exception reason]); } @finally { [cup release]; } Throwing Exceptions NSException *exception = [ NSException exceptionWithName: @&quot;HotTeaException&quot; reason: @&quot;The tea is too hot&quot;userInfo: nil]; @throw exception;
  • 27.
    Objective-C Vs C++ C++ supports multiple Inheritance, where as Objective-C doesn’t. By default C++ supports Compile time binding, where as Objective-C supports runtime binding. In C++ there is no Root Class concept. In C++ we issue order while calling Methods, Where as in Object . Method() ; Objective-C we pass requesting message to Methods. [ Object Method ]
  • 28.
    Example access.h #import<Foundation/NSObject.h> @interface Access: NSObject { @public int publicVar; @private int privateVar; int privateVar2; @protected int protectedVar; } @end
  • 29.
    Example (Continued…)access.m #import &quot;Access.h&quot; @implementation Access { } @end
  • 30.
    Example (Continued…)main.m #import &quot;Access.h&quot; #import <stdio.h> int main( int argc, const char *argv[] ) { Access *a = [ Access new ]; // works a->publicVar = 5; printf( &quot;public var: %i\n&quot;, a->publicVar ); // doesn't compile // a->privateVar = 10; // printf( &quot;private var: %i\n&quot;, a->privateVar ); [a release]; return 0; }
  • 31.
    References www.wikipedia.org www.apple.com http://www.otierney.net/objective-c.html
  • 32.