Vous êtes sur la page 1sur 38

Objective-C

Introduction to IPhone Programming

Adapted from Programming in Objective-C 2.0 by Stephen Kochan, ClassroomM, Inc.


All rights reserved

Background

Object Oriented Programming: Classes,


Objects, and Methods

Writing a program in Objective-C Introduction to XCode

Data types and expressions

Loops
Making decisions

A simple Outline

Frameworks

Using the Documentation

Foundation classes

String and Number Objects


Collections: Arrays, Dictionaries, and Sets

Memory Management

Copying Objects

Working with Files

What 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)

What is Objective-C?

Apple Acquired NeXT Software (1996)

NEXTSTEP environment was basis for Mac OS


X

Objective-C became the standard


development language for apps written for
Mac OS X and then later for the iPhone and
iPod Touch

Your First Program


//First program example
#import <Foundation/Foundation.h>
int main (int argc, const char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog (@"Programming is fun.");
[pool drain];
return 0;
}

Common filename
extensions

.c

C source file

.cc, .cpp

.h

.m

Objective-C source file

.pl

Perl source file

.o

C++ source file

Header file

Object file

To run in Xcode 3.2

Start up Xcode

If 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)

The Second
#import <Foundation/Foundation.h>
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;
}

OOP

What is

Object
Instance
Class
Message

OOP

An object is a thing OOP is dealing with


objects

Everyday example of an object:

A car

Drive , then fill it gas, then wash it, then


get it serviced

What is an Instance

An 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 it

Method

The action you perform on an object or on a


class

In Objective-C, the syntax is:

[ ClassorInstance method ];
[ receiver message ];

Method

First, 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];

Method

Get information about your car:

currentMileage = [myCar odometer];

Set the trip odometer to 0:

[myCar setTripOdometer: 0];

Usually

Objects 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 taps
n = [touch tapCount]; // # of taps

// Set the text on a label

[myLabel setText: @Hello];

A fraction Class:
Interface
@interface Fraction: NSObject
{
int numerator;
int denominator;
}
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
@end

A fraction Class:
Implement
@implementation Fraction
-(void) print {
NSLog (@ %i/%i , numerator, denominator);
}
-(void) setNumerator: (int) n {
numerator = n;
}
-(void) setDenominator: (int) d {
denominator = d;
}
@end

Lets use it
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *myFraction;
// Create an instance of a Fraction
myFraction = [Fraction alloc];
myFraction = [myFraction init];
// Set fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];
// Display the fraction using the print method
NSLog (@The value of myFraction is: );
[myFraction print];
[myFraction release];
[pool drain];
return 0;

Interface
@interface NewClassName: ParentClassName
{
Instance Variable Declarations
}
methodDeclarations
@end

Implementation
#import NewClassName.h
@implementation NewClassName
methodDefinitions
@end

How to read a method


header
- (void) setNumerator: (int) n;

Method type

Return type

Method name

Method takes parameter (aka argument)

Parameter type

Parameter name

The program
// Declare an object
Fraction *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];
// -ormyFraction = [Fraction new];
// Declare, allocate, and initialize
Fraction *myFraction = [[Fraction alloc] init];

int 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 fractions
NSLog (@First fraction is:);
[frac1 print];
NSLog (@Second fraction is:);
[frac2 print];
[frac1 release];
[frac2 release];
[pool drain];
return 0;

Accessing Instance
Variables

Instance methods can access their own


instance variables

Class methods cant Theyre hidden from


everyone else (data encapsulation)

Accessor 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 methods
NSLog (@The value of myFraction is %i/%i,
[myFraction numerator], [myFraction denominator]);
The value of myFraction is 1/3

Basic Data Types

Conversion (C like)

Floating to integer produces truncation:

One floating term results in a floating result:

int i1 = 123.75; // stores 123

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.5

Boolean Type
You can use the special BOOL type and the defined YES and
NO values when working with Boolean variables
BOOL endOfData = NO;
while (endOfData == NO) {
if (...)
...
endOfData = YES;
}

Synthesized Accessors

Getters and Setters can be automatically generated for


you

Starts 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;

Synthesized Accessors
#import <Foundation/Foundation.h>
@interface Fraction : NSObject
{
int numerator;
int denominator;
}
@property int numerator, denominator;
-(void) print;
-(double) convertToNum;
@end

Synthesized Accessors
@implementation Fraction
@synthesize numerator, denominator;
-(void) print {
...
}
-(double) convertToNum {

}
@end

Dot Operator
Used to access properties.
Format:
instance.property is the same as writing
[instance property]
Example:
myFraction.numerator

Dot Operator
Format:
instance.property = value
is the same as writing
[instance setProperty: value]
Example:
myFraction.numerator = 5;

Multiple Method
Arguments
Interface 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:

The self Keyword


The 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];

Allocating 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;

The Code

See fraction example for whole code

http://classroomm.com/objective-c/index.php?topic=2046.0

Vous aimerez peut-être aussi