SlideShare a Scribd company logo
iOS DEVELOPMENT
AGENDA
  • Introduction about iOS

  • Objective-C knowlegde
      Introduction
      OOP
      Objective-C syntax
      Object Lifecycle & Memory Managenment
      Foundation Frameworks

  • MVC Pattern

  • Build up an View-based Application
      Xcode
      Application Lifecycle
      View and Custom View
      Interface Builder
      View Controller Lifecycle
      Navigation Controllers
      Common UIControl (UIButton, UITable,...)
      Multi resolution and Rotation
      Deployment
                                                 2
Introduction about iOS




                         3
Introduction about iOS
  • What is iOS?
      iOS (known as iPhone OS prior to June 2010) is Apple’s mobile operating
      system.
      Originally developed for the iPhone, it has since been extended to support
      other Apple devices such as the iPod Touch, iPad and Apple TV.

  • iOS & Devices - History & Evolution
      iOS version:
           Common: iOS 4.0 & later
           Newest: iOS 6.0
           Our support: iOS 3.0 & later
      Device:
           iPhone:
                1st Generation, 3G, 3GS
                 4, 4S - Retina Display
           iPod Touch: 1st, 2nd, 3rd, 4th (Retina display) Generation
           iPad: 1, 2, New iPad (Retina display)
           Apple TV

  • Types of iOS Applications
       Native applications
       Web applications

                                                                                   4
Introduction about iOS




                         5
Introduction about iOS




                         6
Introduction about iOS
      iOS Technology Overview: iOS Layers


                                     UIKit, MapKit, Printing, Push Notification,
Objective C
                                     GameKit,….
                                     Core Graphic, Core Audio, Core Video,
                                     Core Animation,…
                                     Core Foundation, Address book, Core
                                     Locaion, …

     C                               Sercurity, External Accessory , System (
                                     threading, networking,...) ...
Introduction about iOS
 iOS Technology Overview: iOS Layers


  UIKit framework
Introduction about iOS
 iOS Technology Overview: Platform Component
Introduction about iOS
 iOS Technology Overview: Platform Component
Introduction about iOS
 iOS Technology Overview: Platform Component
Introduction about iOS
 iOS Technology Overview: Platform Component
Introduction about iOS
 iOS Technology Overview: Platform Component
Objective-C knowledge
Objective-C knowledge
 Introduction




   • Mix C with Smalltalk.
   • Message passing (defining method).
   • Single inheritance, classes inherit from one and only one superclass.
   • Dynamic binding.
   • It’s OOP language.
Objective-C knowledge
 Introduction

   • Primitive data types : int, float, double,….
   • Conditional structure:




   • Loops:
Objective-C knowledge
 OOP
    • Class: defines 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 (or “ivar”): a specific piece of data belonging to an object.


    • Encapsulation
    • Polymorphism
    • Inheritance

    Use self to access methods, properties,...
    Use super to access methods, properties,... of parent class.
Objective-C knowledge
 OOP
Objective-C knowledge
 Objective-C syntax : Defining a Class

Class interface declared in header file (.h)   Class Implementation (.m)
Objective-C knowledge
 Objective-C syntax : Message syntax
    (BOOL) sendMailTo: (NSString*) address withBody: (NSString*) body;

 BOOL : Return type

 sendMailTo :First part of method name.
 withBody :Second part of method name.
 sendMailTo: withBody: :full method name or is called selector.

 address :first argument.
 body :second argument.

 sendMailTo: (NSString*) address :First message.
 withBody: (NSString*) body :second message.



  BOOL isSuccess = [self sendMailTo: @”yp@yp.com” withBody: @”YP”];
Objective-C knowledge
 Objective-C syntax : Instance method
 • Starts with a dash
      - (BOOL) sendMailTo: (NSString*) address withBody: (NSString*) body;

 •“Normal” methods you are used to

 • Can access instance variables inside as if they were locals

 • Can send messages to self and super inside

 • Example calling syntax:
     BOOL isSuccess = [account sendMailTo: @”yp@yp.com” withBody: @”YP”];
Objective-C knowledge
 Objective-C syntax : Class method
 • Starts with a plus. Used for allocation, singletons, utilities
      + (id) alloc;
      + (NSString*) stringWithString: (NSString*) string;

 • Can not access instance variables inside

 • Example calling syntax (a little different from instance methods)
     NSString *string = [NSString stringWithString:@"YP"];
Objective-C knowledge
 Objective-C syntax : Instance Variables
   - By default, instance variables are @protected (only the class and
   subclasses can access).
   -Can be marked @private (only the class can access) or @public
   (anyone can access).

     @interface Person: NSObject
     {
         int age;
     @private                              @private: heart
         int heart;                        @protected: age, hand, leg
     @protected                            @public: face, body
         int hand;
         int leg;
     @public
         int face;
         int body;
     }
Objective-C knowledge
 Objective-C syntax : Properties

   @interface MyObject : NSObject        @interface MyObject : NSObject
   {                                     {
   @private                              @private
        int age;                             int age;
   }                                     }
   - (int) age;                          @property int age;
   - (void)setAge:(int)anInt;            @end
   @end


     - Mark all of your instance variables @private.
     - Generate set/get method declarations.
     - @property (readonly) int age; // does not declare a setAge method
     - Use “dot notation” to access instance variables.
     - By default, get/set is thread-safe method.
          + @property (nonatomic) int age; no thread-safe method
