SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
iPhone Application Development 1
           Janet Huang
            2011/11/23
ALL Schedule

       11/23 - iPhone SDK
               - Objective-C Basic
               - Your First iPhone Application

       11/30 - MVC design & UI
               - GPS/MAP Application
                 (CoreLocation & MapKit)
               - Google Map API
               - LBS Application

       12/07 - Network service
               - Facebook API
               - LBS + Facebook Application
How to study?

   - Stanford CS193p
      - videos in iTunes U
     - all resources on website


   - Apple official document


   - Good book
     - iOS Programming The Big Nerd Ranch Guide
Today’s Topics

• iPhone SDK
• Objective-C
• Common Foundation Class
• Your First iPhone Application
iPhone SDK

• Xcode Tools
 • Xcode
 • Instruments
• iOS Simulator
• iOS Developer Library
iPhone OS overview
Platform Components
OOP Vocabulary
• Class: define the grouping of data and
  code, the “type” of an object
• Instance: a specific allocation of a class
• Method: a “function” that an object knows
  how to perform
• Instance variable: a specific piece of data
  belonging to an object
OOP Vocabulary
• Encapsulation
 •   keep implementation private and separate from
     interface

• Polymorphism
 •   different object, same interface

• Inheritance
 •   hierarchical organization, share code, customize
     or extend behaviors
Inheritance




- Hierarchical relation between classes
- Subclass “inherit” behavior and data from superclass
- Subclasses can use, augment or replace superclass methods
Objective-C

• Classes & Objects
• Messaging
• Properties
• Protocols
Classes and Instances
• In obj-c, classes and instances are both
  objects
• class is the blueprint to create instances
Classes and Objects
• Classes declare state and behavior
• State (data) is maintained using instance
  variables
• Behavior is implemented using methods
• instance variables typically hidden
  •   accessible only using getter/setter methods
