SlideShare a Scribd company logo
1 of 63
Download to read offline
Stanford CS193p
Developing Applications for iOS
Fall 2011

Stanford CS193p
Fall 2011
Today
What is this class all about?
Description
Prerequisites
Homework / Final Project

iOS Overview
What’s in iOS?

MVC

Object-Oriented Design Concept

Objective C

New language!
Basic concepts only for today.

Stanford CS193p
Fall 2011
What will I learn in this course?
How to build cool apps

Easy to build even very complex applications
Result lives in your pocket!
Very easy to distribute your application through the AppStore
Vibrant development community

Real-life Object-Oriented Programming

The heart of Cocoa Touch is 100% object-oriented
Application of MVC design model
Many computer science concepts applied in a commercial development platform:
Databases, Graphics, Multimedia, Multithreading, Animation, Networking, and much, much more!
Numerous students have gone on to sell products on the AppStore

Stanford CS193p
Fall 2011
Prerequisites
Most Important Prereq!

You should know these terms!

Object-Oriented Terms

Programming Experience

Class (description/template for an object)
Instance (manifestation of a class)
Message (sent to object to make it act)
Method (code invoked by a Message)
Instance Variable (object-specific storage)
Superclass/Subclass (Inheritance)
Protocol (non-class-specific methods)

If you have never written a program where you
had to design and implement more than a
handful of classes, this will be a big step up in
difficulty for you.

Object-Oriented Programming
CS106A&B required, CS107 recommended

If you are not very comfortable with all of
these, this might not be the class for you
This is an upper-level CS course.

Stanford CS193p
Fall 2011
Assignments
Weekly Homework

7 weekly assignments
Assigned Thursday after lecture
Due the following Wednesday at 11:59pm
Individual work only
Homework graded ✓, ✓+ and ✓- based on
Required Tasks and Evaluation criteria
Lots of extra credit available, bank it
Only 3 “free” late days per quarter
#1 fail: falling behind on homework

Final Project

3 weeks to work on it
But weighted like 4 weeks of homework
Proposal requires instructor approval
Some teams of 2 might be allowed
Keynote presentation required (3 mins or so)

Stanford CS193p
Fall 2011
iOS
Cocoa Touch
Media
Core Services
Core OS

Core OS
OSX Kernel Power Management
Mach 3.0

Keychain Access

BSD

Certificates

Sockets

File System

Security

Bonjour

Stanford CS193p
Fall 2011
iOS
Cocoa Touch
Media
Core Services
Core OS

Core Services
Collections

Core Location

Address Book Net Services
Networking

Threading

File Access

Preferences

SQLite

URL Utilities

Stanford CS193p
Fall 2011
iOS
Cocoa Touch
Media
Core Services
Core OS

Media
Core Audio

JPEG, PNG, TIFF

OpenAL

PDF

Audio Mixing

Quartz (2D)

Audio Recording Core Animation
Video Playback

OpenGL ES

Stanford CS193p
Fall 2011
iOS
Cocoa Touch
Media
Core Services
Core OS

Cocoa Touch
Multi-Touch

Alerts

Core Motion

Web View

View Hierarchy

Map Kit

Localization

Image Picker

Controls

Camera

Stanford CS193p
Fall 2011
Platform Components
Tools

Language

Xcode 4

[display setTextColor:[UIColor blackColor]];

e
or
C

Frameworks
Foundation
Design Strategies

s

nt
stru me
In

a
at
D

Ma
p

Cor
eM
otio
n
Kit

MVC

UIKit

Stanford CS193p
Fall 2011
MVC
Controller

Model

View

Divide objects in your program into 3 “camps.”
Stanford CS193p
Fall 2011
MVC
Controller

Model

View

Model = What your application is (but not how it is displayed)
Stanford CS193p
Fall 2011
MVC
Controller

Model

View

Controller = How your Model is presented to the user (UI logic)
Stanford CS193p
Fall 2011
MVC
Controller

Model

View

View = Your Controller’s minions
Stanford CS193p
Fall 2011
MVC
Controller

Model

View

It’s all about managing communication between camps
Stanford CS193p
Fall 2011
MVC
Controller

Model

View

Controllers can always talk directly to their Model.
Stanford CS193p
Fall 2011
MVC
Controller

Model

outlet

View

Controllers can also talk directly to their View.
Stanford CS193p
Fall 2011
MVC
Controller

Model

outlet

View

The Model and View should never speak to each other.
Stanford CS193p
Fall 2011
MVC
Controller

Model

outlet

?
View

Can the View speak to its Controller?
Stanford CS193p
Fall 2011
MVC
Controller

Model

outlet

View

Sort of. Communication is “blind” and structured.
Stanford CS193p
Fall 2011
MVC
target

Controller

Model

outlet

View

The Controller can drop a target on itself.
Stanford CS193p
Fall 2011
MVC
target

Controller

outlet

action

Model

View

Then hand out an action to the View.
Stanford CS193p
Fall 2011
MVC
target

Controller

outlet

action

Model

View

The View sends the action when things happen in the UI.
Stanford CS193p
Fall 2011
MVC
target