Objective-C knowledge
 Objective-C syntax : Properties
    Other typing ways to define a property

  @interface MyObject : NSObject        @interface MyObject : NSObject
  {                                     {
      int iAge;
  }                                     }
  @property int age;                    @property int age;
  @end                                  @end




       But whatever you declare, you must then implement
Objective-C knowledge
 Objective-C syntax : Properties
             .h                               .m

@interface MyObject : NSObject     @implementation MyObject
{                                  - (int)age {
    int age;                            return age;
}                                  }
@property int age;
@end                               - (void)setAge:(int)anInt {
                                        age= anInt;
                                   }
                                   @end
Objective-C knowledge
 Objective-C syntax : Properties
            .h                                .m

@interface MyObject : NSObject     @implementation MyObject
{                                  - (int) age{
    int iAge;                           return iAge;
}                                  }
@property int age;
@end                               - (void)setAge:(int)anInt {
                                        iAge = anInt;
                                   }
                                   @end
Objective-C knowledge
 Objective-C syntax : Properties
             .h                               .m

@interface MyObject : NSObject     @implementation MyObject
{                                  - (int) age {
                                         ???
}                                  }
@property int age;
@end                               - (void)setAge:(int)anInt {
                                         ???
                                   }
                                   @end
Objective-C knowledge
 Objective-C syntax : Properties
  Let the compiler help you with implementation using @synthesize!
            .h                                 .m
 @interface MyObject : NSObject     @implementation MyObject
 @property int age;                 @synthesize age;
 @end                               @end

 @interface MyObject : NSObject{     @implementation MyObject
     int age;                        @synthesize age;
 }                                   @end
 @property int age;
 @end

 @interface MyObject : NSObject{      @implementation MyObject
     int iAge;                        @synthesize age= iAge;
 }                                    @end
 @property int age;
 @end
Objective-C knowledge
 Objective-C syntax : Properties


   If you use @synthesize, you can still implement one or the other
   @implementation MyObject
   @synthesize age;
   - (void)setAge:(int)anInt {
        if (anInt > 0) age= anInt;
   }
   @end
Objective-C knowledge
 Objective-C syntax : Properties
   How to use?

       int x = self.age;
       int x = [self age];

       self.age = x;
       [self setAge: x];




  And, there’s more to think about when a @property is an object. We
  will discuss later.
Objective-C knowledge
 Objective-C syntax : Dynamic Binding
   - Decision about code to run on message send happens at runtime
   Not at compile time.
    If neither the class of the receiving object nor its superclasses implements
   that method: crash!

   - It is legal (and sometimes even good code) to “cast” a pointer
   But we usually do it only after we’ve used “introspection” to find out more
   about the object.

   id obj = [[MyObject alloc] init];
   NSString *s = (NSString *)obj; // dangerous ... best know what you are
   doing
   [s setAge: 1]; //warning…crash when runtime

   id obj = [[Person alloc] init];
   NSString *s = (NSString *)obj; // dangerous ... best know what you are
   doing
   [s setAge: 1]; //warning…work well.
Objective-C knowledge
 Objective-C syntax : Introspection
   All objects that inherit from NSObject know these methods

   - isKindOfClass: returns true whether an object is that kind of class
                   (inheritance included)
   - isMemberOfClass: returns true whether an object is that kind of class (no
                             inheritance)
   Ex:
        if ([obj isKindOfClass:[Person class]]) {
              int age = [obj age];
        }

   - respondsToSelector: returns true whether an object responds to a given
                       method
   Ex:
        if ([obj respondsToSelector:@selector(setAge:)]) {
              [obj setAge: 20];
        }
Objective-C knowledge
 Objective-C syntax : Struct, Enum, BOOL & nil

   Struct
     typedef struct {
                                       Ex:
          float x;
                                       Point p = {10,10};
          float y;
                                       NSLog(@”x = %f”, p.x);
     } Point;

  Enum

     typedef enum TransactionTypes {
          Inquiry,
          Payment,                     Ex:
          Transfer = 10,               TransactionTypes type = Payment;
          Topup                        NSLog(@”type = %d”, type);
     } TransactionTypes;
Objective-C knowledge
 Objective-C syntax : Struct, Enum, BOOL & nil

   BOOL
     YES or NO instead of true or false
     YES = true
     NO = false


   nil
         - An object pointer that does not point to anything.
         - Sending messages to nil is ok.
              If the method returns a value, it will return zero ( or nil ).
              int i = [obj methodWhichReturnsAnInt]; //i = 0 if obj = nil
              Person *p = [obj getPerson];      //p = nil if obj = nil
              Be careful if the method returns a C struct. Return value is
         undefined.
              CGPoint p = [obj getLocation]; //p = undefined value if obj = nil