Define a Class
public header                         private implementation
#import <Foundation/Foundation.h>     #import "Person.h"
@interface Person : NSObject {         @implementation Person
    // instance variables              - (int)age {
    NSString *name;                       return age;
    int age;                           }
}                                      - (void)setAge:(int)value {
 // method declarations               age = value; }
 - (NSString *)name;                   //... and other methods
 - (void)setName:(NSString *)value;    @end
 - (int)age;
 - (void)setAge:(int)age;
 - (BOOL)canLegallyVote;
 - (void)castBallot;
@end
                    in .h file                       in .m file
A class declaration
Object Creation
• Two steps
  •   allocate memory to store the object

  •   initialize object state

 +alloc
   class method that knows how much memory is needed

 -init
   instance method to set initial values, perform other setup
Implementing your own -init method
   Person *person = nil;
   person = [[Person alloc] init]


   #import “Person.h”

   @implementation Person

   - (id)init {
       if(self = [super init]){
           age = 0;
           name = @”Janet”;
           // do other initialization
       }
   }
                             Create = Allocate + Initialize
Messaging


• Class method and instance method
• Messaging syntax
Terminology
• Message expression
       [receiver method: argument]

• Message
       [receiver method: argument]

• Selector
       [receiver method: argument]

• Method
       The code selected by a message
Method declaration syntax
Class and Instance
          Methods
• instances respond to instance methods
      - (id) init;
      - (float) height;
      - (void) walk;
•   classes respond to class methods
     + (id) alloc;
     + (id) person;
     + (Person *) sharedPerson;
Messaging
 • message syntax
             [receiver message]

             [receiver message:argument]

             [receiver message:arg1 andArg:arg2]

 • message declaration
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

 • call a method or messaging
        [myArray insertObject:anObject atIndex:0]
Instance Variables
• Scope      default @protected only the class and subclass can access
                      @private          only the class can access
                      @public           anyone can access

• Scope syntax
     @interface MyObject : NSObject {
       int foo;
     @private
       int eye;
     @protected                          Protected: foo & bar
       int bar;
                                         Private: eye & jet
     @public
       int forum;                        Public: forum & apology
       int apology;
     @private
       int jet;
     }
•   Forget everything on the previous slide!
    Mark all of your instance variables @private.
    Use @property and “dot notation” to access instance variables.
Accessor methods
•   Create getter/setter methods to access instance
    variable’s value
    @interface MyObject : NSObject {
    @private
    int eye;
    }                          * Note the capitalization
    - (int)eye;                  - instance variables always start with lower case
    - (void)setEye:(int)anInt;   - the letter after “set” MUST be capitalized
    @end

•   Now anyone can access your instance variable using
    “dot syntax”
    someObject.eye = newEyeValue; // set the instance variable
    int eyeValue = someObject.eye; // get the instance variable’s current value
Properties
@property
Let compiler to help you generate setter/getter method
declarations

@interface MyObject : NSObject {   @interface MyObject : NSObject {
@private                           @private
int eye;                           int eye;
}                                  }
@property int eye;                 @property int eye;
- (int)eye;
- (void)setEye:(int)anInt;         @end
@end
Properties
• An @property doesn’t have to match an
    instance variable

@interface MyObject : NSObject {       @interface MyObject : NSObject {
@private                               }
int p_eye;                             @property int eye;
}                                      @end
@property int eye;
@end

                                   *They are all perfectly legal!
Properties
 • Don’t forget to implement it after you
     declare

in .h file                          in .m file
                                   @implementation MyObject
@interface MyObject : NSObject {
                                   - (int)eye {
@private
                                       return eye;
int eye;
                                   }
}
                                   - (void)setEye:(int)anInt {
@property int eye;
                                   eye = anInt;
@end
                                   }
                                   @end
Properties
    @synthesize
     Let compiler to help you with implementation


in .h file                          in .m file
@interface MyObject : NSObject {   @implementation MyObject
@private                           @synthesize eye;
int eye;                           - (int)eye {
}                                      return eye;
@property int eye;                 }
@end                               - (void)setEye:(int)anInt {
                                   eye = anInt;
                                   }
                                   @end
Properties
• Be careful!!
  What’s wrong?
       - (void)setEye:(int)anInt
       {
          self.eye = anInt;
       }                                   Infinite loop!!! :(

  Can happen with the getter too ...

      - (int)eye { if (self.eye > 0) { return eye; } else { return -1; } }
Protocols
@interface MyClass : NSObject <UIApplicationDelegate,
AnotherProtocol> {
}
@end



@protocol MyProtocol
- (void)myProtocolMethod;
@end
Dynamic and static
        typing
• Dynamically-typed object
        id anObject          not id *

• Statically-typed object
        Person * anObject
The null pointer: nil
• explicitly                   if (person == nil) return;

• implicitly                   if (!person) return;

• assignment                   person = nil;

• argument                     [button setTarget: nil];

• send a message to nil
        person = nil;
        [person castBallot];
BOOL typedef
• Obj-C uses a typedef to define BOOL as a
  type
• use YES or NO
           BOOL flag = NO;
           if (flag == YES)
           if (flag)
           if (!flag)
           if (flag != YES)
           flag = YES;
           flag = 1;
Foundation Framework
• NSObject
• Strings
 •   NSString

 •   NSMutableString

• Collections
 •   Array

 •   Dictionary

 •   Set
NSObject
   • Root class
   • Implements many basics
      •   memory management

      •   introspection

      •   object equality

- (NSString *)description is a useful method to override (it’s %@ in NSLog()).
String Constants
• C constant strings
           “c simple strings”

• Obj-C constant strings
          @“obj-c simple strings”

• Constant strings are NSString instances
      NSString *aString = @“Hello World!”;
Format Strings
• use %@ to add objects (similar to printf)
NSString *aString = @”World!”;
NSString *result = [NSString stringWithFormat: @”Hello %@”,
aString];


result: Hello World!


• used for logging
NSLog(@”I am a %@, I have %d items.”, [array className], [array count]);

Log output: I am NSArray, I have 5 items.
NSString
• Create an Obj-C string from a C string
   NSString *fromCString = [NSString stringWithCString:"A C string"
   encoding:NSASCIIStringEncoding];

• Modify an existing string to be a new string
   - (NSString *)stringByAppendingString:(NSString *)string;
   - (NSString *)stringByAppendingFormat:(NSString *)string;
   - (NSString *)stringByDeletingPathComponent;


 for example:
   NSString *myString = @”Hello”;
   NSString *fullString;
   fullString = [myString stringByAppendingString:@” world!”];
NSMutableString
•    Mutable version of NSString
•    Allows a string to be modified
•    Common methods
          + (id)string;
          - (void)appendString:(NSString *)string;
          - (void)appendFormat:(NSString *)format, ...;

for example:
    NSMutableString *newString = [NSMutableString string];
    [newString appendString:@”Hi”];
    [newString appendFormat:@”, my favorite number is: %d”,
    [self favoriteNumber]];
MVC
                          should
                                   did
                       will                 target

                       controller
                                          outlet
                      count
Notification




                                          de
                         data




                                   da
 & KVO




                                             le
                                     ta

                                             ga
                                                        action




                                               te
                                         so
                                           urc
                                           es
              model                                  view
General process for building
iPhone application
         1.	
  Create	
  a	
  simple	
  MVC	
  iPhone	
  applica5on
         2.	
  Build	
  interfaces	
  using	
  Interface	
  builder
         3.	
  Declara5ons
             a.	
  Declaring	
  instance	
  variables
             b.	
  Declaring	
  methods
         4.	
  Make	
  connec5ons
             a.	
  SeDng	
  a	
  pointer
             b.	
  SeDng	
  targets	
  and	
  ac5ons
         5.	
  Implemen5ng	
  methods
             a.	
  Ini5al	
  method
             b.	
  Ac5on	
  methods
         6.	
  Build	
  and	
  run	
  on	
  the	
  simulator
         7.	
  Test	
  applica5on	
  on	
  the	
  device

Contenu connexe

Tendances

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 

Tendances (20)

The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Prototype
PrototypePrototype
Prototype
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
PyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for FoursquarePyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for Foursquare
 
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)
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtext
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About Ruby
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 

En vedette (9)

SAJ @ the Movies - Princess Diaries 2 - Paul Gardner
SAJ @ the Movies - Princess Diaries 2 - Paul GardnerSAJ @ the Movies - Princess Diaries 2 - Paul Gardner
SAJ @ the Movies - Princess Diaries 2 - Paul Gardner
 
Planning and enjoying a vacation in alaska
Planning and enjoying a vacation in alaskaPlanning and enjoying a vacation in alaska
Planning and enjoying a vacation in alaska
 
Iphone course 3
Iphone course 3Iphone course 3
Iphone course 3
 
Of class1
Of class1Of class1
Of class1
 
Message2
Message2Message2
Message2
 
Luke 1:26-35 -Bryan Thomson
Luke 1:26-35 -Bryan ThomsonLuke 1:26-35 -Bryan Thomson
Luke 1:26-35 -Bryan Thomson
 
Of class3
Of class3Of class3
Of class3
 
God is Closer Than You Think - Part 2 - Raewyn Gardner
God is Closer Than You Think - Part 2 - Raewyn GardnerGod is Closer Than You Think - Part 2 - Raewyn Gardner
God is Closer Than You Think - Part 2 - Raewyn Gardner
 
The power of example
The power of exampleThe power of example
The power of example
 

Similaire à Iphone course 1

Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
Petr Dvorak
 

Similaire à Iphone course 1 (20)

iOS Basic
iOS BasiciOS Basic
iOS Basic
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-C
 
OOPS features using Objective C
OOPS features using Objective COOPS features using Objective C
OOPS features using Objective C
 
iOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEEiOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEE
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
A quick and dirty intro to objective c
A quick and dirty intro to objective cA quick and dirty intro to objective c
A quick and dirty intro to objective c
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talk
 
Irving iOS Jumpstart Meetup - Objective-C Session 2
Irving iOS Jumpstart Meetup - Objective-C Session 2Irving iOS Jumpstart Meetup - Objective-C Session 2
Irving iOS Jumpstart Meetup - Objective-C Session 2
 
Modernizes your objective C - Oliviero
Modernizes your objective C - OlivieroModernizes your objective C - Oliviero
Modernizes your objective C - Oliviero
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
From C++ to Objective-C
From C++ to Objective-CFrom C++ to Objective-C
From C++ to Objective-C
 
iOS
iOSiOS
iOS
 
Pioc
PiocPioc
Pioc
 
iOS Einstieg und Ausblick
iOS Einstieg und AusblickiOS Einstieg und Ausblick
iOS Einstieg und Ausblick
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
 
Modernize your Objective-C
Modernize your Objective-CModernize your Objective-C
Modernize your Objective-C
 
Fwt ios 5
Fwt ios 5Fwt ios 5
Fwt ios 5
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
iOS Einstieg und Ausblick - Mobile DevCon 2011 - OPITZ CONSULTING -Stefan Sch...
iOS Einstieg und Ausblick - Mobile DevCon 2011 - OPITZ CONSULTING -Stefan Sch...iOS Einstieg und Ausblick - Mobile DevCon 2011 - OPITZ CONSULTING -Stefan Sch...
iOS Einstieg und Ausblick - Mobile DevCon 2011 - OPITZ CONSULTING -Stefan Sch...
 

Plus de Janet Huang (9)

Transferring Sensing to a Mixed Virtual and Physical Experience
Transferring Sensing to a Mixed Virtual and Physical ExperienceTransferring Sensing to a Mixed Virtual and Physical Experience
Transferring Sensing to a Mixed Virtual and Physical Experience
 
Collecting a Image Label from Crowds Using Amazon Mechanical Turk
Collecting a Image Label from Crowds Using Amazon Mechanical TurkCollecting a Image Label from Crowds Using Amazon Mechanical Turk
Collecting a Image Label from Crowds Using Amazon Mechanical Turk
 
Art in the Crowd
Art in the CrowdArt in the Crowd
Art in the Crowd
 
How to Program SmartThings
How to Program SmartThingsHow to Program SmartThings
How to Program SmartThings
 
Designing physical and digital experience in social web
Designing physical and digital experience in social webDesigning physical and digital experience in social web
Designing physical and digital experience in social web
 
Of class2
Of class2Of class2
Of class2
 
Iphone course 2
Iphone course 2Iphone course 2
Iphone course 2
 
Responsive web design
Responsive web designResponsive web design
Responsive web design
 
Openframworks x Mobile
Openframworks x MobileOpenframworks x Mobile
Openframworks x Mobile
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Iphone course 1

  • 1. iPhone Application Development 1 Janet Huang 2011/11/23
  • 2. ALL Schedule 11/23 - iPhone SDK - Objective-C Basic - Your First iPhone Application 11/30 - MVC design & UI - GPS/MAP Application (CoreLocation & MapKit) - Google Map API - LBS Application 12/07 - Network service - Facebook API - LBS + Facebook Application
  • 3. How to study? - Stanford CS193p - videos in iTunes U - all resources on website - Apple official document - Good book - iOS Programming The Big Nerd Ranch Guide
  • 4. Today’s Topics • iPhone SDK • Objective-C • Common Foundation Class • Your First iPhone Application
  • 5. iPhone SDK • Xcode Tools • Xcode • Instruments • iOS Simulator • iOS Developer Library
  • 7.
  • 8.
  • 9.
  • 10.
  • 12. OOP Vocabulary • Class: define the grouping of data and code, the “type” of an object • Instance: a specific allocation of a class • Method: a “function” that an object knows how to perform • Instance variable: a specific piece of data belonging to an object
  • 13. OOP Vocabulary • Encapsulation • keep implementation private and separate from interface • Polymorphism • different object, same interface • Inheritance • hierarchical organization, share code, customize or extend behaviors
  • 14. Inheritance - Hierarchical relation between classes - Subclass “inherit” behavior and data from superclass - Subclasses can use, augment or replace superclass methods
  • 15. Objective-C • Classes & Objects • Messaging • Properties • Protocols
  • 16. Classes and Instances • In obj-c, classes and instances are both objects • class is the blueprint to create instances
  • 17. Classes and Objects • Classes declare state and behavior • State (data) is maintained using instance variables • Behavior is implemented using methods • instance variables typically hidden • accessible only using getter/setter methods
  • 18. Define a Class public header private implementation #import <Foundation/Foundation.h> #import "Person.h" @interface Person : NSObject { @implementation Person // instance variables - (int)age { NSString *name; return age; int age; } } - (void)setAge:(int)value { // method declarations age = value; } - (NSString *)name; //... and other methods - (void)setName:(NSString *)value; @end - (int)age; - (void)setAge:(int)age; - (BOOL)canLegallyVote; - (void)castBallot; @end in .h file in .m file
  • 20. Object Creation • Two steps • allocate memory to store the object • initialize object state +alloc class method that knows how much memory is needed -init instance method to set initial values, perform other setup
  • 21. Implementing your own -init method Person *person = nil; person = [[Person alloc] init] #import “Person.h” @implementation Person - (id)init { if(self = [super init]){ age = 0; name = @”Janet”; // do other initialization } } Create = Allocate + Initialize
  • 22. Messaging • Class method and instance method • Messaging syntax
  • 23. Terminology • Message expression [receiver method: argument] • Message [receiver method: argument] • Selector [receiver method: argument] • Method The code selected by a message
  • 25. Class and Instance Methods • instances respond to instance methods - (id) init; - (float) height; - (void) walk; • classes respond to class methods + (id) alloc; + (id) person; + (Person *) sharedPerson;
  • 26. Messaging • message syntax [receiver message] [receiver message:argument] [receiver message:arg1 andArg:arg2] • message declaration - (void)insertObject:(id)anObject atIndex:(NSUInteger)index; • call a method or messaging [myArray insertObject:anObject atIndex:0]
  • 27. Instance Variables • Scope default @protected only the class and subclass can access @private only the class can access @public anyone can access • Scope syntax @interface MyObject : NSObject { int foo; @private int eye; @protected Protected: foo & bar int bar; Private: eye & jet @public int forum; Public: forum & apology int apology; @private int jet; }
  • 28. Forget everything on the previous slide! Mark all of your instance variables @private. Use @property and “dot notation” to access instance variables.
  • 29. Accessor methods • Create getter/setter methods to access instance variable’s value @interface MyObject : NSObject { @private int eye; } * Note the capitalization - (int)eye; - instance variables always start with lower case - (void)setEye:(int)anInt; - the letter after “set” MUST be capitalized @end • Now anyone can access your instance variable using “dot syntax” someObject.eye = newEyeValue; // set the instance variable int eyeValue = someObject.eye; // get the instance variable’s current value
  • 30. Properties @property Let compiler to help you generate setter/getter method declarations @interface MyObject : NSObject { @interface MyObject : NSObject { @private @private int eye; int eye; } } @property int eye; @property int eye; - (int)eye; - (void)setEye:(int)anInt; @end @end
  • 31. Properties • An @property doesn’t have to match an instance variable @interface MyObject : NSObject { @interface MyObject : NSObject { @private } int p_eye; @property int eye; } @end @property int eye; @end *They are all perfectly legal!
  • 32. Properties • Don’t forget to implement it after you declare in .h file in .m file @implementation MyObject @interface MyObject : NSObject { - (int)eye { @private return eye; int eye; } } - (void)setEye:(int)anInt { @property int eye; eye = anInt; @end } @end
  • 33. Properties @synthesize Let compiler to help you with implementation in .h file in .m file @interface MyObject : NSObject { @implementation MyObject @private @synthesize eye; int eye; - (int)eye { } return eye; @property int eye; } @end - (void)setEye:(int)anInt { eye = anInt; } @end
  • 34. Properties • Be careful!! What’s wrong? - (void)setEye:(int)anInt { self.eye = anInt; } Infinite loop!!! :( Can happen with the getter too ... - (int)eye { if (self.eye > 0) { return eye; } else { return -1; } }
  • 35. Protocols @interface MyClass : NSObject <UIApplicationDelegate, AnotherProtocol> { } @end @protocol MyProtocol - (void)myProtocolMethod; @end
  • 36. Dynamic and static typing • Dynamically-typed object id anObject not id * • Statically-typed object Person * anObject
  • 37. The null pointer: nil • explicitly if (person == nil) return; • implicitly if (!person) return; • assignment person = nil; • argument [button setTarget: nil]; • send a message to nil person = nil; [person castBallot];
  • 38. BOOL typedef • Obj-C uses a typedef to define BOOL as a type • use YES or NO BOOL flag = NO; if (flag == YES) if (flag) if (!flag) if (flag != YES) flag = YES; flag = 1;
  • 39. Foundation Framework • NSObject • Strings • NSString • NSMutableString • Collections • Array • Dictionary • Set
  • 40. NSObject • Root class • Implements many basics • memory management • introspection • object equality - (NSString *)description is a useful method to override (it’s %@ in NSLog()).
  • 41. String Constants • C constant strings “c simple strings” • Obj-C constant strings @“obj-c simple strings” • Constant strings are NSString instances NSString *aString = @“Hello World!”;
  • 42. Format Strings • use %@ to add objects (similar to printf) NSString *aString = @”World!”; NSString *result = [NSString stringWithFormat: @”Hello %@”, aString]; result: Hello World! • used for logging NSLog(@”I am a %@, I have %d items.”, [array className], [array count]); Log output: I am NSArray, I have 5 items.
  • 43. NSString • Create an Obj-C string from a C string NSString *fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding]; • Modify an existing string to be a new string - (NSString *)stringByAppendingString:(NSString *)string; - (NSString *)stringByAppendingFormat:(NSString *)string; - (NSString *)stringByDeletingPathComponent; for example: NSString *myString = @”Hello”; NSString *fullString; fullString = [myString stringByAppendingString:@” world!”];
  • 44. NSMutableString • Mutable version of NSString • Allows a string to be modified • Common methods + (id)string; - (void)appendString:(NSString *)string; - (void)appendFormat:(NSString *)format, ...; for example: NSMutableString *newString = [NSMutableString string]; [newString appendString:@”Hi”]; [newString appendFormat:@”, my favorite number is: %d”, [self favoriteNumber]];
  • 45. MVC should did will target controller outlet count Notification de data da & KVO le ta ga action te so urc es model view
  • 46. General process for building iPhone application 1.  Create  a  simple  MVC  iPhone  applica5on 2.  Build  interfaces  using  Interface  builder 3.  Declara5ons a.  Declaring  instance  variables b.  Declaring  methods 4.  Make  connec5ons a.  SeDng  a  pointer b.  SeDng  targets  and  ac5ons 5.  Implemen5ng  methods a.  Ini5al  method b.  Ac5on  methods 6.  Build  and  run  on  the  simulator 7.  Test  applica5on  on  the  device