0% found this document useful (0 votes)
10 views

Lecture 03 Iphone Programming

The document provides an overview of topics to be covered in class including Objective-C, the Foundation framework, memory management, instance variables, methods, properties, protocols and delegates.

Uploaded by

jmarquez01a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 03 Iphone Programming

The document provides an overview of topics to be covered in class including Objective-C, the Foundation framework, memory management, instance variables, methods, properties, protocols and delegates.

Uploaded by

jmarquez01a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

CS193p

Spring 2010

Monday, April 5, 2010


Announcements
You should have received an e-mail by now
If you received e-mail approving enrollment, but are not in Axess, do it!
If you have any questions, please ask via e-mail or after class.

If you have not installed SDK and


gotten it working, talk to us after class.

Homework
Strongly recommend trying a submission today even if you’re not yet done
Multiple attempted submissions is no problem
Assignments are to be done individually (except approved pairs for final project)
Honor code applies
Any questions about the homework?

Monday, April 5, 2010


Communication

E-mail
Questions are best sent to [email protected]
Sending directly to instructor or TA’s risks slow response.

Web Site
Very Important!
http://cs193p.stanford.edu
All lectures, assignments, code, etc. will be there.
This site will be your best friend when it comes to getting info.

Monday, April 5, 2010


Office Hours
Andreas
Monday 6pm to 8pm
Thursday 6pm to 8pm
Gates B26A
Bring your Stanford ID card for access to the building

Sonali
Friday 11am to 1pm
Thursday 1pm to 3pm
Gates B26B

Monday, April 5, 2010


Today’s Topics
Objective-C
Instance Variables
Methods (Class and Instance)
Properties
Dynamic vs. Static Binding
Introspection
Protocols and Delegates

Foundation Framework
NSObject, NSString, NSMutableString
NSNumber, NSValue, NSData, NSDate
NSArray, NSDictionary, NSSet
NSUserDefaults, etc.

Memory Management
Allocating and initializing objects
Reference Counting

Monday, April 5, 2010


Header -> Implementation
#import <Foundation/Foundation.h>

@interface CalculatorBrain : NSObject


{
double operand;
}

- (void)setOperand:(double)anOperand;

- (double)performOperation:(NSString *)operation;

@end

Monday, April 5, 2010


Header -> Implementation
#import “CalculatorBrain.h”

@implementation CalculatorBrain

- (void)setOperand:(double)anOperand
{
}

- (double)performOperation:(NSString *)operation
{
}

@end

Monday, April 5, 2010


Instance Variables
By default, they are “protected”
Only methods in the class itself and superclass can see them

Can be marked private with @private

Can be marked public with @public


Don’t do it! Use properties instead. Later.

@interface Ship : Vehicle


{
Size size;
@private
int turrets;
@public
NSString *dontDoThisString;
}

Monday, April 5, 2010


Methods
If public, declare them in .h file.
Public or private, implement them in .m file.

- (NSArray *)findShipsAtPoint:(CGPoint)bombDrop withDamage:(BOOL)damaged;

1. Specify class method with + or instance method with - (more on this later)
2. Then return type in parentheses (can be void if returns nothing)
3. Then first part of name of method, always ending in : unless zero args
4. Then type of first argument in parentheses
5. Then name of first argument
6. If more arguments, next comes a required space, then repeat 3-5
7. Then semicolon if declaring , or code inside { } if implementing
Spaces allowed between any of the above steps, but no spaces in step 3 or 5

Monday, April 5, 2010


Instance Methods
Declarations start with a - (a dash)

“Normal” methods you are used to

Instance variables usable inside implementation

Receiver of message can be self or super too


self calls method in calling object (recursion okay)
super calls method on self, but uses superclass’s implementation
If a superclass calls a method on self, it will use your implementation

Calling syntax:
BOOL destroyed = [ship dropBomb:bombType at:dropPoint];

Monday, April 5, 2010


Class Methods
Declarations start with a + (a plus sign)
Usually used to ask a class to create an instance
Sometimes hands out “shared” instances
Or performs some sort of utility function
Not sent to an instance, so no instance
variables can be used in the implementation
of a class method (and be careful about self
in a class method ... it means the class object)
Calling syntax:
Ship *ship = [Ship shipWithTurrentCount:3];
Ship *mother = [Ship motherShip];
int size = [Ship turretCountForShipSize:shipSize];

Monday, April 5, 2010


Properties
Note lowercase “o” then uppercase “O”
Replaces Use this convention for properties.
- (double)operand;
- (void)setOperand:(double)anOperand;
with
@property double operand;

Implementation replaced with ...


@synthesize operand; // if there’s an instance variable operand
@synthesize operand = op; // if correspon ding ivar is op

Callers use dot notation to set and get


double x = brain.operand;
brain.operand = newOperand;

Monday, April 5, 2010


Properties
Properties can be “read only” (no setter)
@property (readonly) double operand;

You can use @synthesize and still implement


the setter or the getter yourself (one of them)
- (void)setMaximumSpeed:(int)speed
{
if (speed > 65) {
speed = 65;
}
maximumSpeed = speed;
}

@synthesize maximumSpeedwould still create


the getter even with above implementation

Monday, April 5, 2010


Properties
Using your own (self’s) properties

What does this code do?