Objective-C knowledge
 Object Lifecycle & Memory Managenment




  How to create object?
  It is a two step operation to create an object in Objective-C
        Allocating: allocate memory to store the object.
             + alloc: Class method that knows how much memory is needed
             Initializing: initialize object state.
             - init: Instance method to set initial values, perform other setup
        Ex: Person *person = [[Person alloc] init];

  How to destroy object?
     Dealloc: will free memory. However, never call -dealloc directly
Objective-C knowledge
 Object Lifecycle & Memory Managenment
  How to destroy object?
     • Every object has a retaincount
           ■ Defined on NSObject
           ■ As long as retaincount is > 0, object is alive and valid
     • +alloc and -copy create objects with retaincount == 1
     • -retain increments retaincount
     • -release decrements retaincount
     • When retaincount reaches 0, object is destroyed
     • -dealloc method invoked automatically
           ■ One-way street, once you’re in -dealloc there’s no turning back

  Why must call retain/release to increments/decrements retain count
  instead of free as C??
Objective-C knowledge
 Object Lifecycle & Memory Managenment


  When do you take ownership?
     - You immediately own any object you get by sending a message starting
     with new, alloc or copy.
      - If you get an object from any other source you do not own it, but you can
     take ownership by using retain.

  How do you give up ownership when you are done?
     Using release.
     Importane: do not release to an object you do not own. This is very bad.
Objective-C knowledge
    Object Lifecycle & Memory Managenment
-(void) doSample{
     Person *person = [[Person alloc] init];    //person take ownership
     Person *personA = person;                  //personA do not take ownership

      //right methods
      [person doSomething];
      [personA doSomething];

      [personA release];     //personA do not take ownership, so do not release
                             object
      [personA retain];      //personA take ownership on object, retaincount is 2
      [personA release];     //right, personA give up ownership, retaincount is 1

      [person release];      //right, person give up ownership, retaincount is 0,
                             object will be dealloc.
}
Objective-C knowledge
 Object Lifecycle & Memory Managenment
   Autorelease & Autorelease pool
         Person *person = [Person returnPerson];

  person do not take ownership, so it do not call release anyway.
  So, how to free memory of object is returned from [Person returnPerson]?

   Using “autorelease” to flags an object to be sent release at some point in
   the future
Objective-C knowledge
 Object Lifecycle & Memory Managenment
   Autorelease & Autorelease pool
         Person *person = [Person returnPerson];
   -(Person*) returnPerson{
        .Person *person = [[Person alloc] init];
        return person;
        //wrong, object person will nerver be destroyed.
   }
   -(Person*) returnPerson{
        .Person *person = [[Person alloc] init];
        [person release];
        return person;
        //wrong, object person will be destroyed, so app will crash if any
   message is sent to person.
   }

    -(Person*) returnPerson{
         .Person *person = [[Person alloc] init];
         [person autorelease];
         return person;
         //right, object person will have more time to alive.
    }
Objective-C knowledge
 Object Lifecycle & Memory Managenment
   Autorelease & Autorelease pool


    How does -autorelease work?
    • Object is added to current autorelease pool
    • Autorelease pools track objects scheduled to be released
         ■ When the pool itself is released, it sends -release to all its objects
    • UIKit automatically wraps a pool around every event dispatch

    • If you need to hold onto those objects you need to retain them
Objective-C knowledge
 Object Lifecycle & Memory Managenment
   Autorelease & Autorelease pool
Objective-C knowledge
 Object Lifecycle & Memory Managenment
   Property with Memory management
    - Understand who owns an object returned from a getter or passed to a setter.
    - Getter methods usually return instance variables directly (if return object, it’s
    autoreleased object).
    - If you use @synthesize to implement setter? Is retain automatically sent?
    …Maybe.
           There are three options for setters made by @synthesize
           @property (retain) Person *person;
            - (Person*)setPerson:(Person*)aPerson{
                      [person release];
                      person = [aPerson retain];
                 }
           @property (copy) Person *person;
           - (Person*)setPerson:(Person*)aPerson{
                      [person release];
                      person = [aPerson copy];
                 }
           @property (assign) Person *person;
           - (Person*)setPerson:(Person*)aPerson{
                      person = [aPerson retain];
                 }
Objective-C knowledge
 Object Lifecycle & Memory Managenment

Summary, you have 2 ways to get object:

- Using alloc/init ( or new, copy ): will return a object with ownership (retained
object)
     NSString *string =[ [NSString alloc] initWithString:@”Hello”];
     NSString *stringCopy = [string copy];

- Take object from other soure: will return an object without
ownership(autoreleased object), and use retain if you want to hold on that
object.
     NSString *string = [NSString stringWithFormat:@”%@”, @”Hello”];
     NSString *string2 = [string stringByAppendingString:@”World”];
     NSString *string2 = [[string stringByAppendingString:@”World”] retain];
Objective-C knowledge
 Foundation Frameworks
   NSObject
      - Base class for pretty much every object in the iOS SDK
      - Implements memory management primitives (and more…)

   NSString
      - International (any language) strings using Unicode.
      - An NSString instance can not be modified! They are immutable.
      - Usual usage pattern is to send a message to an NSString and it will
      return you a new one.
       - Important methods:
           - stringByAppendingString:
           - isEqualToString:
           - componentsSeparatedByString:
           - substringFromIndex:
           - dataUsingEncoding:
           – stringByReplacingOccurrencesOfString:withString:
           – rangeOfString:
           + stringWithString:
           + stringWithFormat:
