An Objective‐C Primer Babul Mirdha Founder, Meetnar.com www.meetnar.com
An Objective‐C Primer
Babul MirdhaFounder, Meetnar.com
www.meetnar.com
Overview
•Objective‐Cfl i–a reflective,
–object‐oriented programming language–follows ANSI C style codingthat adds Smalltalk style messaging–that adds Smalltalk‐style messaging
–other C programming language.
• Objective‐CObjective C–a thin layer on top of C, and moreover is a strict superset of C;
• it is possible p–to compile any C program with an Objective‐C compiler, –and to freely include C code within an Objective‐C classclass.
• There is no formal written standard– Relies mostly on libraries written by others
• Flexible almost everything is done at runtime.Dynamic Binding– Dynamic Binding
– Dynamic Typing– Dynamic Linking
InventorsInventors
• Objective‐C was invented by two men, Bradj y ,Cox and Tom Love.
• Both were introduced to Smalltalk at ITT in 1981
• Cox thought something like Smalltalk would be very useful to application developersbe very useful to application developers
• Cox modified a C compiler and by 1983 he had a working Object‐oriented extension to Ca working Object oriented extension to C called OOPC.
DevelopmentDevelopment
• Tom Love acquired a commercial copy ofTom Love acquired a commercial copy of Smalltalk‐80 while working for Schlumberger ResearchResearch
• With direct access Smalltalk, Love added more to OOPC making the final product Objectiveto OOPC making the final product, Objective‐C.
I 1986 h l Obj i C h h h i• In 1986 they release Objective‐C through their company “Stepstone”
NeXT and NeXTSTEPNeXT and NeXTSTEP
• In 1988 Steve Jobs acquires Objective‐C q jlicense for NeXT
• Used Objective‐C to build the NeXTSTEPOperating System
• Objective‐C made interface design for NeXTSTEP much easierNeXTSTEP much easier
• NeXTSTEP was derived from BSD Unix• In 1995 NeXT gets full rights to Objective C• In 1995 NeXT gets full rights to Objective‐C from Stepstone
OPENSTEP APIOPENSTEP API
• Developed in 1993 by NeXT and Sunp y• An effort to make NeXTSTEP‐like Objective‐C implementation available to other platforms.
• In order to be OS independent– Removed dependency on Mach Kernel– Made low‐level data into classes
• Paved the way for Mac OS X, GNUstep
Apple and Mac OS XApple and Mac OS X
• NeXT is taken over by Apple in 1996 and put y pp pSteve Jobs and his Objective‐C libraries to work
d d b l• Redesigned Mac OS to use objective‐C similar to that of NeXTSTEP
• Developed a collection of libraries named• Developed a collection of libraries named “Cocoa” to aid GUI development
• Release Mac OS X (ten) which was radicallyRelease Mac OS X (ten), which was radically different than OS 9, in March 2001
The Cocoa APIThe Cocoa API
• Primarily the most frequently used frameworksPrimarily the most frequently used frameworks nowadays.
• Developed by Apple from NeXTSTEP and OPENSTEPp y pp
• Has a set of predefined classes and types such as NSnumber, NSstring, Nsdate, etc.g
• NS stands for NeXT‐sun
• Includes a root class NSObject where words like alloc, j ,retain, and release come from
Dynamic LanguageDynamic Language
• Almost everything is done at runtimeAlmost everything is done at runtime
• Uses dynamic typing, linking, and binding
hi ll f fl ibili• This allows for greater flexibility
• Minimizes RAM and CPU usage
Objective‐C Primer, Part 1
C++/C#/Java and Objective‐C Terminology ComparisonTerminology Comparison
A brief introductionA brief introduction
– Object modelObject model
– Square brackets
– Naming conventionsNaming conventions
– Importing
Class definition and implementation– Class definition and implementation
– Exception handling
Nil objects– Nil objects
– Memory management
Object ModelObject Model
• provides messaging‐style syntax that involvesprovides messaging style syntax that involves passing messages to object instances, rather than calling methods on objectsthan calling methods on objects.
Square Brackets and Methods
• The object model is based around the conceptThe object model is based around the concept that objects are sent messages in order to invoke a method.
• The square brackets indicate that you areThe square brackets indicate that you are sending a message to an object.
• Example:[ diesel start];[ diesel start];
Methods and Messaging
This declaration is preceded by a minus (-) sign, which indicates that this is an instance method.
[myArray insertObject:anObject atIndex:0];
Calling a Method
// Create reference to an object of type Engine class called diesel.*Engine* diesel;
// Create an instance of the Engine object and point the diesel reference at itdiesel [[ Engine alloc] init];diesel = [[ Engine alloc] init];
// Call the start method by passing the Engine object the start message[ diesel start];[ diesel start];
The same code in C++ (without the comments) would look as follows:Engine diesel;g ;diesel = new Engine();diesel.start();
Passing and Retrieving
• Passing:Passing:[diesel start: gas];
• return such a value:currentRevs = [ diesel revs ];
Naming Conventions
• much like other languagesmuch like other languages, – using PascalCase for classes
and camelCase for methods and properties– and camelCase for methods and properties.
ImportingImporting
• Two ways of importing just as with C/C++• Two ways of importing, just as with C/C++. – 1. Angle Bracker <> – 2. Double Quote “”
• The difference is that the syntax of – force the compiler’s preprocessor to look for the file in the system header directory, – Quotes syntax will look in the current directory if you haven’t specified an alternative location.
• To look in the system header directory, use the following syntax:
• #import <Foundation/foundation.h>
• To look for your own header file in the current or specific directory, use the following syntax:
• #import "myfile.h”
Class Definition and ImplementationClass Definition and Implementation
• As with most object‐oriented languages, – an object is defined by its class, – and many instances of that object may be created.
• Every class consists of – an interface, which defines the structure of the class – and allows its functionality to be implemented.
• Each classEach class – has a corresponding implementation – that actually provides the functionality.
Obj‐C l h lClass with structure & Implementation
• In Obj‐C, these implementations are held in separate files, with – the interface code contained in a header file (.h extension) – and the implementation held in a message file (.m extension).
• .h file: – describes the Structure or Abstraction
• .m file:.m file:– implements details
Class in Obj‐CClass in Obj C
Engine hEngine.h@interface Engin
‐ (int) revs;@end
Engine.m@implementation Engin
‐ (int) revs (return revs;}}
‐ (void) start {// Start the engine at an idle speed of 900 rpm// – NOTE This is a comment
900revs=900;}
@end
Nil ObjectsNil Objects
• Methods are – implemented as messages being passed to objects whose correct identity is resolved at runtime.
• a mismatch during runtime, – either an exception will be thrown (best‐case scenario)
h b ll l l h (– or the object will silently ignore the message (worst‐case scenario).
• Be extra careful about both – ensuring message\object interaction is valid – and that good exception handling is added throughout– and that good exception handling is added throughout.
Exception Handling
• Similar to those used C++/C#/Java or exception handling in other languageslanguages.
@try{{// Code to execute and for which you wish to catch the exception}@catch (){{// Do something after an exception has been caught}@finally{// Clean up code here}
Memory ManagementMemory Management
• A referencecounting system is used by Objective‐C.•• This means that
– if you keep track of your references, the runtime will automatically l i d b bj t th f t treclaim any memory used by objects once the reference count returns
to zero.
• NSString* s = [[NSString alloc] init]; // Ref count is 1NSString s [[NSString alloc] init]; // Ref count is 1 • [s retain]; // Ref count is 2 ‐ silly • // to do this after init
• [s release]; // Ref count is back to 1 • [s release]; // Ref count is 0, object is freed
ARCARC• Now you are free from Reference counting because of ARC• Xcode 4.2 and iOS 5
– offer a new feature called automatic reference counting (ARC), – which simplifies memory management.
• ARC – ARC makes memory management much easier, – greatly reducing the chance for your program to have memory leaks. – inserts the appropriate method calls for you at compile time.– The compiler also generates the appropriate dealloc methods to free
up memory that is no longer required.
• Essentially, ARC is a pre‐compilation stage that adds the necessary code you previously would have had to insert manuallycode you previously would have had to insert manually.
Obj i C i 2Objective‐C Primer, Part 2
Class DeclarationClass Declaration
.NET C# Objective‐C
cass AClass : Object{
@interface AClass : NSObject{
{int aValue;void doNothing();
int aValue;}‐ (void)doNothing();g()
String returnString();}
+ (NSString)returnString();@end
Method Declaration
• Two type of Method:– Class Method– Instance method
• A class method – indicated by a plus (+) character. – associated with the class type.
• An instance method – indicated by a minus (‐) character– indicated by a minus (‐) character. – associated with an instance object associated with the class.
Properties
Strings
Interfaces and Protocols
Comments
DemoDemo
Hello World!
Creating Your First iPhone ApplicationCreating Your First iPhone Application
• 1 Create your project1. Create your project.
• 2. Design your application.
3 i d• 3. Write code.
• 4. Build and run your app.
• 5. Test, measure, and tune your app.
Q & A
Thank You All