Controller

outlet

action
should

Model

will

did

View

Sometimes the View needs to synchronize with the Controller.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller

outlet
g
le

de
e
at

Model

action

View

The Controller sets itself as the View’s delegate.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller

outlet
g
le

de
e
at

Model

action

View

The delegate is set via a protocol (i.e. it’s “blind” to class).
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller

outlet
g
le

de
e
at

Model

action

View

Views do not own the data they display.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller

outlet
g
le

de
e
at

Model

data
at

action

View

count

So, if needed, they have a protocol to acquire it.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

count

rc
e

e
at

so
u

g
le

Model

de

da
ta

outlet

action

View

Controllers are almost always that data source (not Model!).
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

count

rc
e

e
at

so
u

g
le

Model

de

da
ta

outlet

action

View

Controllers interpret/format Model information for the View.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller

so
u

rc
e

e
at

da
ta

outlet
g
le

Model

count

de

?

data
at

action

View

Can the Model talk directly to the Controller?
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

count

rc
e

e
at

so
u

g
le

Model

de

da
ta

outlet

action

View

No. The Model is (should be) UI independent.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

count

rc
e

e
at

so
u

g
le

Model

de

da
ta

outlet

action

View

So what if the Model has information to update or something?
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

rc
e

e
at

so
u

g
le

Model

da
ta

outlet
de

Notification
& KVO

count

action

View

It uses a “radio station”-like broadcast mechanism.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

rc
e

e
at

so
u

g
le

Model

da
ta

outlet
de

Notification
& KVO

count

action

View

Controllers (or other Model) “tune in” to interesting stuff.
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

rc
e

e
at

so
u

g
le

Model

da
ta

outlet
de

Notification
& KVO

count

action

View

A View might “tune in,” but probably not to a Model’s “station.”
Stanford CS193p
Fall 2011
MVC
target

should
will

did

Controller
data
at

rc
e

e
at

so
u

g
le

Model

da
ta

outlet
de

Notification
& KVO

count

action

View

Now combine MVC groups to make complicated programs ...
Stanford CS193p
Fall 2011
MVCs working together

Stanford CS193p
Fall 2011
MVCs not working together

Stanford CS193p
Fall 2011
Objective-C
New language to learn!

Strict superset of C
Adds syntax for classes, methods, etc.
A few things to “think differently” about (e.g. properties, dynamic binding)

Most important concept to understand today: Properties

Usually we do not access instance variables directly in Objective-C.
Instead, we use “properties.”
A “property” is just the combination of a getter method and a setter method in a class.
The getter has the name of the property (e.g. “myValue”)
The setter’s name is “set” plus capitalized property name (e.g. “setMyValue:”)
(To make this look nice, we always use a lowercase letter as the first letter of a property name.)
We just call the setter to store the value we want and the getter to get it. Simple.

This is just your first glimpse of this language!
We’ll go much more into the details next week.
Don’t get too freaked out by the syntax at this point.

Stanford CS193p
Fall 2011
Objective-C

Spaceship.h
#import "Vehicle.h"

Superclass’s header file.
This is often <UIKit/UIKit.h> .

Spaceship.m

#import "Spaceship.h"

Importing our own header file.

@interface Spaceship : Vehicle

Class name

Superclass

@implementation Spaceship

Note, superclass not specified here.

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h
#import "Vehicle.h"

Objective-C

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle
// declaration of public methods
@implementation Spaceship
// implementation of public and private methods

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

Spaceship.m

#import "Vehicle.h"

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

Don’t forget the

().

No superclass here either.

@implementation Spaceship
// implementation of public and private methods

@end

@end

Stanford CS193p
Fall 2011
Objective-C

Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

We need to import Planet.h for
method declaration below to work.

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

The full name of this method is
orbitPlanet:atAltitude:

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

@implementation Spaceship
// implementation of public and private methods

Lining up the colons
makes things look nice.

It takes two arguments.
Note how each is preceded by its own keyword.
It does not return any value.

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

Objective-C

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end
@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

No semicolon here.
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end
@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

- (void)setTopSpeed:(double)percentSpeedOfLight;
- (double)topSpeed;

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end
@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;
- (void)setTopSpeed:(double)percentSpeedOfLight;
- (double)topSpeed;

// implementation of public and private methods