Objective-C knowledge
 Foundation Frameworks
   NSMutableString
      - Mutable version of NSString.
      - Can do some of the things NSString can do without creating a new one
      (i.e. in-place changes).
       - Important methods:
            NSMutableString *mutString = [[NSMutableString alloc]
      initWithString:@“Hello”];
            [mutString appendString: @”YP”];

   NSDate
      - Used to find out the time right now or to store past or future times/dates.
      - See also NSCalendar, NSDateFormatter, NSDateComponents.
Objective-C knowledge
 Foundation Frameworks

  NSNumber
     - Object wrapper around primitive types like int, float, double, BOOL, etc.
          NSNumber *num = [NSNumber numberWithFloat:77.7];
          float f = [num floatValue];
     - Useful when you want to put these primitive types in a collection (e.g.
     NSArray or NSDictionary).

   NSValue
      - Generic object wrapper for other non-object data types.
       - Important methods:
      CGPoint point = CGPointMake(25.0, 15.0);
      NSValue *val = [NSValue valueWithCGPoint:point];

   NSData
      - “Bag of bits.”
      - Used to save/restore/transmit data throughout the iOS SDK.
Objective-C knowledge
 Foundation Frameworks

  NSArray
       - Ordered collection of objects.
       - Immutable. That’s right, you cannot add or remove objects to it once it’s
  created.
       - Important methods:
           + (id)arrayWithObjects:(id)firstObject, ...;
           - (int)count;
           - (id)objectAtIndex:(int)index;

   NSMutableArray
      - Mutable version of NSArray.
      - Important methods:
          - (void)addObject:(id)anObject;
          - (void)insertObject:(id)anObject atIndex:(int)index;
          - (void)removeObjectAtIndex:(int)index;
Objective-C knowledge
 Foundation Frameworks

   NSDictionary
      - Hash table. Look up objects using a key to get a value.
      - Immutable. That’s right, you cannot add or remove objects to it
      once it’s created.
      - Keys are usually NSString objects.
      - Important methods:
           - (int)count;
           - (id)objectForKey:(id)key;
           - (NSArray *)allKeys;
           - (NSArray *)allValues;

   NSMutableDictionary
      - Mutable version of NSDictionary.
      - Important methods:
          - (void)setObject:(id)anObject forKey:(id)key;
          - (void)removeObjectForKey:(id)key;
          - (void)addEntriesFromDictionary:(NSDictionary*)
      otherDictionary;
Q&A
Thank you

More Related Content

PPT
Objective-C for iOS Application Development
PPTX
Objective c slide I
PDF
Introduction to Objective - C
PDF
iOS 101 - Xcode, Objective-C, iOS APIs
PDF
Introduction to objective c
PPTX
Introduction to Objective - C
PPT
Objective c
PPT
Objective c intro (1)
Objective-C for iOS Application Development
Objective c slide I
Introduction to Objective - C
iOS 101 - Xcode, Objective-C, iOS APIs
Introduction to objective c
Introduction to Objective - C
Objective c
Objective c intro (1)

What's hot (20)

PPT
Classes and data abstraction
KEY
Objective-Cひとめぐり
PPTX
Introduce oop in python
PPTX
Python - OOP Programming
PDF
201005 accelerometer and core Location
PDF
Constructors destructors
PDF
Constructors and destructors
KEY
Exciting JavaScript - Part I
PPTX
iOS Session-2
PDF
C# Summer course - Lecture 3
PPTX
Ios development
PPT
Oops concept in c#
PDF
C# Summer course - Lecture 4
PPTX
Python Programming Essentials - M20 - Classes and Objects
PDF
Object Oriented Programming using C++ Part I
PDF
Classes and object
PDF
Object Oriented Programming With C++
PDF
Inheritance
PPTX
Constructors and destructors
Classes and data abstraction
Objective-Cひとめぐり
Introduce oop in python
Python - OOP Programming
201005 accelerometer and core Location
Constructors destructors
Constructors and destructors
Exciting JavaScript - Part I
iOS Session-2
C# Summer course - Lecture 3
Ios development
Oops concept in c#
C# Summer course - Lecture 4
Python Programming Essentials - M20 - Classes and Objects
Object Oriented Programming using C++ Part I
Classes and object
Object Oriented Programming With C++
Inheritance
Constructors and destructors
Ad

Viewers also liked (8)

PDF
iOS Basic Development Day 2 - Objective-C 2.0 & iOS Framework
PDF
Introduction to xcode
PDF
Advanced iOS
PPTX
Apple iOS Introduction
PPTX
Ios operating system
PPTX
Presentation on iOS
PPTX
Apple iOS
PDF
Никита Корчагин - Programming Apple iOS with Objective-C
iOS Basic Development Day 2 - Objective-C 2.0 & iOS Framework
Introduction to xcode
Advanced iOS
Apple iOS Introduction
Ios operating system
Presentation on iOS
Apple iOS
Никита Корчагин - Programming Apple iOS with Objective-C
Ad