- (int)maximumSpeed
{
if (self.maximumSpeed > 65) {
return 65;
} else {
return maximumSpeed;
}
}

Infinite loop!

Monday, April 5, 2010


nil
nil is the value that a variable which is a
pointer to an object (id or Foo *) has when it
is not currently pointing to anything.
Like “zero” for a primitive type (int, double, etc.)
(actually, it is not just “like” zero, it is zero)

NSObject sets all its instance variables to “zero”


(thus nil for objects)
Can be implicitly tested in an if statement:
if (obj) { } means “if the obj pointer is not nil”

Sending messages to nil is (mostly) A-OK!


If the method returns a value, it will return 0
Be careful if return value is a C struct though! Results undefined.
e.g. CGPoint p = [obj getLocation]; // if obj is nil, p undefined

Monday, April 5, 2010


BOOL
BOOL is Objective-C’s boolean value
Can also be tested implicitly
YES means “true,” NO means “false”
NO is zero, YES is anything else

if (flag) { } means “if flag is YES”


if (!flag) { } means “if flag is NO”
if (flag == YES) { } means “if flag is YES”
if (flag != NO) { } means “if flag is not NO”

Monday, April 5, 2010


Dynamic vs. Static
NSString * versus id
id * (almost never used, pointer to a pointer)
Compiler can check NSString *
Compiler will accept any message sent to id
that it knows about (i.e. it has to know some
object somewhere that knows that message)
“Force” a pointer by casting: (NSString *)foo

Regardless of what compiler says, your


program will crash if you send a message to
an object that does not implement that method

Monday, April 5, 2010


Examples
@interface Ship : Vehicle
- (void)shoot;
@end

Ship *s = [[Ship alloc] init];


[s shoot];

Vehicle *v = s;
[v shoot]; // compiler will warn, no crash at runtime in this case

Ship *castedVehicle = (Ship *)someVehicle; // dangerous!!!


[castedVehicle shoot]; // compiler won’t warn, might crash

id obj = ...;
[obj shoot]; // compiler won’t warn, might crash
[obj lskdfjslkfjslfkj]; // compiler will warn, runtime crash
[(id)someVehicle shoot]; // no warning, might crash

Vehicle *tank = [[Tank alloc] init];


[(Ship *)tank shoot]; // no warning, crashes at runtime

Monday, April 5, 2010


Introspection
isKindOfClass:
Can be sent to any object and takes inheritance into account
Takes a Class object as its argument (where do I get one?)
[NSString class] or [CalculatorBrain class] or [obj class]
Syntax: if ([obj isKindOfClass:[NSString class]]) {

isMemberOfClass:
Can be sent to any object but does NOT take inheritance into account
Syntax: if ([obj isMemberOfClass:[NSString class]]) {
This would be false if obj were NSMutableString

className
Returns the name of the class as an NSString
Syntax: NSString *name = [obj className];

Monday, April 5, 2010


Introspection
respondsToSelector:
Can be sent to any NSObject to find out if it implements a certain method
Needs a special method token as its argument (a “selector”)
@selector(shoot) or @selector(foo:bar:)
Syntax: if ([obj respondsToSelector:@selector(shoot)]) {

SEL versus @selector()


The “type” of a selector is SEL, e.g., - (void)performSelector:(SEL)action
Important use: set up target/action outside of Interface Builder
Syntax: [btn addTarget:self action:@selector(shoot) ...]

performSelector:
Send a message to an NSObject using a selector
Syntax: [obj performSelector:@selector(shoot)]
Syntax: [obj performSelector:@selector(foo:) withObject:x]

Monday, April 5, 2010


Introspection
Example

id anObject = ...;
SEL aSelector = @selector(someMethod:);
if ([anObject respondsToSelector:aSelector]) {
[anObject performSelector:aSelector withObject:self];
}

Monday, April 5, 2010


Foundation Framework
NSObject
Base class for pretty much every object in iPhone SDK Frameworks
Implements memory management primitives (more on this in a moment)
and introspection
- (NSString *)description is a useful method to override, it’s %@ in NSLog

NSString
International (any language) strings
Used throughout all of iPhone SDK instead of C’s char *
Cannot be modified!
Usually returns you a new NSString when you ask it to do something
Tons of utility functions (case, URLs, conversion to/from lots of other
types, substrings, file system paths, and much much more!)
Compiler will create a constant one for you with @”foo”

NSMutableString
Mutable version of NSString
Can do some of the things NSString can do without making a new one

Monday, April 5, 2010


Foundation Framework
NSNumber
Object wrapper around primitive types: int, float, double, BOOL, etc.
Use it when you want to store those in an NSArray or other object

NSValue
Generic object wrapper for any non-object data type.
Useful for wrapping graphics things like a CGPoint or CGRect

NSData
“Bag of bits”
Used to save/restore/transmit data throughout the SDK

NSDate
Can be used to find out the time now or store a past/future time
See also NSCalendar, NSDateFormatter, NSDateComponents

Monday, April 5, 2010


Coming Up
Tuesday: Assignment #1 due by 11:59pm

Wednesday: Demos of (most of) this stuff


Will be very relevant to the homework this week
which will be assigned after class on Wednesday and due next Tuesday 11:59pm

Next Week: Custom Views, Navigation Controllers

Monday, April 5, 2010

You might also like