SlideShare a Scribd company logo
1 of 20
Download to read offline
CS193p
                           Spring 2010




Thursday, April 29, 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?



Thursday, April 29, 2010
Communication

                           E-mail
                           Questions are best sent to cs193p@cs.stanford.edu
                           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.




Thursday, April 29, 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


Thursday, April 29, 2010
Instance Variables
                           By 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 @public
                           Don’t do it! Use properties instead. Later.


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


Thursday, April 29, 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




Thursday, April 29, 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’ implementation
                                                                          s
                           If 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
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];

Thursday, April 29, 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;

Thursday, April 29, 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

Thursday, April 29, 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!


Thursday, April 29, 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
                                                                /

Thursday, April 29, 2010
BOOL
                           BOOL is Objective-C’ boolean value
                                              s
                           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”




Thursday, April 29, 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



Thursday, April 29, 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
                                             /


Thursday, April 29, 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];



Thursday, April 29, 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]



Thursday, April 29, 2010
Introspection
                           Example

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




Thursday, April 29, 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’ %@ in NSLog
                                                                                   s


                       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

Thursday, April 29, 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




Thursday, April 29, 2010

More Related Content

What's hot

Basic Mechanism of OOPL
Basic Mechanism of OOPLBasic Mechanism of OOPL
Basic Mechanism of OOPLkwatch
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaRafael Magana
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch岳華 杜
 
Java class 3
Java class 3Java class 3
Java class 3Edureka!
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_springGuo Albert
 
Java class 4
Java class 4Java class 4
Java class 4Edureka!
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONLalitkumar_98
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesCtOlaf
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic ProgrammingPingLun Liao
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013rivierarb
 

What's hot (20)

Basic Mechanism of OOPL
Basic Mechanism of OOPLBasic Mechanism of OOPL
Basic Mechanism of OOPL
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Fast Forward To Scala
Fast Forward To ScalaFast Forward To Scala
Fast Forward To Scala
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch
 
Java class 3
Java class 3Java class 3
Java class 3
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
 
Java class 4
Java class 4Java class 4
Java class 4
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-properties
 
First fare 2010 java-introduction
First fare 2010 java-introductionFirst fare 2010 java-introduction
First fare 2010 java-introduction
 
Rejectkaigi 2010
Rejectkaigi 2010Rejectkaigi 2010
Rejectkaigi 2010
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Python3
Python3Python3
Python3
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013
 
JavaScript Essentials
JavaScript EssentialsJavaScript Essentials
JavaScript Essentials
 

Viewers also liked

Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)
Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)
Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)Nguyen Thanh Xuan
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome EconomyHelge Tennø
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsBarry Feldman
 

Viewers also liked (7)

Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)
Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)
Lecture 2#- (Intro to Obj-C, Interface Builder and Xcode)
 
Lecture 06
Lecture 06Lecture 06
Lecture 06
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
String slide
String slideString slide
String slide
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post Formats
 

Similar to Lecture 03

JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.pptParikhitGhosh1
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Altece
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking introHans Jones
 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphismsanjay joshi
 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphismumesh patil
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismAndiNurkholis1
 
Objective-C A Beginner's Dive
Objective-C A Beginner's DiveObjective-C A Beginner's Dive
Objective-C A Beginner's DiveAltece
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Bhanwar Singh Meena
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 

Similar to Lecture 03 (20)

JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)
 
Java
JavaJava
Java
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphism
 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphism
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Objective-C A Beginner's Dive
Objective-C A Beginner's DiveObjective-C A Beginner's Dive
Objective-C A Beginner's Dive
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
java poly ppt.pptx
java poly ppt.pptxjava poly ppt.pptx
java poly ppt.pptx
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
C#
C#C#
C#
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 

Lecture 03

  • 1. CS193p Spring 2010 Thursday, April 29, 2010
  • 2. 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? Thursday, April 29, 2010
  • 3. Communication E-mail Questions are best sent to cs193p@cs.stanford.edu 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. Thursday, April 29, 2010
  • 4. 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 Thursday, April 29, 2010
  • 5. Instance Variables By 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 @public Don’t do it! Use properties instead. Later. @interface Ship : Vehicle { Size size; @private int turrets; @public NSString *dontDoThisString; } Thursday, April 29, 2010
  • 6. 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 Thursday, April 29, 2010
  • 7. 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’ implementation s If 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
  • 8. 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]; Thursday, April 29, 2010
  • 9. 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; Thursday, April 29, 2010
  • 10. 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 Thursday, April 29, 2010
  • 11. 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! Thursday, April 29, 2010
  • 12. 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 / Thursday, April 29, 2010
  • 13. BOOL BOOL is Objective-C’ boolean value s 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” Thursday, April 29, 2010
  • 14. 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 Thursday, April 29, 2010
  • 15. 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 / Thursday, April 29, 2010
  • 16. 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]; Thursday, April 29, 2010
  • 17. 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] Thursday, April 29, 2010
  • 18. Introspection Example id anObject = ...; SEL aSelector = @selector(someMethod:); if ([anObject respondsToSelector:aSelector]) { [anObject performSelector:aSelector withObject:self]; } Thursday, April 29, 2010
  • 19. 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’ %@ in NSLog s 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 Thursday, April 29, 2010
  • 20. 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 Thursday, April 29, 2010