- (void)setTopSpeed:(double)speed
{
???
}
- (double)topSpeed
{
???
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h
#import "Vehicle.h"
#import "Planet.h"
@interface Spaceship : Vehicle
// declaration of public methods

Objective-C

Spaceship.m

#import "Spaceship.h"

This @property
essentially declares
the two “topSpeed”
methods below.

@interface Spaceship()
// declaration of private methods (as needed)
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

- (void)setTopSpeed:(double)percentSpeedOfLight;
- (double)topSpeed;

nonatomic means its setter and getter are not thread-safe.
That’s no problem if this is UI code because all UI code happens
on the main thread of the application.

- (void)setTopSpeed:(double)speed
{
???
}
- (double)topSpeed
{
???
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

We never declare both the @property and
its setter and getter in the header file
(just the @property).

- (void)setTopSpeed:(double)speed
{
???
}
- (double)topSpeed
{
???
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

We almost always use @synthesize to create the
implementation of the setter and getter for a @property.
It both creates the setter and getter methods AND
creates some storage to hold the value.

This is the name of the
storage location to use.

@synthesize topSpeed = _topSpeed;
- (void)setTopSpeed:(double)speed
{
???
_ (underbar) then the name of the
property is a common naming convention.
}
- (double)topSpeed
{
???
}

If we don’t use = here, @synthesize
uses the name of the property
(which is bad so always use =).

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Objective-C

Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods
@synthesize topSpeed = _topSpeed;

This is what the methods
created by @synthesize
would look like.

- (void)setTopSpeed:(double)speed
{
_topSpeed = speed;
}
- (double)topSpeed
{
return _topSpeed;
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

Objective-C

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods
@synthesize topSpeed = _topSpeed;

Most of the time, you can let @synthesize do all
the work of creating setters and getters

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

Objective-C

Spaceship.m

#import "Spaceship.h"

@interface Spaceship : Vehicle

@interface Spaceship()
// declaration of private methods (as needed)

// declaration of public methods

@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods
@synthesize topSpeed = _topSpeed;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}

However, we can create our own if there is any
special work to do when setting or getting.
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

@synthesize topSpeed = _topSpeed;

Here’s another @property.
This one is private (because it’s in our .m file).

- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

It’s a pointer to an object (of class Wormhole).
It’s strong which means that the memory used by this
object will stay around for as long as we need it.
All objects are always allocated on the heap.
So we always access them through a pointer. Always.

@synthesize topSpeed = _topSpeed;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

This creates the setter and getter for our new

@property.

does NOT create storage
for the object this pointer points to.
It just allocates room for the pointer.
@synthesize

We’ll talk about how to allocate and
initialize the objects themselves next week.
@end

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
}
@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}

Now let’s take a look at some example coding.
This is just to get a feel for Objective-C syntax.

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here

}
@end

@end

Stanford CS193p
Fall 2011
Objective-C

Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;

The “square brackets” syntax
is used to send messages.

We’re calling

topSpeed’
s

getter on ourself here.

- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
double speed = [self topSpeed];
if (speed > MAX_RELATIVE) speed = MAX_RELATIVE;
}

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

- (void)setTopSpeed:(double)percentSpeedOfLight;
- (double)topSpeed;

A reminder of what our getter declaration looks like.
Recall that these two declarations are accomplished with
the @property for topSpeed above.

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
double speed = [self topSpeed];
if (speed > MAX_RELATIVE) speed = MAX_RELATIVE;
}

@end

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}

Here’s another example of sending a message.
It looks like this method has 2 arguments:
a Planet to travel to and a speed to travel at.
It is being sent to an instance of Wormhole.
@end

- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
double speed = [self topSpeed];
if (speed > MAX_RELATIVE) speed = MAX_RELATIVE;
[[self nearestWormhole] travelToPlanet:aPlanet
atSpeed:speed];
}

Square brackets inside square brackets.

@end

Stanford CS193p
Fall 2011
Spaceship.h

Objective-C

#import "Vehicle.h"
#import "Planet.h"

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;

Calling getters and setters is such an important
task, it has its own syntax: dot notation.

@end

- (void)setTopSpeed:(double)speed
This is identical to [self topSpeed].
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
double speed = self.topSpeed;
if (speed > MAX_RELATIVE) speed = MAX_RELATIVE;
[[self nearestWormhole] travelToPlanet:aPlanet
atSpeed:speed];
}
@end

Stanford CS193p
Fall 2011
Spaceship.h
#import "Vehicle.h"
#import "Planet.h"

Objective-C

Spaceship.m

#import "Spaceship.h"

// declaration of public methods

@interface Spaceship()
// declaration of private methods (as needed)
@property (nonatomic, strong) Wormhole *nearestWormhole;
@end

@property (nonatomic) double topSpeed;

@implementation Spaceship

- (void)orbitPlanet:(Planet *)aPlanet
atAltitude:(double)km;

// implementation of public and private methods

@interface Spaceship : Vehicle

@synthesize topSpeed = _topSpeed;
@synthesize nearestWormhole = _nearestWormhole;
- (void)setTopSpeed:(double)speed
{
if ((speed < 1) && (speed > 0)) _topSpeed = speed;
}
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km
{
// put the code to orbit a planet here
double speed = self.topSpeed;
if (speed > MAX_RELATIVE) speed = MAX_RELATIVE;
[self.nearestWormhole travelToPlanet:aPlanet
atSpeed:speed];
}

We can use dot notation here too.

@end

@end

Stanford CS193p
Fall 2011
Coming Up
Next Lecture

Overview of the Integrated Development Environment (IDE, i.e. Xcode 4)
Objective-C in action
Concrete example of MVC
Major demonstration of all of the above: RPN Calculator
(HOMEWORK: if you do not know what an RPN Calculator is, look it up on the internet.)

Friday

Very simple introduction to using the debugger.
Optional. You can figure it out on your own if you want (not too difficult).