Similar to iOS Basic (20)

PDF
Iphone course 1
PDF
iOS Einstieg und Ausblick
KEY
iPhone Development Intro
PPTX
OOPS features using Objective C
PDF
Objective-C A Beginner's Dive (with notes)
PPTX
iOS Einstieg und Ausblick - Mobile DevCon 2011 - OPITZ CONSULTING -Stefan Sch...
PDF
Objective-C talk
PPTX
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
PPTX
iPhone Workshop Mobile Monday Ahmedabad
PPTX
iOS,From Development to Distribution
PDF
Irving iOS Jumpstart Meetup - Objective-C Session 2
ODP
A quick and dirty intro to objective c
PPT
Ios development
PPT
iPhone development from a Java perspective (Jazoon '09)
ODP
How to develop an iOS application
PDF
Introduction to iOS and Objective-C
PPT
iOS Application Development
PPTX
Swift vs Objective-C
PPTX
From C++ to Objective-C
PPTX
Ios fundamentals with ObjectiveC
Iphone course 1
iOS Einstieg und Ausblick
iPhone Development Intro
OOPS features using Objective C
Objective-C A Beginner's Dive (with notes)
iOS Einstieg und Ausblick - Mobile DevCon 2011 - OPITZ CONSULTING -Stefan Sch...
Objective-C talk
ioS Einstieg und Ausblick - Mobile DevCon Hamburg 2011 - OPITZ CONSULTING - S...
iPhone Workshop Mobile Monday Ahmedabad
iOS,From Development to Distribution
Irving iOS Jumpstart Meetup - Objective-C Session 2
A quick and dirty intro to objective c
Ios development
iPhone development from a Java perspective (Jazoon '09)
How to develop an iOS application
Introduction to iOS and Objective-C
iOS Application Development
Swift vs Objective-C
From C++ to Objective-C
Ios fundamentals with ObjectiveC

More from Duy Do Phan (13)

PPTX
Twitter Bootstrap Presentation
PPT
BlackBerry Basic
PPT
PCI DSS
PPT
PPTX
Location based AR & how it works
PPT
Linux Introduction
PPT
Iso8583
PPT
Cryptography Fundamentals
PPT
PPT
Android Programming Basic
PPT
SMS-SMPP-Concepts
PPT
One minute manager
PPTX
Work life balance
Twitter Bootstrap Presentation
BlackBerry Basic
PCI DSS
Location based AR & how it works
Linux Introduction
Iso8583
Cryptography Fundamentals
Android Programming Basic
SMS-SMPP-Concepts
One minute manager
Work life balance

iOS Basic

  • 2. AGENDA • Introduction about iOS • Objective-C knowlegde Introduction OOP Objective-C syntax Object Lifecycle & Memory Managenment Foundation Frameworks • MVC Pattern • Build up an View-based Application Xcode Application Lifecycle View and Custom View Interface Builder View Controller Lifecycle Navigation Controllers Common UIControl (UIButton, UITable,...) Multi resolution and Rotation Deployment 2
  • 4. Introduction about iOS • What is iOS? iOS (known as iPhone OS prior to June 2010) is Apple’s mobile operating system. Originally developed for the iPhone, it has since been extended to support other Apple devices such as the iPod Touch, iPad and Apple TV. • iOS & Devices - History & Evolution iOS version: Common: iOS 4.0 & later Newest: iOS 6.0 Our support: iOS 3.0 & later Device: iPhone: 1st Generation, 3G, 3GS 4, 4S - Retina Display iPod Touch: 1st, 2nd, 3rd, 4th (Retina display) Generation iPad: 1, 2, New iPad (Retina display) Apple TV • Types of iOS Applications Native applications Web applications 4
  • 7. Introduction about iOS iOS Technology Overview: iOS Layers UIKit, MapKit, Printing, Push Notification, Objective C GameKit,…. Core Graphic, Core Audio, Core Video, Core Animation,… Core Foundation, Address book, Core Locaion, … C Sercurity, External Accessory , System ( threading, networking,...) ...
  • 8. Introduction about iOS iOS Technology Overview: iOS Layers UIKit framework
  • 9. Introduction about iOS iOS Technology Overview: Platform Component
  • 10. Introduction about iOS iOS Technology Overview: Platform Component
  • 11. Introduction about iOS iOS Technology Overview: Platform Component
  • 12. Introduction about iOS iOS Technology Overview: Platform Component
  • 13. Introduction about iOS iOS Technology Overview: Platform Component
  • 15. Objective-C knowledge Introduction • Mix C with Smalltalk. • Message passing (defining method). • Single inheritance, classes inherit from one and only one superclass. • Dynamic binding. • It’s OOP language.
  • 16. Objective-C knowledge Introduction • Primitive data types : int, float, double,…. • Conditional structure: • Loops:
  • 17. Objective-C knowledge OOP • Class: defines 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 (or “ivar”): a specific piece of data belonging to an object. • Encapsulation • Polymorphism • Inheritance Use self to access methods, properties,... Use super to access methods, properties,... of parent class.
  • 19. Objective-C knowledge Objective-C syntax : Defining a Class Class interface declared in header file (.h) Class Implementation (.m)
  • 20. Objective-C knowledge Objective-C syntax : Message syntax (BOOL) sendMailTo: (NSString*) address withBody: (NSString*) body; BOOL : Return type sendMailTo :First part of method name. withBody :Second part of method name. sendMailTo: withBody: :full method name or is called selector. address :first argument. body :second argument. sendMailTo: (NSString*) address :First message. withBody: (NSString*) body :second message. BOOL isSuccess = [self sendMailTo: @”yp@yp.com” withBody: @”YP”];
  • 21. Objective-C knowledge Objective-C syntax : Instance method • Starts with a dash - (BOOL) sendMailTo: (NSString*) address withBody: (NSString*) body; •“Normal” methods you are used to • Can access instance variables inside as if they were locals • Can send messages to self and super inside • Example calling syntax: BOOL isSuccess = [account sendMailTo: @”yp@yp.com” withBody: @”YP”];
  • 22. Objective-C knowledge Objective-C syntax : Class method • Starts with a plus. Used for allocation, singletons, utilities + (id) alloc; + (NSString*) stringWithString: (NSString*) string; • Can not access instance variables inside • Example calling syntax (a little different from instance methods) NSString *string = [NSString stringWithString:@"YP"];
  • 23. Objective-C knowledge Objective-C syntax : Instance Variables - By default, instance variables are @protected (only the class and subclasses can access). -Can be marked @private (only the class can access) or @public (anyone can access). @interface Person: NSObject { int age; @private @private: heart int heart; @protected: age, hand, leg @protected @public: face, body int hand; int leg; @public int face; int body; }
  • 24. Objective-C knowledge Objective-C syntax : Properties @interface MyObject : NSObject @interface MyObject : NSObject { { @private @private int age; int age; } } - (int) age; @property int age; - (void)setAge:(int)anInt; @end @end - Mark all of your instance variables @private. - Generate set/get method declarations. - @property (readonly) int age; // does not declare a setAge method - Use “dot notation” to access instance variables. - By default, get/set is thread-safe method. + @property (nonatomic) int age; no thread-safe method
  • 25. Objective-C knowledge Objective-C syntax : Properties Other typing ways to define a property @interface MyObject : NSObject @interface MyObject : NSObject { { int iAge; } } @property int age; @property int age; @end @end But whatever you declare, you must then implement
  • 26. Objective-C knowledge Objective-C syntax : Properties .h .m @interface MyObject : NSObject @implementation MyObject { - (int)age { int age; return age; } } @property int age; @end - (void)setAge:(int)anInt { age= anInt; } @end
  • 27. Objective-C knowledge Objective-C syntax : Properties .h .m @interface MyObject : NSObject @implementation MyObject { - (int) age{ int iAge; return iAge; } } @property int age; @end - (void)setAge:(int)anInt { iAge = anInt; } @end
  • 28. Objective-C knowledge Objective-C syntax : Properties .h .m @interface MyObject : NSObject @implementation MyObject { - (int) age { ??? } } @property int age; @end - (void)setAge:(int)anInt { ??? } @end
  • 29. Objective-C knowledge Objective-C syntax : Properties Let the compiler help you with implementation using @synthesize! .h .m @interface MyObject : NSObject @implementation MyObject @property int age; @synthesize age; @end @end @interface MyObject : NSObject{ @implementation MyObject int age; @synthesize age; } @end @property int age; @end @interface MyObject : NSObject{ @implementation MyObject int iAge; @synthesize age= iAge; } @end @property int age; @end
  • 30. Objective-C knowledge Objective-C syntax : Properties If you use @synthesize, you can still implement one or the other @implementation MyObject @synthesize age; - (void)setAge:(int)anInt { if (anInt > 0) age= anInt; } @end
  • 31. Objective-C knowledge Objective-C syntax : Properties How to use? int x = self.age; int x = [self age]; self.age = x; [self setAge: x]; And, there’s more to think about when a @property is an object. We will discuss later.
  • 32. Objective-C knowledge Objective-C syntax : Dynamic Binding - Decision about code to run on message send happens at runtime Not at compile time. If neither the class of the receiving object nor its superclasses implements that method: crash! - It is legal (and sometimes even good code) to “cast” a pointer But we usually do it only after we’ve used “introspection” to find out more about the object. id obj = [[MyObject alloc] init]; NSString *s = (NSString *)obj; // dangerous ... best know what you are doing [s setAge: 1]; //warning…crash when runtime id obj = [[Person alloc] init]; NSString *s = (NSString *)obj; // dangerous ... best know what you are doing [s setAge: 1]; //warning…work well.
  • 33. Objective-C knowledge Objective-C syntax : Introspection All objects that inherit from NSObject know these methods - isKindOfClass: returns true whether an object is that kind of class (inheritance included) - isMemberOfClass: returns true whether an object is that kind of class (no inheritance) Ex: if ([obj isKindOfClass:[Person class]]) { int age = [obj age]; } - respondsToSelector: returns true whether an object responds to a given method Ex: if ([obj respondsToSelector:@selector(setAge:)]) { [obj setAge: 20]; }
  • 34. Objective-C knowledge Objective-C syntax : Struct, Enum, BOOL & nil Struct typedef struct { Ex: float x; Point p = {10,10}; float y; NSLog(@”x = %f”, p.x); } Point; Enum typedef enum TransactionTypes { Inquiry, Payment, Ex: Transfer = 10, TransactionTypes type = Payment; Topup NSLog(@”type = %d”, type); } TransactionTypes;
  • 35. Objective-C knowledge Objective-C syntax : Struct, Enum, BOOL & nil BOOL YES or NO instead of true or false YES = true NO = false nil - An object pointer that does not point to anything. - Sending messages to nil is ok. If the method returns a value, it will return zero ( or nil ). int i = [obj methodWhichReturnsAnInt]; //i = 0 if obj = nil Person *p = [obj getPerson]; //p = nil if obj = nil Be careful if the method returns a C struct. Return value is undefined. CGPoint p = [obj getLocation]; //p = undefined value if obj = nil
  • 36. Objective-C knowledge Object Lifecycle & Memory Managenment How to create object? It is a two step operation to create an object in Objective-C Allocating: allocate memory to store the object. + alloc: Class method that knows how much memory is needed Initializing: initialize object state. - init: Instance method to set initial values, perform other setup Ex: Person *person = [[Person alloc] init]; How to destroy object? Dealloc: will free memory. However, never call -dealloc directly
  • 37. Objective-C knowledge Object Lifecycle & Memory Managenment How to destroy object? • Every object has a retaincount ■ Defined on NSObject ■ As long as retaincount is > 0, object is alive and valid • +alloc and -copy create objects with retaincount == 1 • -retain increments retaincount • -release decrements retaincount • When retaincount reaches 0, object is destroyed • -dealloc method invoked automatically ■ One-way street, once you’re in -dealloc there’s no turning back Why must call retain/release to increments/decrements retain count instead of free as C??
  • 38. Objective-C knowledge Object Lifecycle & Memory Managenment When do you take ownership? - You immediately own any object you get by sending a message starting with new, alloc or copy. - If you get an object from any other source you do not own it, but you can take ownership by using retain. How do you give up ownership when you are done? Using release. Importane: do not release to an object you do not own. This is very bad.
  • 39. Objective-C knowledge Object Lifecycle & Memory Managenment -(void) doSample{ Person *person = [[Person alloc] init]; //person take ownership Person *personA = person; //personA do not take ownership //right methods [person doSomething]; [personA doSomething]; [personA release]; //personA do not take ownership, so do not release object [personA retain]; //personA take ownership on object, retaincount is 2 [personA release]; //right, personA give up ownership, retaincount is 1 [person release]; //right, person give up ownership, retaincount is 0, object will be dealloc. }
  • 40. Objective-C knowledge Object Lifecycle & Memory Managenment Autorelease & Autorelease pool Person *person = [Person returnPerson]; person do not take ownership, so it do not call release anyway. So, how to free memory of object is returned from [Person returnPerson]? Using “autorelease” to flags an object to be sent release at some point in the future
  • 41. Objective-C knowledge Object Lifecycle & Memory Managenment Autorelease & Autorelease pool Person *person = [Person returnPerson]; -(Person*) returnPerson{ .Person *person = [[Person alloc] init]; return person; //wrong, object person will nerver be destroyed. } -(Person*) returnPerson{ .Person *person = [[Person alloc] init]; [person release]; return person; //wrong, object person will be destroyed, so app will crash if any message is sent to person. } -(Person*) returnPerson{ .Person *person = [[Person alloc] init]; [person autorelease]; return person; //right, object person will have more time to alive. }
  • 42. Objective-C knowledge Object Lifecycle & Memory Managenment Autorelease & Autorelease pool How does -autorelease work? • Object is added to current autorelease pool • Autorelease pools track objects scheduled to be released ■ When the pool itself is released, it sends -release to all its objects • UIKit automatically wraps a pool around every event dispatch • If you need to hold onto those objects you need to retain them
  • 43. Objective-C knowledge Object Lifecycle & Memory Managenment Autorelease & Autorelease pool
  • 44. Objective-C knowledge Object Lifecycle & Memory Managenment Property with Memory management - Understand who owns an object returned from a getter or passed to a setter. - Getter methods usually return instance variables directly (if return object, it’s autoreleased object). - If you use @synthesize to implement setter? Is retain automatically sent? …Maybe. There are three options for setters made by @synthesize @property (retain) Person *person; - (Person*)setPerson:(Person*)aPerson{ [person release]; person = [aPerson retain]; } @property (copy) Person *person; - (Person*)setPerson:(Person*)aPerson{ [person release]; person = [aPerson copy]; } @property (assign) Person *person; - (Person*)setPerson:(Person*)aPerson{ person = [aPerson retain]; }
  • 45. Objective-C knowledge Object Lifecycle & Memory Managenment Summary, you have 2 ways to get object: - Using alloc/init ( or new, copy ): will return a object with ownership (retained object) NSString *string =[ [NSString alloc] initWithString:@”Hello”]; NSString *stringCopy = [string copy]; - Take object from other soure: will return an object without ownership(autoreleased object), and use retain if you want to hold on that object. NSString *string = [NSString stringWithFormat:@”%@”, @”Hello”]; NSString *string2 = [string stringByAppendingString:@”World”]; NSString *string2 = [[string stringByAppendingString:@”World”] retain];
  • 46. Objective-C knowledge Foundation Frameworks NSObject - Base class for pretty much every object in the iOS SDK - Implements memory management primitives (and more…) NSString - International (any language) strings using Unicode. - An NSString instance can not be modified! They are immutable. - Usual usage pattern is to send a message to an NSString and it will return you a new one. - Important methods: - stringByAppendingString: - isEqualToString: - componentsSeparatedByString: - substringFromIndex: - dataUsingEncoding: – stringByReplacingOccurrencesOfString:withString: – rangeOfString: + stringWithString: + stringWithFormat:
  • 47. Objective-C knowledge Foundation Frameworks NSMutableString - Mutable version of NSString. - Can do some of the things NSString can do without creating a new one (i.e. in-place changes). - Important methods: NSMutableString *mutString = [[NSMutableString alloc] initWithString:@“Hello”]; [mutString appendString: @”YP”]; NSDate - Used to find out the time right now or to store past or future times/dates. - See also NSCalendar, NSDateFormatter, NSDateComponents.
  • 48. Objective-C knowledge Foundation Frameworks NSNumber - Object wrapper around primitive types like int, float, double, BOOL, etc. NSNumber *num = [NSNumber numberWithFloat:77.7]; float f = [num floatValue]; - Useful when you want to put these primitive types in a collection (e.g. NSArray or NSDictionary). NSValue - Generic object wrapper for other non-object data types. - Important methods: CGPoint point = CGPointMake(25.0, 15.0); NSValue *val = [NSValue valueWithCGPoint:point]; NSData - “Bag of bits.” - Used to save/restore/transmit data throughout the iOS SDK.
  • 49. Objective-C knowledge Foundation Frameworks NSArray - Ordered collection of objects. - Immutable. That’s right, you cannot add or remove objects to it once it’s created. - Important methods: + (id)arrayWithObjects:(id)firstObject, ...; - (int)count; - (id)objectAtIndex:(int)index; NSMutableArray - Mutable version of NSArray. - Important methods: - (void)addObject:(id)anObject; - (void)insertObject:(id)anObject atIndex:(int)index; - (void)removeObjectAtIndex:(int)index;
  • 50. Objective-C knowledge Foundation Frameworks NSDictionary - Hash table. Look up objects using a key to get a value. - Immutable. That’s right, you cannot add or remove objects to it once it’s created. - Keys are usually NSString objects. - Important methods: - (int)count; - (id)objectForKey:(id)key; - (NSArray *)allKeys; - (NSArray *)allValues; NSMutableDictionary - Mutable version of NSDictionary. - Important methods: - (void)setObject:(id)anObject forKey:(id)key; - (void)removeObjectForKey:(id)key; - (void)addEntriesFromDictionary:(NSDictionary*) otherDictionary;
  • 51. Q&A

Editor's Notes

  • #8: Cocoa Touch LayerThe Cocoa Touch layer contains the key frameworks for building iOS applications. This layer defines the basic application infrastructure and support for key technologies such as multitasking, touch-based input, push notifications, and many high-level system services.Media LayerThe Media layer contains the graphics, audio, and video technologies geared toward creating the best multimedia experience available on a mobile device.Core Services Layer The Core Services layer contains the fundamental system services that all applications use. Even if you do not use these services directly, many parts of the system are built on top of them.Core OS Layer The Core OS layer contains the low-level features that most other technologies are built upon. Even if you do not use these technologies directly in your applications, they are most likely being used by other frameworks. And in situations where you need to explicitly deal with security or communicating with an external hardware accessory, you do so using the frameworks in this layer. For more infomations about iOS Layers: http://developer.apple.com/library/ios/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/iPhoneOSTechnologies/iPhoneOSTechnologies.html#//apple_ref/doc/uid/TP40007898-CH3-SW1
  • #9: Cocoa Touch LayerThe Cocoa Touch layer contains the key frameworks for building iOS applications. This layer defines the basic application infrastructure and support for key technologies such as multitasking, touch-based input, push notifications, and many high-level system services.Media LayerThe Media layer contains the graphics, audio, and video technologies geared toward creating the best multimedia experience available on a mobile device.Core Services Layer The Core Services layer contains the fundamental system services that all applications use. Even if you do not use these services directly, many parts of the system are built on top of them.Core OS Layer The Core OS layer contains the low-level features that most other technologies are built upon. Even if you do not use these technologies directly in your applications, they are most likely being used by other frameworks. And in situations where you need to explicitly deal with security or communicating with an external hardware accessory, you do so using the frameworks in this layer. For more infomations about iOS Layers: http://developer.apple.com/library/ios/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/iPhoneOSTechnologies/iPhoneOSTechnologies.html#//apple_ref/doc/uid/TP40007898-CH3-SW1