Objective C 2.0 Part 1

download Objective C 2.0 Part 1

of 38

description

Presentation Slides on Objective C 2.0

Transcript of Objective C 2.0 Part 1

Objective-C

Objective-CIntroduction to IPhone Programming

Adapted from Programming in Objective-C 2.0 by Stephen Kochan, ClassroomM, Inc. All rights reserved1BackgroundObject Oriented Programming: Classes, Objects, and Methods Writing a program in Objective-C - Introduction to XCode Data types and expressions Loops Making decisions2A simple Outline Frameworks Using the Documentation Foundation classesString and Number Objects Collections: Arrays, Dictionaries, and Sets Memory Management Copying Objects Working with Files3What is Objective-C? An object-oriented programming language (OOP) Designed by Brad Cox (early 1980s)Based on SmallTalk Layered on the C language (1970s)Licensed by NeXT Software (1988)4What is Objective-C?Apple Acquired NeXT Software (1996)NEXTSTEP environment was basis for Mac OS XObjective-C became the standard development language for apps written for Mac OS X and then later for the iPhone and iPod Touch5Your First Program//First program example #import int main (int argc, const char *argv[]) {NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog (@"Programming is fun.");[pool drain]; return 0;}6Common filename extensions.c C source file.cc, .cpp C++ source file.h Header file.m Objective-C source file.pl Perl source file.o Object file7To run in Xcode 3.2Start up XcodeIf this is a new project, select File->New Project... Choose Application, Command Line Tool, Foundation (as Type) and click Choose....Select a name for your project. Click Save.Under Source select the file projectName.m. Save your changes that youve entered by selecting File, Save.Build and run your application by selecting Build, Build and Run (or click on the Build and Go button)8The Second#import int main (int argc, const char *argv[]) {NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int sum;sum = 50 + 25;NSLog (@"The sum of 50 and 25 is %i, sum);[pool drain]; return 0;}9OOPWhat is ObjectInstanceClassMessage10OOPAn object is a thing OOP is dealing with objectsEveryday example of an object:AcarDrive , then fill it gas, then wash it, then get it serviced11What is an InstanceAn object comes from a class (e.g. Cars) A unique occurrence of an object from a class is called an instance Your car may be red, have 20 wheels, and a V8 engine. Its VIN number uniquely identifies it12MethodThe action you perform on an object or on a classIn Objective-C, the syntax is:

[ ClassorInstance method ]; [ receiver message ];13MethodFirst, create a new instance from a class: myCar = [Car new];Next, you perform actions with that instance:[myCar wash]; [myCar drive]; [myCar service]; [myCar topDown]; 14MethodGet information about your car:currentMileage = [myCar odometer];Set the trip odometer to 0: [myCar setTripOdometer: 0];15UsuallyObjects you work with will be a little different:// Reload table data [myTable reloadData];// Load image data from a file[UIImage imageNamed: @apple.png]; // Count the number of tapsn = [touch tapCount];// # of taps// Set the text on a label [myLabel setText: @Hello];16A fraction Class: Interface@interface Fraction: NSObject {int numerator; int denominator;}-(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d;@end17A fraction Class: Implement@implementation Fraction -(void) print {NSLog (@ %i/%i , numerator, denominator);}-(void) setNumerator: (int) n {numerator = n;}-(void) setDenominator: (int) d {denominator = d; }@end18Lets use itint main (int argc, char *argv[]){NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *myFraction;// Create an instance of a FractionmyFraction = [Fraction alloc]; myFraction = [myFraction init];// Set fraction to 1/3[myFraction setNumerator: 1];[myFraction setDenominator: 3];// Display the fraction using the print methodNSLog (@The value of myFraction is: ); [myFraction print];[myFraction release]; [pool drain];return 0;}19Interface@interface NewClassName: ParentClassName {Instance Variable Declarations}methodDeclarations@end20Implementation#import NewClassName.h@implementation NewClassName methodDefinitions@end21How to read a method header- (void) setNumerator: (int) n;Method typeReturn typeMethod nameMethod takes parameter (aka argument)Parameter typeParameter name22The program// Declare an objectFraction *myFraction; // Allocate a new instance from a class myFraction = [Fraction alloc];// Initialize the new instance myFraction = [myFraction init];