Next Week

Objective-C language in depth
Foundation classes: arrays, dictionaries, strings, etc.
Dynamic vs. static typing
Protocols, categories and much, much more!
Stanford CS193p
Fall 2011

More Related Content

What's hot

JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobileJavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobileLoiane Groner
 
Plug yourself in and your app will never be the same (2 hour edition)
Plug yourself in and your app will never be the same (2 hour edition)Plug yourself in and your app will never be the same (2 hour edition)
Plug yourself in and your app will never be the same (2 hour edition)Mikkel Flindt Heisterberg
 
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1Rich Helton
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierHimel Nag Rana
 
Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScriptKevin Whinnery
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
Xamarin.iOS introduction
Xamarin.iOS introductionXamarin.iOS introduction
Xamarin.iOS introductionGuido Magrin
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02Rich Helton
 
Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Katy Slemon
 
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...Xamarin
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
How Symfony Changed My Life
How Symfony Changed My LifeHow Symfony Changed My Life
How Symfony Changed My LifeMatthias Noback
 
CC-Castle; The best Real-Time/Embedded/HighTech language EVER?
CC-Castle; The best Real-Time/Embedded/HighTech language EVER?CC-Castle; The best Real-Time/Embedded/HighTech language EVER?
CC-Castle; The best Real-Time/Embedded/HighTech language EVER?Albert Mietus
 
iPhone Coding For Web Developers
iPhone Coding For Web DevelopersiPhone Coding For Web Developers
iPhone Coding For Web DevelopersMatt Biddulph
 
Enhancing operator effectiveness with Symbol Factory
Enhancing operator effectiveness with Symbol FactoryEnhancing operator effectiveness with Symbol Factory
Enhancing operator effectiveness with Symbol FactoryAVEVA
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectureselliando dias
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldSaurabh Moody
 

What's hot (19)

JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobileJavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
 
Plug yourself in and your app will never be the same (2 hour edition)
Plug yourself in and your app will never be the same (2 hour edition)Plug yourself in and your app will never be the same (2 hour edition)
Plug yourself in and your app will never be the same (2 hour edition)
 
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 
Write Better JavaScript
Write Better JavaScriptWrite Better JavaScript
Write Better JavaScript
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Xamarin.iOS introduction
Xamarin.iOS introductionXamarin.iOS introduction
Xamarin.iOS introduction
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02
 
Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)
 
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
GitHub halp app - Minimizing platform-specific code with MVVM - Justin Spahr-...
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Android programming-basics
Android programming-basicsAndroid programming-basics
Android programming-basics
 
Azure rev002
Azure rev002Azure rev002
Azure rev002
 
How Symfony Changed My Life
How Symfony Changed My LifeHow Symfony Changed My Life
How Symfony Changed My Life
 
CC-Castle; The best Real-Time/Embedded/HighTech language EVER?
CC-Castle; The best Real-Time/Embedded/HighTech language EVER?CC-Castle; The best Real-Time/Embedded/HighTech language EVER?
CC-Castle; The best Real-Time/Embedded/HighTech language EVER?
 
iPhone Coding For Web Developers
iPhone Coding For Web DevelopersiPhone Coding For Web Developers
iPhone Coding For Web Developers
 
Enhancing operator effectiveness with Symbol Factory
Enhancing operator effectiveness with Symbol FactoryEnhancing operator effectiveness with Symbol Factory
Enhancing operator effectiveness with Symbol Factory
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectures
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The World
 

Viewers also liked

How to be cooler online than you are in real life
How to be cooler online than you are in real lifeHow to be cooler online than you are in real life
How to be cooler online than you are in real lifeNicole Dion
 
Arquitectura ecléctica
Arquitectura eclécticaArquitectura ecléctica
Arquitectura eclécticaVanessa Gómez
 
Dynamic Faces - Analyzing Data with a Face
Dynamic Faces - Analyzing Data with a FaceDynamic Faces - Analyzing Data with a Face
Dynamic Faces - Analyzing Data with a FaceExcel Effects
 
Sponsordossier Vsp
Sponsordossier VspSponsordossier Vsp
Sponsordossier Vspprdsutte
 
Laboratorio de concreto nº3 LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...
Laboratorio de concreto nº3  LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...Laboratorio de concreto nº3  LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...
Laboratorio de concreto nº3 LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...kedy ramirez gil
 
Acto de San Francisco
Acto de San FranciscoActo de San Francisco
Acto de San Franciscogpcarla
 
Social Tools in the Workplace Infographic
Social Tools in the Workplace InfographicSocial Tools in the Workplace Infographic
Social Tools in the Workplace InfographicMicrosoft
 
87.careers in microbiology
87.careers in microbiology87.careers in microbiology
87.careers in microbiologyentranzz123
 
9 – 10 листопада 2015 року з метою
9 – 10 листопада 2015 року з  метою9 – 10 листопада 2015 року з  метою
9 – 10 листопада 2015 року з метоюАлександр Дрон
 
Triptico
TripticoTriptico
Tripticogpcarla
 
