lecture 03

20
CS193p Spring 2010 Thursday, April 29, 2010

Upload: nguyen-thanh-xuan

Post on 15-May-2015

266 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Lecture 03

CS193pSpring 2010

Thursday, April 29, 2010

Page 2: Lecture 03

AnnouncementsYou should have received an e-mail by nowIf 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 andgotten it working, talk to us after class.

HomeworkStrongly recommend trying a submission today even if you’re not yet doneMultiple attempted submissions is no problemAssignments are to be done individually (except approved pairs for final project)Honor code appliesAny questions about the homework?

Thursday, April 29, 2010

Page 3: Lecture 03

Communication

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

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

Thursday, April 29, 2010

Page 4: Lecture 03

Today’s TopicsObjective-CInstance VariablesMethods (Class and Instance)PropertiesDynamic vs. Static BindingIntrospectionProtocols and Delegates

Foundation FrameworkNSObject, NSString, NSMutableStringNSNumber, NSValue, NSData, NSDateNSArray, NSDictionary, NSSetNSUserDefaults, etc.

Memory ManagementAllocating and initializing objectsReference Counting

Thursday, April 29, 2010

Page 5: Lecture 03

Instance VariablesBy default, they are “protected”Only methods in the class itself and subclasses can see them

Can be marked private with @private

Can be marked public with @publicDon’t do it! Use properties instead. Later.

@interface Ship : Vehicle{ Size size;@private int turrets;@public NSString *dontDoThisString;}

Thursday, April 29, 2010

Page 6: Lecture 03

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

or instance method with -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 args4. Then type of first argument in parentheses5. Then name of first argument6. If more arguments, next comes a required space, then repeat 3-57. Then semicolon if declaringSpaces allowed between any of the above steps, but no spaces in step 3 or 5

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

1. Specify class method with + (more on this later)

, or code inside { } if implementing

;

Thursday, April 29, 2010

Page 7: Lecture 03

Instance MethodsDeclarations start with a - (a dash)

“Normal” methods you are used to

Instance variables usable inside implementation

Receiver of message can be self or super tooself calls method in calling object (recursion okay)super calls method on self, but uses superclass’s implementationIf a superclass calls a method on self, it will use your implementation

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

Thursday, April 29, 2010

Page 8: Lecture 03

Class MethodsDeclarations start with a + (a plus sign)Usually used to ask a class to create an instanceSometimes hands out “shared” instancesOr performs some sort of utility functionNot sent to an instance, so no instancevariables can be used in the implementationof a class method (and be careful about selfin a class method ... it means the class object)Calling syntax:Ship *ship = [Ship shipWithTurrentCount:3];

int size = [Ship turretCountForShipSize:shipSize];Ship *mother = [Ship motherShip];

Thursday, April 29, 2010

Page 9: Lecture 03

Properties- (double)operand;- (void)setOperand:(double)anOperand;

@synthesize operand; // if there’s an instance variable operand

@property double operand;

Replaces

with

Implementation replaced with ...

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

Callers use dot notation to set and get

Note lowercase “o” then uppercase “O”Use this convention for properties.

@synthesize operand = op; // if corresponding ivar is op

Thursday, April 29, 2010

Page 10: Lecture 03

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

You can use @synthesize and still implementthe setter or the getter yourself (one of them)

@synthesize maximumSpeed would still createthe getter even with above implementation

- (void)setMaximumSpeed:(int)speed{ if (speed > 65) { speed = 65; } maximumSpeed = speed;}

Thursday, April 29, 2010

Page 11: Lecture 03

PropertiesUsing your own (self’s) properties

What does this code do?

Infinite loop!

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

Thursday, April 29, 2010

Page 12: Lecture 03

nilnil is the value that a variable which is apointer to an object (id or Foo *) has when itis 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 0Be careful if return value is a C struct though! Results undefined.e.g. CGPoint p = [obj getLocation]; // if obj is nil, p undefined

Thursday, April 29, 2010

Page 13: Lecture 03

BOOLBOOL is Objective-C’s boolean valueCan also be tested implicitlyYES 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”

Thursday, April 29, 2010

Page 14: Lecture 03

Dynamic vs. StaticNSString * versus idid * (almost never used, pointer to a pointer)Compiler can check NSString *Compiler will accept any message sent to idthat it knows about (i.e. it has to know someobject somewhere that knows that message)“Force” a pointer by casting: (NSString *)fooRegardless of what compiler says, yourprogram will crash if you send a message toan object that does not implement that method

Thursday, April 29, 2010

Page 15: Lecture 03

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

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

Examples

Thursday, April 29, 2010

Page 16: Lecture 03

IntrospectionisKindOfClass:Can be sent to any object and takes inheritance into accountTakes 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 accountSyntax: if ([obj isMemberOfClass:[NSString class]]) {This would be false if obj were NSMutableString

classNameReturns the name of the class as an NSStringSyntax: NSString *name = [obj className];

Thursday, April 29, 2010

Page 17: Lecture 03

IntrospectionrespondsToSelector:Can be sent to any NSObject to find out if it implements a certain methodNeeds 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)actionImportant use: set up target/action outside of Interface BuilderSyntax: [btn addTarget:self action:@selector(shoot) ...]

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

Thursday, April 29, 2010

Page 18: Lecture 03

IntrospectionExample

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

Thursday, April 29, 2010

Page 19: Lecture 03

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

NSStringInternational (any language) stringsUsed 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 somethingTons of utility functions (case, URLs, conversion to/from lots of othertypes, substrings, file system paths, and much much more!)Compiler will create a constant one for you with @”foo”

NSMutableStringMutable version of NSStringCan do some of the things NSString can do without making a new one

Thursday, April 29, 2010

Page 20: Lecture 03

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

NSValueGeneric 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

NSDateCan be used to find out the time now or store a past/future timeSee also NSCalendar, NSDateFormatter, NSDateComponents

Thursday, April 29, 2010