// Allocate and initialize a new instance myFraction = [[Fraction alloc] init];// -or-myFraction = [Fraction new]; // Declare, allocate, and initialize Fraction *myFraction = [[Fraction alloc] init];23int main (int argc, char *argv[]){NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *frac1 = [[Fraction alloc] init];Fraction *frac2 = [[Fraction alloc] init];[frac1 setNumerator: 2];[frac1 setDenominator: 3];

[frac2 setNumerator: 3];[frac2 setDenominator: 7];// Display the fractionsNSLog (@First fraction is:); [frac1 print];NSLog (@Second fraction is:); [frac2 print];[frac1 release]; [frac2 release]; [pool drain]; return 0;}24Accessing Instance Variables Instance methods can access their own instance variables Class methods cant Theyre hidden from everyone else (data encapsulation)

25Accessor Methods-(int) numerator { return numerator; }-(int) denominator { return denominator; }***********myFraction = [[Fraction alloc] init];[myFraction setNumerator: 1]; [myFraction setDenominator: 3];// Display the fraction using our two new methodsNSLog (@The value of myFraction is %i/%i, [myFraction numerator], [myFraction denominator]);The value of myFraction is 1/326Basic Data Types

27Conversion (C like)Floating to integer produces truncation: int i1 = 123.75; // stores 123One floating term results in a floating result:int i=5; float f = i / 2.0;Two integer terms results in an integer:int i=5; floatf=i/2; //stores2intof

int i=5,j=2; float f = (float) i / j;// assigns 2.528Boolean TypeYou can use the special BOOL type and the defined YES and NO values when working with Boolean variablesBOOL endOfData = NO;while (endOfData == NO) { if (...)...endOfData = YES;}29Synthesized AccessorsGetters and Setters can be automatically generated for youStarts with the @property directive in the interface section:@property int numerator, denominator;@synthesize directive in implementation section causes automatic generation of the setter and getter methods:@synthesize numerator, denominator;30Synthesized Accessors#import @interface Fraction : NSObject {int numerator; int denominator;}@property int numerator, denominator;-(void) print; -(double) convertToNum; @end31Synthesized Accessors@implementation Fraction

@synthesize numerator, denominator;

-(void) print {...}

-(double) convertToNum {}

@end32Dot OperatorUsed to access properties.Format:instance.property is the same as writing[instance property] Example:myFraction.numerator33Dot OperatorFormat:instance.property = value is the same as writing[instance setProperty: value] Example:myFraction.numerator = 5;34Multiple Method ArgumentsInterface Definition:-(void) setTo: (int) n over: (int) d;Implementation Definition:-(void) setTo: (int) n over: (int) d{numerator = n; denominator = d;}Use:[myFraction setTo: 100 over: 200]; Name:setTo:over:35The self KeywordThe self keyword refers to the receiver of the message-(void) add: (Fraction *) f {// To add two fractions: // a/b + c/d = ((a*d) + (b*c)) / (b * d)numerator = (numerator * f.denominator) + (denominator * f.numerator);

denominator *= f.denominator;

[self reduce];}36Allocating and Returning Object from Methods-(Fraction *) add: (Fraction *) f {// To add two fractions: // a/b + c/d = ((a*d) + (b*c)) / (b * d)

Fraction *result = [[Fraction alloc] init];

result.numerator = (numerator * f.denominator) + (denominator * f.numerator);

result.denominator = denominator * f.denominator;

[result reduce]; return result;}37The CodeSee fraction example for whole codehttp://classroomm.com/objective-c/index.php?topic=2046.038