Musab Certificate and Details
Musab Certificate and DetailsMusab Certificate and Details
Musab Certificate and DetailsMusaab Osman
 
PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...
PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...
PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...Kirstie Mogilner
 
The Witch's Halloween
The Witch's HalloweenThe Witch's Halloween
The Witch's HalloweenFortuna Lu
 
Leveraging Social Media. Some new stuff...thinking differently
Leveraging Social Media. Some new stuff...thinking differentlyLeveraging Social Media. Some new stuff...thinking differently
Leveraging Social Media. Some new stuff...thinking differentlyLee Yount
 
Barna encendida - Evento de Marketing Digital de SiteGround - José Ramón Padrón
Barna encendida - Evento de Marketing Digital de SiteGround - José Ramón PadrónBarna encendida - Evento de Marketing Digital de SiteGround - José Ramón Padrón
Barna encendida - Evento de Marketing Digital de SiteGround - José Ramón PadrónSiteGround España
 
9. εθνικός διχασμός 1915 1917
9. εθνικός διχασμός 1915 19179. εθνικός διχασμός 1915 1917
9. εθνικός διχασμός 1915 19174gymsch
 
交點台北開場簡報 11月份
交點台北開場簡報 11月份交點台北開場簡報 11月份
交點台北開場簡報 11月份交點
 

Viewers also liked (18)

How to be cooler online than you are in real life
How to be cooler online than you are in real lifeHow to be cooler online than you are in real life
How to be cooler online than you are in real life
 
Arquitectura ecléctica
Arquitectura eclécticaArquitectura ecléctica
Arquitectura ecléctica
 
Dynamic Faces - Analyzing Data with a Face
Dynamic Faces - Analyzing Data with a FaceDynamic Faces - Analyzing Data with a Face
Dynamic Faces - Analyzing Data with a Face
 
Sponsordossier Vsp
Sponsordossier VspSponsordossier Vsp
Sponsordossier Vsp
 
Laboratorio de concreto nº3 LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...
Laboratorio de concreto nº3  LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...Laboratorio de concreto nº3  LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...
Laboratorio de concreto nº3 LOS PESOS UNITARIOS DE LOS AGREGADOS Y EL CONTEN...
 
Acto de San Francisco
Acto de San FranciscoActo de San Francisco
Acto de San Francisco
 
Social Tools in the Workplace Infographic
Social Tools in the Workplace InfographicSocial Tools in the Workplace Infographic
Social Tools in the Workplace Infographic
 
87.careers in microbiology
87.careers in microbiology87.careers in microbiology
87.careers in microbiology
 
9 – 10 листопада 2015 року з метою
9 – 10 листопада 2015 року з  метою9 – 10 листопада 2015 року з  метою
9 – 10 листопада 2015 року з метою
 
Triptico
TripticoTriptico
Triptico
 
Musab Certificate and Details
Musab Certificate and DetailsMusab Certificate and Details
Musab Certificate and Details
 
PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...
PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...
PerkinElmer white paper evaluating XRpad flat panel detectors for security ap...
 
The Witch's Halloween
The Witch's HalloweenThe Witch's Halloween
The Witch's Halloween
 
Leveraging Social Media. Some new stuff...thinking differently
Leveraging Social Media. Some new stuff...thinking differentlyLeveraging Social Media. Some new stuff...thinking differently
Leveraging Social Media. Some new stuff...thinking differently
 
Barna encendida - Evento de Marketing Digital de SiteGround - José Ramón Padrón
Barna encendida - Evento de Marketing Digital de SiteGround - José Ramón PadrónBarna encendida - Evento de Marketing Digital de SiteGround - José Ramón Padrón
Barna encendida - Evento de Marketing Digital de SiteGround - José Ramón Padrón
 
9. εθνικός διχασμός 1915 1917
9. εθνικός διχασμός 1915 19179. εθνικός διχασμός 1915 1917
9. εθνικός διχασμός 1915 1917
 
交點台北開場簡報 11月份
交點台北開場簡報 11月份交點台北開場簡報 11月份
交點台北開場簡報 11月份
 
Resumen2
Resumen2Resumen2
Resumen2
 

Similar to iOS Programming - MCV (Delegate/Protocols/Property&Syntax)

Lecture 1 slides
Lecture 1 slidesLecture 1 slides
Lecture 1 slidesamarprabhu
 
Code camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una DalyCode camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una DalyUna Daly
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan
 
iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)Netcetera
 
Eclipse 2011 Hot Topics
Eclipse 2011 Hot TopicsEclipse 2011 Hot Topics
Eclipse 2011 Hot TopicsLars Vogel
 
Cross Platform Mobile Apps with the Ionic Framework
Cross Platform Mobile Apps with the Ionic FrameworkCross Platform Mobile Apps with the Ionic Framework
Cross Platform Mobile Apps with the Ionic FrameworkTroy Miles
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to DistributionTunvir Rahman Tusher
 
Building Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdfBuilding Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdfSivarajAmbat1
 
iOS course day 1
iOS course day 1iOS course day 1
iOS course day 1Rich Allen
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentPython Ireland
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applicationshchen1
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...NicheTech Com. Solutions Pvt. Ltd.
 

Similar to iOS Programming - MCV (Delegate/Protocols/Property&Syntax) (20)

Lecture 1 slides
Lecture 1 slidesLecture 1 slides
Lecture 1 slides
 
Code camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una DalyCode camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una Daly
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)
 
Eclipse 2011 Hot Topics
Eclipse 2011 Hot TopicsEclipse 2011 Hot Topics
Eclipse 2011 Hot Topics
 
Cross Platform Mobile Apps with the Ionic Framework
Cross Platform Mobile Apps with the Ionic FrameworkCross Platform Mobile Apps with the Ionic Framework
Cross Platform Mobile Apps with the Ionic Framework
 
02 objective-c session 2
02  objective-c session 202  objective-c session 2
02 objective-c session 2
 
iphone presentation
iphone presentationiphone presentation
iphone presentation
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
Building Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdfBuilding Accessible Apps using NET MAUI.pdf
Building Accessible Apps using NET MAUI.pdf
 
iOS course day 1
iOS course day 1iOS course day 1
iOS course day 1
 
React native
React nativeReact native
React native
 
Hello world ios v1
Hello world ios v1Hello world ios v1
Hello world ios v1
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
 
Intro to Android Programming
Intro to Android ProgrammingIntro to Android Programming
Intro to Android Programming
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 

iOS Programming - MCV (Delegate/Protocols/Property&Syntax)

  • 1. Stanford CS193p Developing Applications for iOS Fall 2011 Stanford CS193p Fall 2011
  • 2. Today What is this class all about? Description Prerequisites Homework / Final Project iOS Overview What’s in iOS? MVC Object-Oriented Design Concept Objective C New language! Basic concepts only for today. Stanford CS193p Fall 2011
  • 3. What will I learn in this course? How to build cool apps Easy to build even very complex applications Result lives in your pocket! Very easy to distribute your application through the AppStore Vibrant development community Real-life Object-Oriented Programming The heart of Cocoa Touch is 100% object-oriented Application of MVC design model Many computer science concepts applied in a commercial development platform: Databases, Graphics, Multimedia, Multithreading, Animation, Networking, and much, much more! Numerous students have gone on to sell products on the AppStore Stanford CS193p Fall 2011
  • 4. Prerequisites Most Important Prereq! You should know these terms! Object-Oriented Terms Programming Experience Class (description/template for an object) Instance (manifestation of a class) Message (sent to object to make it act) Method (code invoked by a Message) Instance Variable (object-specific storage) Superclass/Subclass (Inheritance) Protocol (non-class-specific methods) If you have never written a program where you had to design and implement more than a handful of classes, this will be a big step up in difficulty for you. Object-Oriented Programming CS106A&B required, CS107 recommended If you are not very comfortable with all of these, this might not be the class for you This is an upper-level CS course. Stanford CS193p Fall 2011
  • 5. Assignments Weekly Homework 7 weekly assignments Assigned Thursday after lecture Due the following Wednesday at 11:59pm Individual work only Homework graded ✓, ✓+ and ✓- based on Required Tasks and Evaluation criteria Lots of extra credit available, bank it Only 3 “free” late days per quarter #1 fail: falling behind on homework Final Project 3 weeks to work on it But weighted like 4 weeks of homework Proposal requires instructor approval Some teams of 2 might be allowed Keynote presentation required (3 mins or so) Stanford CS193p Fall 2011
  • 6. iOS Cocoa Touch Media Core Services Core OS Core OS OSX Kernel Power Management Mach 3.0 Keychain Access BSD Certificates Sockets File System Security Bonjour Stanford CS193p Fall 2011
  • 7. iOS Cocoa Touch Media Core Services Core OS Core Services Collections Core Location Address Book Net Services Networking Threading File Access Preferences SQLite URL Utilities Stanford CS193p Fall 2011
  • 8. iOS Cocoa Touch Media Core Services Core OS Media Core Audio JPEG, PNG, TIFF OpenAL PDF Audio Mixing Quartz (2D) Audio Recording Core Animation Video Playback OpenGL ES Stanford CS193p Fall 2011
  • 9. iOS Cocoa Touch Media Core Services Core OS Cocoa Touch Multi-Touch Alerts Core Motion Web View View Hierarchy Map Kit Localization Image Picker Controls Camera Stanford CS193p Fall 2011
  • 10. Platform Components Tools Language Xcode 4 [display setTextColor:[UIColor blackColor]]; e or C Frameworks Foundation Design Strategies s nt stru me In a at D Ma p Cor eM otio n Kit MVC UIKit Stanford CS193p Fall 2011
  • 11. MVC Controller Model View Divide objects in your program into 3 “camps.” Stanford CS193p Fall 2011
  • 12. MVC Controller Model View Model = What your application is (but not how it is displayed) Stanford CS193p Fall 2011
  • 13. MVC Controller Model View Controller = How your Model is presented to the user (UI logic) Stanford CS193p Fall 2011
  • 14. MVC Controller Model View View = Your Controller’s minions Stanford CS193p Fall 2011
  • 15. MVC Controller Model View It’s all about managing communication between camps Stanford CS193p Fall 2011
  • 16. MVC Controller Model View Controllers can always talk directly to their Model. Stanford CS193p Fall 2011
  • 17. MVC Controller Model outlet View Controllers can also talk directly to their View. Stanford CS193p Fall 2011
  • 18. MVC Controller Model outlet View The Model and View should never speak to each other. Stanford CS193p Fall 2011
  • 19. MVC Controller Model outlet ? View Can the View speak to its Controller? Stanford CS193p Fall 2011
  • 20. MVC Controller Model outlet View Sort of. Communication is “blind” and structured. Stanford CS193p Fall 2011
  • 21. MVC target Controller Model outlet View The Controller can drop a target on itself. Stanford CS193p Fall 2011
  • 22. MVC target Controller outlet action Model View Then hand out an action to the View. Stanford CS193p Fall 2011
  • 23. MVC target Controller outlet action Model View The View sends the action when things happen in the UI. Stanford CS193p Fall 2011
  • 24. MVC target Controller outlet action should Model will did View Sometimes the View needs to synchronize with the Controller. Stanford CS193p Fall 2011
  • 26. MVC target should will did Controller outlet g le de e at Model action View The delegate is set via a protocol (i.e. it’s “blind” to class). Stanford CS193p Fall 2011
  • 33. MVC target should will did Controller data at count rc e e at so u g le Model de da ta outlet action View So what if the Model has information to update or something? Stanford CS193p Fall 2011
  • 36. MVC target should will did Controller data at rc e e at so u g le Model da ta outlet de Notification & KVO count action View A View might “tune in,” but probably not to a Model’s “station.” Stanford CS193p Fall 2011
  • 38. MVCs working together Stanford CS193p Fall 2011
  • 39. MVCs not working together Stanford CS193p Fall 2011
  • 40. Objective-C New language to learn! Strict superset of C Adds syntax for classes, methods, etc. A few things to “think differently” about (e.g. properties, dynamic binding) Most important concept to understand today: Properties Usually we do not access instance variables directly in Objective-C. Instead, we use “properties.” A “property” is just the combination of a getter method and a setter method in a class. The getter has the name of the property (e.g. “myValue”) The setter’s name is “set” plus capitalized property name (e.g. “setMyValue:”) (To make this look nice, we always use a lowercase letter as the first letter of a property name.) We just call the setter to store the value we want and the getter to get it. Simple. This is just your first glimpse of this language! We’ll go much more into the details next week. Don’t get too freaked out by the syntax at this point. Stanford CS193p Fall 2011
  • 41. Objective-C Spaceship.h #import "Vehicle.h" Superclass’s header file. This is often <UIKit/UIKit.h> . Spaceship.m #import "Spaceship.h" Importing our own header file. @interface Spaceship : Vehicle Class name Superclass @implementation Spaceship Note, superclass not specified here. @end @end Stanford CS193p Fall 2011
  • 42. Spaceship.h #import "Vehicle.h" Objective-C Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle // declaration of public methods @implementation Spaceship // implementation of public and private methods @end @end Stanford CS193p Fall 2011
  • 43. Spaceship.h Objective-C Spaceship.m #import "Vehicle.h" #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end Don’t forget the (). No superclass here either. @implementation Spaceship // implementation of public and private methods @end @end Stanford CS193p Fall 2011
  • 44. Objective-C Spaceship.h #import "Vehicle.h" #import "Planet.h" We need to import Planet.h for method declaration below to work. Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end The full name of this method is orbitPlanet:atAltitude: - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; @implementation Spaceship // implementation of public and private methods Lining up the colons makes things look nice. It takes two arguments. Note how each is preceded by its own keyword. It does not return any value. @end @end Stanford CS193p Fall 2011
  • 45. Spaceship.h #import "Vehicle.h" #import "Planet.h" Objective-C Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods No semicolon here. - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 46. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods - (void)setTopSpeed:(double)percentSpeedOfLight; - (double)topSpeed; - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 47. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; - (void)setTopSpeed:(double)percentSpeedOfLight; - (double)topSpeed; // implementation of public and private methods - (void)setTopSpeed:(double)speed { ??? } - (double)topSpeed { ??? } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 48. Spaceship.h #import "Vehicle.h" #import "Planet.h" @interface Spaceship : Vehicle // declaration of public methods Objective-C Spaceship.m #import "Spaceship.h" This @property essentially declares the two “topSpeed” methods below. @interface Spaceship() // declaration of private methods (as needed) @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods - (void)setTopSpeed:(double)percentSpeedOfLight; - (double)topSpeed; nonatomic means its setter and getter are not thread-safe. That’s no problem if this is UI code because all UI code happens on the main thread of the application. - (void)setTopSpeed:(double)speed { ??? } - (double)topSpeed { ??? } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 49. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods We never declare both the @property and its setter and getter in the header file (just the @property). - (void)setTopSpeed:(double)speed { ??? } - (double)topSpeed { ??? } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 50. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods We almost always use @synthesize to create the implementation of the setter and getter for a @property. It both creates the setter and getter methods AND creates some storage to hold the value. This is the name of the storage location to use. @synthesize topSpeed = _topSpeed; - (void)setTopSpeed:(double)speed { ??? _ (underbar) then the name of the property is a common naming convention. } - (double)topSpeed { ??? } If we don’t use = here, @synthesize uses the name of the property (which is bad so always use =). - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 51. Objective-C Spaceship.h #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @synthesize topSpeed = _topSpeed; This is what the methods created by @synthesize would look like. - (void)setTopSpeed:(double)speed { _topSpeed = speed; } - (double)topSpeed { return _topSpeed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 52. Spaceship.h #import "Vehicle.h" #import "Planet.h" Objective-C Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @synthesize topSpeed = _topSpeed; Most of the time, you can let @synthesize do all the work of creating setters and getters - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 53. Spaceship.h #import "Vehicle.h" #import "Planet.h" Objective-C Spaceship.m #import "Spaceship.h" @interface Spaceship : Vehicle @interface Spaceship() // declaration of private methods (as needed) // declaration of public methods @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @synthesize topSpeed = _topSpeed; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } However, we can create our own if there is any special work to do when setting or getting. - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 54. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle @synthesize topSpeed = _topSpeed; Here’s another @property. This one is private (because it’s in our .m file). - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 55. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle It’s a pointer to an object (of class Wormhole). It’s strong which means that the memory used by this object will stay around for as long as we need it. All objects are always allocated on the heap. So we always access them through a pointer. Always. @synthesize topSpeed = _topSpeed; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 56. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle This creates the setter and getter for our new @property. does NOT create storage for the object this pointer points to. It just allocates room for the pointer. @synthesize We’ll talk about how to allocate and initialize the objects themselves next week. @end @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end Stanford CS193p Fall 2011
  • 57. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } Now let’s take a look at some example coding. This is just to get a feel for Objective-C syntax. - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here } @end @end Stanford CS193p Fall 2011
  • 58. Objective-C Spaceship.h #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; The “square brackets” syntax is used to send messages. We’re calling topSpeed’ s getter on ourself here. - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here double speed = [self topSpeed]; if (speed > MAX_RELATIVE) speed = MAX_RELATIVE; } @end @end Stanford CS193p Fall 2011
  • 59. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle - (void)setTopSpeed:(double)percentSpeedOfLight; - (double)topSpeed; A reminder of what our getter declaration looks like. Recall that these two declarations are accomplished with the @property for topSpeed above. @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here double speed = [self topSpeed]; if (speed > MAX_RELATIVE) speed = MAX_RELATIVE; } @end @end Stanford CS193p Fall 2011
  • 60. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } Here’s another example of sending a message. It looks like this method has 2 arguments: a Planet to travel to and a speed to travel at. It is being sent to an instance of Wormhole. @end - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here double speed = [self topSpeed]; if (speed > MAX_RELATIVE) speed = MAX_RELATIVE; [[self nearestWormhole] travelToPlanet:aPlanet atSpeed:speed]; } Square brackets inside square brackets. @end Stanford CS193p Fall 2011
  • 61. Spaceship.h Objective-C #import "Vehicle.h" #import "Planet.h" Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; Calling getters and setters is such an important task, it has its own syntax: dot notation. @end - (void)setTopSpeed:(double)speed This is identical to [self topSpeed]. { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here double speed = self.topSpeed; if (speed > MAX_RELATIVE) speed = MAX_RELATIVE; [[self nearestWormhole] travelToPlanet:aPlanet atSpeed:speed]; } @end Stanford CS193p Fall 2011
  • 62. Spaceship.h #import "Vehicle.h" #import "Planet.h" Objective-C Spaceship.m #import "Spaceship.h" // declaration of public methods @interface Spaceship() // declaration of private methods (as needed) @property (nonatomic, strong) Wormhole *nearestWormhole; @end @property (nonatomic) double topSpeed; @implementation Spaceship - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km; // implementation of public and private methods @interface Spaceship : Vehicle @synthesize topSpeed = _topSpeed; @synthesize nearestWormhole = _nearestWormhole; - (void)setTopSpeed:(double)speed { if ((speed < 1) && (speed > 0)) _topSpeed = speed; } - (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km { // put the code to orbit a planet here double speed = self.topSpeed; if (speed > MAX_RELATIVE) speed = MAX_RELATIVE; [self.nearestWormhole travelToPlanet:aPlanet atSpeed:speed]; } We can use dot notation here too. @end @end Stanford CS193p Fall 2011
  • 63. Coming Up Next Lecture Overview of the Integrated Development Environment (IDE, i.e. Xcode 4) Objective-C in action Concrete example of MVC Major demonstration of all of the above: RPN Calculator (HOMEWORK: if you do not know what an RPN Calculator is, look it up on the internet.) Friday Very simple introduction to using the debugger. Optional. You can figure it out on your own if you want (not too difficult). Next Week Objective-C language in depth Foundation classes: arrays, dictionaries, strings, etc. Dynamic vs. static typing Protocols, categories and much, much more! Stanford CS193p Fall 2011