SlideShare a Scribd company logo
Objective-C
 Ing. Paolo Quadrani
   paolo.quadrani@gmail.com
     www.mitapp.com
Introduction
      •   Runtime - Obj-C performs many tasks at runtime (object
          allocation, method invocation)
          → require also a runtime environment ←
      •   Objects - An object associate data with operations that can
          use or affect the data.
      •   id - General data type for any kind of object
      •   Object Messages - To get an object to do something, you
          send it a message telling it to apply a method. Messages are
          enclosed in brackets (e.g. [receiver message]; ). Methods in
          message are called selectors.
      •   Classes - In Obj-C you define objects by defining their
          class. The class definition is a prototype for a kind of object.
www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Memory management

      • Reference counting (retain, release)
       • Manually managed or through the auto-
            release pool
      • Garbage collector (not used in iPhone
         programming, but in Cocoa).



www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Class Interface
             #import "ItsSuperclass.h"

             @class anotherClassForwarding;

             @interface ClassName : ItsSuperclass
             {
                 // instance variable declarations
                 float width;
                    BOOL filled;
                    NSString *name;
             }
             // method declarations
             - (void)setWidth:(float)width;
             + (id)initWithName:(NSString *)aName;

             @end

www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Class Implementation
                 @implementation ClassName : ItsSuperclass
                 {
                     //instance variable declarations
                 }

                 //method definitions
                 - (void)setWidth:(float)width {
                    ...
                 }

                 @end




www.MitAPP.com              http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Class Allocation
                 ...

                 MyClass *obj = [[MyClass alloc] init];
                 obj->myVar = nil;

                 ...




www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
An Example
                                                        The difference between self and super becomes clear in a hierarchy of three



        Messages to self and super
                                                        that we create an object belonging to a class called Low. Low’s superclass is M
                                                        All three classes define a method called negotiate, which they use for a var
                                                        Mid defines an ambitious method called makeLastingPeace, which also has n
                                                        This is illustrated in Figure 2-2:

                                                        Figure 2-2      High, Mid, Low




                 - reposition                                         superclass

                 {                                      High         – negotiate

                     ...
                     [self negotiate];
                     ...
                                                                      superclass
                 }
                                                        Mid         – negotiate
                                                                 – makeLastingPeace



             - reposition
             {                                                        superclass
                 ...
                                                        Low          – negotiate
                 [super negotiate];
                 ...
             }
                                                        We now send a message to our Low object to perform the makeLastingPea
                                                        makeLastingPeace, in turn, sends a negotiate message to the same Low
                                                        object self,

www.MitAPP.com             http://paoloquadrani.blogspot.com/
                                                      - makeLastingPeace                   http://twitter.com/MitAPP
                                                        {
Class Initialization
      •   By convention initializer method begins with
          init e.g. initWithColor: ...
      •   The return type should be id.
      •   You should assign self to the value returned by the
          initializer.
      •   Setting value of member variables, use direct
          assignment, not accessors.
      •   If initializer fails, return nil, otherwise return self.

www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Initializer Example

  - (id)init {
      // Assign self to value returned by super's designated initializer
      // Designated initializer for NSObject is init
      if (self = [super init]) {
          creationDate = [[NSDate alloc] init];
      }
      return self;
  }




www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Combining Allocation
           and Initialization
      • Some classes combine allocation and
         initialization returning a new, initialized
         instance of the class. Convenience
         constructors
      • Examples:+ (id)stringWithFormat:(NSString *)format

                 + (id)arrayWithObject:(id)anObject;




www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Protocols
      • Protocols declare methods that can be
         implemented in any class.
         Useful in:
         • Declare methods that others are expected
            to implement
         • Declare the interface to an object
         • Capture similarity among classes that are
            not hierarchically related
www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Declaring Protocol
       @protocol ProtocolName
          // method declarations
       @optional
          // optional method declarations
       @end



       @protocol MyXMLSupport
       - initFromXMLRepresentation:(NSXMLElement *)XMLElement;
       - (NSXMLElement *)XMLRepresentation;
       @end




www.MitAPP.com              http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Adopting a Protocol
  @interface ClassName : ItsSuperclass < protocol list >



  Ex:
  @interface MyClass : NSObject <UITextFieldDelegate, UIAlertViewDelegate> {
      ...
  }




www.MitAPP.com            http://paoloquadrani.blogspot.com/    http://twitter.com/MitAPP
Declared Properties

      • Declared properties provides a way to
         declare and implement an object’s accessor
         methods
      • The compiler can synthesize accessor
         methods for you



www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Property declaration
         and implementation
                 @property(attributes) type name;



   @interface MyClass : NSObject
   {
        float value;
   }
   @property float value;                   - (float)value;
                                            - (void)setValue:(float)newValue;
   @end




www.MitAPP.com          http://paoloquadrani.blogspot.com/      http://twitter.com/MitAPP
Property Attributes
                      @property(attributes) type name;
   •   Writability
       •   readwrite (the default)
       •   readonly
   •   Setter Semantics
       •   assign (the default) - Used for scalar types such as NSInteger
       •   retain - Used for objects on assignment. The previous value is sent a
           release.
       •   copy - A copy of the object is used for the assignment. The previous
           value is sent a release.
   •   Atomicity
       •   nonatomic (by default) - The synthesized method provide robust access
           in a multi-threading environment.
www.MitAPP.com               http://paoloquadrani.blogspot.com/     http://twitter.com/MitAPP
Example of Property
           Declaration
   @property (nonatomic, retain) IBOutlet NSButton *myButton;

   @property (readonly) NSString *name;

   @property (assign) UITextFieldDelegate *delegate;




www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Property
                 Implementation
      •   Provide one of these Implementation
          Directives inside the @implementation block:
          •   @synthesize
          •   @dynamic
          •   Direct implement setter and getter
              methods


www.MitAPP.com         http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example using @synthesize

   @interface MyClass : NSObject
   {                                                       .h
        NSString *value;
   }
   @property(copy, readwrite) NSString *value;
   @end



   @implementation MyClass                                .m
   @synthesize value;
   @end


www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example using direct implementation
             @interface MyClass : NSObject
             {                                                .h
                  NSString *value;
             }
             @property(copy, readwrite) NSString *value;
             @end



             @implementation MyClass

             - (NSString *)value {                            .m
                 return value;
             }

             - (void)setValue:(NSString *)newValue {
                  if (newValue != value) {
                      value = [newValue copy];
                  }
             }
             @end

www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
DEMO


   • DEMO        (10-15’):

        Looking real code




www.MitAPP.com               http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Selectors

      • In Objective-C selector has two meanings:
       • It refers to a name of a method
       • It refers to a unique identifier that
            replace the name when the code is
            compiled



www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
SEL and @selector

      • Selectors are assigned to special type SEL
      • Valid selectors are never 0
      • @selector() directive lets you refer to
         compiled selectors



www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Examples of selectors

   SEL setWidthHeight;
   setWidthHeight = @selector(setWidth:height:);



   setWidthHeight = NSSelectorFromString(aBuffer);



   NSString *method;
   method = NSStringFromSelector(setWidthHeight);




www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Using a selector

      • NSObject protocol defines three methods
         that use selectors:
         • performSelector:
         • performSelector:withObject:
         • performSelector:withObject:withObject:

www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example
   [friend performSelector:@selector(gossipAbout:)
       withObject:aNeighbor];



     is equivalent to:


   [friend gossipAbout:aNeighbor];




www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Varying message at
                runtime
      • performSelector: and the other two allows
         you to varying messages at runtime. Using
         variables you can:


                 id   helper = getTheReceiver();
                 SEL request = getTheSelector();
                 [helper performSelector:request];



www.MitAPP.com          http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Avoiding Messaging
                Errors
      • Selectors send a message to an object at
         runtime
      • An object that doesn’t implement a method
         generate an error if someone try to send it
         a request to execute a non existent
         method
      • respondsToSelector: is used to check the
         existence of a method

www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example

if ( [anObject respondsToSelector:@selector(setOrigin::)] )
     [anObject setOrigin:0.0 :0.0];
else
     fprintf(stderr, "%s can’t be placedn",
         [NSStringFromClass([anObject class]) UTF8String]);




www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Using C++ with
                  Objective-C

      • C++ can be used inside Objective-C code
      • This hybrid is called Objective-C++
      • Inheritance of Objective-C classes from C+
         + classes (and vice-versa) are not permitted



www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example of mix
   #import <Foundation/Foundation.h>
   class Hello {
       private:
           id greeting_text; // holds an NSString
       public:
           Hello() {
               greeting_text = @"Hello, world!";
           }
           Hello(const char* initial_greeting_text) {
               greeting_text = [[NSString alloc]
   initWithUTF8String:initial_greeting_text];
           }
           void say_hello() {
                printf("%sn", [greeting_text UTF8String]);
           }
   };

www.MitAPP.com         http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example (continue)
             @interface Greeting : NSObject {
                  @private
                      Hello *hello;
             }
             - (id)init;
             - (void)dealloc;
             - (void)sayGreeting;
             - (void)sayGreeting:(Hello*)greeting;
             @end




www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example (continue)
                 @implementation Greeting
                 - (id)init {
                     if (self = [super init]) {
                         hello = new Hello();
                     }
                     return self;
                 }
                 - (void)dealloc {
                     delete hello;
                     [super dealloc];
                 }
                 - (void)sayGreeting {
                     hello->say_hello();
                 }
                 - (void)sayGreeting:(Hello*)greeting {
                     greeting->say_hello();
                 }
                 @end

www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
iPhone
           Main UI arguments


www.MitAPP.com   http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Arguments

      • Dealing with data: User Defaults, SQLite
      • Touch events and Multi-Touch
      • Address book
      • Image Picker
      • Localization
www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Arguments

      • Dealing with data: User Defaults, SQLite
      • Touch events and Multi-Touch
      • Address book
      • Image Picker
      • Localization
www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Dealing with data

      • Property Lists
      • iPhone File System
      • Archiving Objects
      • SQLite
      • Web Services
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Dealing with data

      • Property Lists
      • iPhone File System
      • Archiving Objects
      • SQLite
      • Web Services
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Property Lists
      •   Convenient way to store small amount of data
          •   Array, dictionaries, strings, numbers
          •   XML or binary format
      •   NOT use it if
          •   data is more then few KB, loading is all or nothing
          •   Complex object graphs
          •   Custom object types


www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Reading-Writing
                  Property Lists
  // Writing
  - (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag;
  - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag;


  // Reading
  - (id)initWithContentsOfFile:(NSString *)aPath;
  - (id)initWithContentsOfURL:(NSURL *)aURL;




www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Dealing with data

      • Property Lists
      • iPhone File System
      • Archiving Objects
      • SQLite
      • Web Services
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
iPhone File System

      • Each Application
       • Has its own sand-box
       • Has its own set of directories
       • Can read-write within its own directory

www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
File Paths in Your App
 // Basic Directories
 NSString *homePath = NSHomeDirectory();
 NSString *tmpPath = NSTemporaryDirectory();

 // Documents directories
 NSArray *paths =
 NSSearchPathForDirectoriesInDomain(NSDocumentDirectory,
                          NSUserDomainMask,YES);
 NSString *documentsPath = [paths objectAtIndex:0];


 // <Application Home>/Documents/foo.plist
 NSString *fooPath =
 [documentsPath stringByAppendingPathComponent:@”foo.plist”];

www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Include Writable Files in
       Your Application
      • Build it as part of your app bundle
      • You can’t modify the content of your app
         bundle, so:
         • On first launch, copy the writable to
            your Documents directory



www.MitAPP.com         http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Dealing with data

      • Property Lists
      • iPhone File System
      • Archiving Objects
      • SQLite
      • Web Services
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Archiving Objects
      •   Used for serialization of custom object types

      •   Used by Interface Builder for NIBs

      •   Archivable objects has to conform to the
          <NSCoding> protocol


      •   Implement the two protocol methods:
            - (void)encodeWithCoder:(NSCoder *)coder;
            - (void)initWithCoder:(NSCoder *)coder;

www.MitAPP.com         http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example Coder
      // Encode an object for an archive
      - (void)encodeWithCoder:(NSCoder *)coder {
          [super encodeWithCoder:coder];
          [coder encodeObject: name forKey:@”Name”];
          [coder encodeIntger: numberOfSides forKey:@”Sides”];
      }


      // Decode an object from an archive
      - (id)initWithCoder: (NSCoder *)coder {
          self = [super initWithCoder: coder];
          name = [[coder decodeObjectForKey: @”Name”] retain];
          numberOfSides = [coder decodeIntegerForKey: @”Side”];
      }

www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Dealing with data

      • Property Lists
      • iPhone File System
      • Archiving Objects
      • SQLite
      • Web Services
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
SQLite

      • Complete SQL database in an ordinary file
      • Simple, compact, fast, reliable
      • No server is needed
      • Great for embedded devices
       • Included on the iPhone platform
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
When not to use
                SQLite

      • Multi-gigabyte database
      • High concurrency (multiple writers)
      • Client-server application

www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
SQLite C API basic
      • Open the DB
           int sqlite3_open(const char *filename, sqlite3 **db);

      • Execute a SQL statement
           int sqlite3_exec(sqlite3 *db, const char *sql,
                     int (*callback)(void*, int, char **, char **),
                     void *context, char **error);

           // Your callback
           int callback(void *context, int count,
                       char **values, char **columns);

      • Close the DB
           int sqlite3_close(sqlite3 *db);

www.MitAPP.com              http://paoloquadrani.blogspot.com/        http://twitter.com/MitAPP
SQLITE 3
   • DEMO        (10-15’):

        Real application with Sqlite3




www.MitAPP.com               http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Core Data
      •   Object graph management and persistence
          framework
          •   Make it easy to save and load model objects
          •   Higher-level abstraction then SQLite or
              property lists
      •   Available on the MAC OSX desktop
      •   Available only on iPhone OS 3.x and later

www.MitAPP.com          http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Dealing with data

      • Property Lists
      • iPhone File System
      • Archiving Objects
      • SQLite
      • Web Services
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Integrating with Web Services
      •   Many are exposed via RESTful interface with XML
          or JSON
      •   Options for Parsing XML are:
          •   libxml2 - C library
          •   NSXMLParser - simpler but less powerful
              than the previous one
      •   JavaScript Object Notation
          •   More lightweight then XML
          •   Looks like a property list
          •   open source json-framework wrapper for Obj-C
www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
JSON & XML PARSER
   • DEMO        (10-15’):

        Real application with Json (Flickr API) & XML parser




www.MitAPP.com               http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Arguments

      • Dealing with data: User Defaults, SQLite
      • Touch events and Multi-Touch
      • Address book
      • Image Picker
      • Localization
www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Single Touch Sequence

      •   UITouch represent a single finger

      •   There are three phases in touch:

          •   touchBegan

          •   touchMoved

          •   touchEnded

www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
UIEvent: Collection of UITouch

      • UIEvent is a container for UITouch
      • Can give information on:
       • all touches
       • all touches in a window
       • all touches in a view
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Receiving touches
      • UIResponder is the base class of touches
         ‘listener’

      • Methods called are:
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

    - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;



www.MitAPP.com             http://paoloquadrani.blogspot.com/    http://twitter.com/MitAPP
Multiple Touches

      • Same events are generated then Single
         Touch

      • You must enable it to make it works
         BOOL multipleTouchEnabled;




www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Arguments

      • Dealing with data: User Defaults, SQLite
      • Touch events and Multi-Touch
      • Address book
      • Image Picker
      • Localization
www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Address Book basics

 •   Create a person and set
     some properties

 •   Create a
     ABPersonViewController

 •   Push the view controller
     onto the navigation stack


www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Get people from the
          Address Book

  ABAddressBookRef ab = ABAddressBookCreate();
  CFArrayRef people = ABAddressBookCopyPeopleWithName(ab, name);




www.MitAPP.com         http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Person
      • ABRecordRef
      • A collection of properties
       • First and last name
       • Image
       • Phone numbers, emails, etc...

www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Properties
      •   Properties can have different types

          •   String

          •   Date

          •   Dictionary, Data...

      •   Some properties may have multiple values

          •   Telephone: home, work, mobile...

      •   Person properties in ABPerson.h
www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Retrieve and Set Single
        Value Properties

// Retrieve the first name of a person
CFStringRef first = ABRecordCopyValue(person, kABPersonFirstNameProperty);

 // Update or Set the birthday of a person
 CFDateRef date = CFDateCreate( ... );
 ABRecordSetValue(person, kABPersonBirthdayProperty, date, &error);




www.MitAPP.com              http://paoloquadrani.blogspot.com/    http://twitter.com/MitAPP
Retrieve Multi Value
     Properties (ABMultiValueRef)
 // Getting multiplicity
 CFIndex count = ABMultiValueGetCount(multiValue);

 // and getting the value
 CFTypeRef value = ABMultiValueCopyValueAtIndex(mv, index);

 // and getting the lable
 CFStringRef label = ABMultiValueCopyLabelAtIndex(mv, index);




www.MitAPP.com          http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Update Multi Value
              Properties
 // Get the multi value reference
 ABMultiValueRef urls = ABRecordCopyValue(person, kABPersonURLProperty);

 // Create the multi value mutable copy
 ABMutableMultiValueRef urlCopy = ABMultiValueCreateMutableCopy(urls);

 // Add the new value
 ABMultiValueAddValueAndLabel(urlCopy, “the url”, “url label”, NULL);
 ABRecordSetValue(person, urlCopy, kABPersonURLProperty);

 // Save the Address Book
 ABAddressBookSave(ab, &error);

www.MitAPP.com             http://paoloquadrani.blogspot.com/    http://twitter.com/MitAPP
Person View Controller
      • ABPersonViewController
       • displayedPerson
       • displayedProperties
       • allowsEditing

www.MitAPP.com    http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Arguments

      • Dealing with data: User Defaults, SQLite
      • Touch events and Multi-Touch
      • Address book
      • Image Picker
      • Localization
www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Image Picker Interface

      • UIImagePickerController class
       • Handles all user and device interactions
       • Built on top of UIViewController
      • UIImagePickerControllerDelegate protocol
       • Implemented by your delegate object
www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Displaying the Image
                Picker

      • Check the source available
      • Assign a delegate object
      • Present the controller modality

www.MitAPP.com     http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example Code

if([UIImagePickerController isSourceTypeAvailable:
                  UIImagePickerControllerSourceTypeCamera]) {
    UIImagePickerController *picker =
                        [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;

    [self presentModalViewController:picker animated:YES];
}




www.MitAPP.com             http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
UIImagePickerController
         delegate methods

      • Two methods:
     - (void)imagePickerController:(UIImagePickerController*)picker
            didFinishPickingMediaWithInfo:(NSDictionary *)info;



     - (void)imagePickerControllerDidCancel:
                                (UIImagePickerController*)picker;




www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Define your delegate
               object
   - (void)imagePickerController:(UIImagePickerController*)picker
          didFinishPickingMediaWithInfo:(NSDictionary *)info {

       // Save or use the image picked here.
       UIImage *image = [info
                 objectForKey: UIImagePickerControllerOriginalImage];

       // Dismiss the image picker.
       [self dismissModalViewControllerAnimated:YES];
       [picker release];
   }


www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Define your delegate
                object

      - (void)imagePickerControllerDidCancel:
                                 (UIImagePickerController*)picker {

          // Dismiss the image picker.
          [self dismissModalViewControllerAnimated:YES];
          [picker release];
      }




www.MitAPP.com            http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Manipulating the
                 returned Image

      • If allowsImageEditing property is YES:
       • User allowed to crop the returned image
       • Image metadata returned in “info”
            NSDictionary



www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Arguments

      • Dealing with data: User Defaults, SQLite
      • Touch events and Multi-Touch
      • Address book
      • Image Picker
      • Localization
www.MitAPP.com      http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Localizing an
                  Application
      • Multiple Languages and locales in a single
         built application
      • Keep localized resources separate from
         everything else
         • Strings
         • Images
         • User Interfaces
www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Where do localized
           resources do?
      •   MyApp.app/
          •   MyApp
          •   English.lproj/
              •   Localizable.strings
              •   MyView.nib
          •   Italian,lproj/
              •   Localizable.strings
              •   MyView.nib

www.MitAPP.com                 http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Localized Strings
      • For user-visible strings in application code
      • Map from an non localized key to a
         localized string
      • Stored in .strings files
       • Key-value pairs
       • Use UTF-16 for encoding
www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Example of .strings

      • en.lproj/Greetings.strings
         “Hello” = “Hello”;
         “Welcome to %@” = “Welcome to%@”;
      • it.lproj/Greetings.strings
         “Hello” = “Ciao”;
         “Welcome to %@” = “Benvenuto a %@”;


www.MitAPP.com       http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Accessing localized
                strings
   // By default, uses Localizable.strings
   NSLocalizedString(@”Hello”, @”Greeting for welcome screen”);


   // Specify a table, uses Greetings.strings
   NSLocalizedStringFromTable(@”Hello”, @”Greetings”,
                                @”Greeting for welcome screen”);




www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
genstrings

      • Tool to scan your code and produce
         a .strings file
      • Inserts comments found in code as clues to
         localizer
      • Run the tool over your *.m files

www.MitAPP.com        http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP
Localizing XIBs


      •   Xcode allows you to
          generate localized
          version of your User
          Interface




www.MitAPP.com           http://paoloquadrani.blogspot.com/   http://twitter.com/MitAPP

More Related Content

KEY
Objective-C Crash Course for Web Developers
PPT
Objective-C for iOS Application Development
PDF
iOS 101 - Xcode, Objective-C, iOS APIs
PPT
eXo SEA - JavaScript Introduction Training
PDF
Objective-C for Java Developers
PPTX
iOS Basic
PDF
JavaScript introduction 1 ( Variables And Values )
PPTX
Javascript Basics
Objective-C Crash Course for Web Developers
Objective-C for iOS Application Development
iOS 101 - Xcode, Objective-C, iOS APIs
eXo SEA - JavaScript Introduction Training
Objective-C for Java Developers
iOS Basic
JavaScript introduction 1 ( Variables And Values )
Javascript Basics

What's hot (20)

PPT
JavaScript - An Introduction
PDF
Iphone course 1
PPTX
Introduction to Objective - C
PDF
iPhone Seminar Part 2
PPT
JavaScript Basics
PDF
Uncommon Design Patterns
PDF
Building DSLs with Xtext - Eclipse Modeling Day 2009
PPT
Objective c
PPT
Objective c intro (1)
KEY
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
PDF
Xtext Webinar
PDF
Java ppt Gandhi Ravi (gandhiri@gmail.com)
KEY
Runtime
KEY
Exciting JavaScript - Part I
PDF
Core concepts-javascript
KEY
Xbase - Implementing Domain-Specific Languages for Java
PDF
Introduction to objective c
PDF
Fundamental JavaScript [UTC, March 2014]
PPSX
DIWE - Programming with JavaScript
KEY
Xtext Eclipse Con
JavaScript - An Introduction
Iphone course 1
Introduction to Objective - C
iPhone Seminar Part 2
JavaScript Basics
Uncommon Design Patterns
Building DSLs with Xtext - Eclipse Modeling Day 2009
Objective c
Objective c intro (1)
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Xtext Webinar
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Runtime
Exciting JavaScript - Part I
Core concepts-javascript
Xbase - Implementing Domain-Specific Languages for Java
Introduction to objective c
Fundamental JavaScript [UTC, March 2014]
DIWE - Programming with JavaScript
Xtext Eclipse Con
Ad

Viewers also liked (15)

PPTX
Objective c slide I
PDF
Introduction to Objective - C
PDF
Digital Universitas
PDF
GDB Mobile
PDF
Automatic Reference Counting @ Pragma Night
PDF
Objective-C @ ITIS
PDF
Automatic Reference Counting
PDF
Auto Layout Under Control @ Pragma conference 2013
PDF
Swift Introduction
PDF
Objective-C
PDF
Iphone programming: Objective c
PPTX
Introduction to iOS Apps Development
PDF
A swift introduction to Swift
PPTX
Apple iOS
PDF
Swift Programming Language
Objective c slide I
Introduction to Objective - C
Digital Universitas
GDB Mobile
Automatic Reference Counting @ Pragma Night
Objective-C @ ITIS
Automatic Reference Counting
Auto Layout Under Control @ Pragma conference 2013
Swift Introduction
Objective-C
Iphone programming: Objective c
Introduction to iOS Apps Development
A swift introduction to Swift
Apple iOS
Swift Programming Language
Ad

Similar to Parte II Objective C (20)

PPTX
Inheritance
PPT
Introduction to OOP with PHP
PPT
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
PPS
Learn java
PPTX
Presentation 3rd
PDF
[2015/2016] JavaScript
PDF
Variables in Pharo5
PDF
First class Variables in Pharo
PPT
Md02 - Getting Started part-2
PPTX
Advanced oops concept using asp
PDF
The Naked Bundle - Symfony Live London 2014
PDF
The Naked Bundle - Symfony Barcelona
PDF
What Makes Objective C Dynamic?
PPT
Actionscript
PPTX
Inheritance Mixins & Traits
PPT
Csharp4 objects and_types
KEY
Cappuccino
PDF
Variables in Pharo
PPT
Java Basics
KEY
Grand Central Dispatch Design Patterns
Inheritance
Introduction to OOP with PHP
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
Learn java
Presentation 3rd
[2015/2016] JavaScript
Variables in Pharo5
First class Variables in Pharo
Md02 - Getting Started part-2
Advanced oops concept using asp
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Barcelona
What Makes Objective C Dynamic?
Actionscript
Inheritance Mixins & Traits
Csharp4 objects and_types
Cappuccino
Variables in Pharo
Java Basics
Grand Central Dispatch Design Patterns

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
A Presentation on Artificial Intelligence
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
KodekX | Application Modernization Development
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Empathic Computing: Creating Shared Understanding
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Big Data Technologies - Introduction.pptx
Encapsulation theory and applications.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Monthly Chronicles - July 2025
A Presentation on Artificial Intelligence
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
KodekX | Application Modernization Development
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MYSQL Presentation for SQL database connectivity
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation_ Review paper, used for researhc scholars
Empathic Computing: Creating Shared Understanding
Agricultural_Statistics_at_a_Glance_2022_0.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Review of recent advances in non-invasive hemoglobin estimation
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Spectral efficient network and resource selection model in 5G networks
Big Data Technologies - Introduction.pptx

Parte II Objective C

  • 1. Objective-C Ing. Paolo Quadrani paolo.quadrani@gmail.com www.mitapp.com
  • 2. Introduction • Runtime - Obj-C performs many tasks at runtime (object allocation, method invocation) → require also a runtime environment ← • Objects - An object associate data with operations that can use or affect the data. • id - General data type for any kind of object • Object Messages - To get an object to do something, you send it a message telling it to apply a method. Messages are enclosed in brackets (e.g. [receiver message]; ). Methods in message are called selectors. • Classes - In Obj-C you define objects by defining their class. The class definition is a prototype for a kind of object. www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 3. Memory management • Reference counting (retain, release) • Manually managed or through the auto- release pool • Garbage collector (not used in iPhone programming, but in Cocoa). www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 4. Class Interface #import "ItsSuperclass.h" @class anotherClassForwarding; @interface ClassName : ItsSuperclass { // instance variable declarations float width; BOOL filled; NSString *name; } // method declarations - (void)setWidth:(float)width; + (id)initWithName:(NSString *)aName; @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 5. Class Implementation @implementation ClassName : ItsSuperclass { //instance variable declarations } //method definitions - (void)setWidth:(float)width { ... } @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 6. Class Allocation ... MyClass *obj = [[MyClass alloc] init]; obj->myVar = nil; ... www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 7. An Example The difference between self and super becomes clear in a hierarchy of three Messages to self and super that we create an object belonging to a class called Low. Low’s superclass is M All three classes define a method called negotiate, which they use for a var Mid defines an ambitious method called makeLastingPeace, which also has n This is illustrated in Figure 2-2: Figure 2-2 High, Mid, Low - reposition superclass { High – negotiate ... [self negotiate]; ... superclass } Mid – negotiate – makeLastingPeace - reposition { superclass ... Low – negotiate [super negotiate]; ... } We now send a message to our Low object to perform the makeLastingPea makeLastingPeace, in turn, sends a negotiate message to the same Low object self, www.MitAPP.com http://paoloquadrani.blogspot.com/ - makeLastingPeace http://twitter.com/MitAPP {
  • 8. Class Initialization • By convention initializer method begins with init e.g. initWithColor: ... • The return type should be id. • You should assign self to the value returned by the initializer. • Setting value of member variables, use direct assignment, not accessors. • If initializer fails, return nil, otherwise return self. www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 9. Initializer Example - (id)init { // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init if (self = [super init]) { creationDate = [[NSDate alloc] init]; } return self; } www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 10. Combining Allocation and Initialization • Some classes combine allocation and initialization returning a new, initialized instance of the class. Convenience constructors • Examples:+ (id)stringWithFormat:(NSString *)format + (id)arrayWithObject:(id)anObject; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 11. Protocols • Protocols declare methods that can be implemented in any class. Useful in: • Declare methods that others are expected to implement • Declare the interface to an object • Capture similarity among classes that are not hierarchically related www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 12. Declaring Protocol @protocol ProtocolName // method declarations @optional // optional method declarations @end @protocol MyXMLSupport - initFromXMLRepresentation:(NSXMLElement *)XMLElement; - (NSXMLElement *)XMLRepresentation; @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 13. Adopting a Protocol @interface ClassName : ItsSuperclass < protocol list > Ex: @interface MyClass : NSObject <UITextFieldDelegate, UIAlertViewDelegate> { ... } www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 14. Declared Properties • Declared properties provides a way to declare and implement an object’s accessor methods • The compiler can synthesize accessor methods for you www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 15. Property declaration and implementation @property(attributes) type name; @interface MyClass : NSObject { float value; } @property float value; - (float)value; - (void)setValue:(float)newValue; @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 16. Property Attributes @property(attributes) type name; • Writability • readwrite (the default) • readonly • Setter Semantics • assign (the default) - Used for scalar types such as NSInteger • retain - Used for objects on assignment. The previous value is sent a release. • copy - A copy of the object is used for the assignment. The previous value is sent a release. • Atomicity • nonatomic (by default) - The synthesized method provide robust access in a multi-threading environment. www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 17. Example of Property Declaration @property (nonatomic, retain) IBOutlet NSButton *myButton; @property (readonly) NSString *name; @property (assign) UITextFieldDelegate *delegate; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 18. Property Implementation • Provide one of these Implementation Directives inside the @implementation block: • @synthesize • @dynamic • Direct implement setter and getter methods www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 19. Example using @synthesize @interface MyClass : NSObject { .h NSString *value; } @property(copy, readwrite) NSString *value; @end @implementation MyClass .m @synthesize value; @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 20. Example using direct implementation @interface MyClass : NSObject { .h NSString *value; } @property(copy, readwrite) NSString *value; @end @implementation MyClass - (NSString *)value { .m return value; } - (void)setValue:(NSString *)newValue { if (newValue != value) { value = [newValue copy]; } } @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 21. DEMO • DEMO (10-15’): Looking real code www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 22. Selectors • In Objective-C selector has two meanings: • It refers to a name of a method • It refers to a unique identifier that replace the name when the code is compiled www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 23. SEL and @selector • Selectors are assigned to special type SEL • Valid selectors are never 0 • @selector() directive lets you refer to compiled selectors www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 24. Examples of selectors SEL setWidthHeight; setWidthHeight = @selector(setWidth:height:); setWidthHeight = NSSelectorFromString(aBuffer); NSString *method; method = NSStringFromSelector(setWidthHeight); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 25. Using a selector • NSObject protocol defines three methods that use selectors: • performSelector: • performSelector:withObject: • performSelector:withObject:withObject: www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 26. Example [friend performSelector:@selector(gossipAbout:) withObject:aNeighbor]; is equivalent to: [friend gossipAbout:aNeighbor]; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 27. Varying message at runtime • performSelector: and the other two allows you to varying messages at runtime. Using variables you can: id helper = getTheReceiver(); SEL request = getTheSelector(); [helper performSelector:request]; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 28. Avoiding Messaging Errors • Selectors send a message to an object at runtime • An object that doesn’t implement a method generate an error if someone try to send it a request to execute a non existent method • respondsToSelector: is used to check the existence of a method www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 29. Example if ( [anObject respondsToSelector:@selector(setOrigin::)] ) [anObject setOrigin:0.0 :0.0]; else fprintf(stderr, "%s can’t be placedn", [NSStringFromClass([anObject class]) UTF8String]); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 30. Using C++ with Objective-C • C++ can be used inside Objective-C code • This hybrid is called Objective-C++ • Inheritance of Objective-C classes from C+ + classes (and vice-versa) are not permitted www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 31. Example of mix #import <Foundation/Foundation.h> class Hello { private: id greeting_text; // holds an NSString public: Hello() { greeting_text = @"Hello, world!"; } Hello(const char* initial_greeting_text) { greeting_text = [[NSString alloc] initWithUTF8String:initial_greeting_text]; } void say_hello() { printf("%sn", [greeting_text UTF8String]); } }; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 32. Example (continue) @interface Greeting : NSObject { @private Hello *hello; } - (id)init; - (void)dealloc; - (void)sayGreeting; - (void)sayGreeting:(Hello*)greeting; @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 33. Example (continue) @implementation Greeting - (id)init { if (self = [super init]) { hello = new Hello(); } return self; } - (void)dealloc { delete hello; [super dealloc]; } - (void)sayGreeting { hello->say_hello(); } - (void)sayGreeting:(Hello*)greeting { greeting->say_hello(); } @end www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 34. iPhone Main UI arguments www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 35. Arguments • Dealing with data: User Defaults, SQLite • Touch events and Multi-Touch • Address book • Image Picker • Localization www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 36. Arguments • Dealing with data: User Defaults, SQLite • Touch events and Multi-Touch • Address book • Image Picker • Localization www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 37. Dealing with data • Property Lists • iPhone File System • Archiving Objects • SQLite • Web Services www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 38. Dealing with data • Property Lists • iPhone File System • Archiving Objects • SQLite • Web Services www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 39. Property Lists • Convenient way to store small amount of data • Array, dictionaries, strings, numbers • XML or binary format • NOT use it if • data is more then few KB, loading is all or nothing • Complex object graphs • Custom object types www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 40. Reading-Writing Property Lists // Writing - (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag; - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag; // Reading - (id)initWithContentsOfFile:(NSString *)aPath; - (id)initWithContentsOfURL:(NSURL *)aURL; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 41. Dealing with data • Property Lists • iPhone File System • Archiving Objects • SQLite • Web Services www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 42. iPhone File System • Each Application • Has its own sand-box • Has its own set of directories • Can read-write within its own directory www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 43. File Paths in Your App // Basic Directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); // Documents directories NSArray *paths = NSSearchPathForDirectoriesInDomain(NSDocumentDirectory, NSUserDomainMask,YES); NSString *documentsPath = [paths objectAtIndex:0]; // <Application Home>/Documents/foo.plist NSString *fooPath = [documentsPath stringByAppendingPathComponent:@”foo.plist”]; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 44. Include Writable Files in Your Application • Build it as part of your app bundle • You can’t modify the content of your app bundle, so: • On first launch, copy the writable to your Documents directory www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 45. Dealing with data • Property Lists • iPhone File System • Archiving Objects • SQLite • Web Services www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 46. Archiving Objects • Used for serialization of custom object types • Used by Interface Builder for NIBs • Archivable objects has to conform to the <NSCoding> protocol • Implement the two protocol methods: - (void)encodeWithCoder:(NSCoder *)coder; - (void)initWithCoder:(NSCoder *)coder; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 47. Example Coder // Encode an object for an archive - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject: name forKey:@”Name”]; [coder encodeIntger: numberOfSides forKey:@”Sides”]; } // Decode an object from an archive - (id)initWithCoder: (NSCoder *)coder { self = [super initWithCoder: coder]; name = [[coder decodeObjectForKey: @”Name”] retain]; numberOfSides = [coder decodeIntegerForKey: @”Side”]; } www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 48. Dealing with data • Property Lists • iPhone File System • Archiving Objects • SQLite • Web Services www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 49. SQLite • Complete SQL database in an ordinary file • Simple, compact, fast, reliable • No server is needed • Great for embedded devices • Included on the iPhone platform www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 50. When not to use SQLite • Multi-gigabyte database • High concurrency (multiple writers) • Client-server application www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 51. SQLite C API basic • Open the DB int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*, int, char **, char **), void *context, char **error); // Your callback int callback(void *context, int count, char **values, char **columns); • Close the DB int sqlite3_close(sqlite3 *db); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 52. SQLITE 3 • DEMO (10-15’): Real application with Sqlite3 www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 53. Core Data • Object graph management and persistence framework • Make it easy to save and load model objects • Higher-level abstraction then SQLite or property lists • Available on the MAC OSX desktop • Available only on iPhone OS 3.x and later www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 54. Dealing with data • Property Lists • iPhone File System • Archiving Objects • SQLite • Web Services www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 55. Integrating with Web Services • Many are exposed via RESTful interface with XML or JSON • Options for Parsing XML are: • libxml2 - C library • NSXMLParser - simpler but less powerful than the previous one • JavaScript Object Notation • More lightweight then XML • Looks like a property list • open source json-framework wrapper for Obj-C www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 56. JSON & XML PARSER • DEMO (10-15’): Real application with Json (Flickr API) & XML parser www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 57. Arguments • Dealing with data: User Defaults, SQLite • Touch events and Multi-Touch • Address book • Image Picker • Localization www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 58. Single Touch Sequence • UITouch represent a single finger • There are three phases in touch: • touchBegan • touchMoved • touchEnded www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 59. UIEvent: Collection of UITouch • UIEvent is a container for UITouch • Can give information on: • all touches • all touches in a window • all touches in a view www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 60. Receiving touches • UIResponder is the base class of touches ‘listener’ • Methods called are: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 61. Multiple Touches • Same events are generated then Single Touch • You must enable it to make it works BOOL multipleTouchEnabled; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 62. Arguments • Dealing with data: User Defaults, SQLite • Touch events and Multi-Touch • Address book • Image Picker • Localization www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 63. Address Book basics • Create a person and set some properties • Create a ABPersonViewController • Push the view controller onto the navigation stack www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 64. Get people from the Address Book ABAddressBookRef ab = ABAddressBookCreate(); CFArrayRef people = ABAddressBookCopyPeopleWithName(ab, name); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 65. Person • ABRecordRef • A collection of properties • First and last name • Image • Phone numbers, emails, etc... www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 66. Properties • Properties can have different types • String • Date • Dictionary, Data... • Some properties may have multiple values • Telephone: home, work, mobile... • Person properties in ABPerson.h www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 67. Retrieve and Set Single Value Properties // Retrieve the first name of a person CFStringRef first = ABRecordCopyValue(person, kABPersonFirstNameProperty); // Update or Set the birthday of a person CFDateRef date = CFDateCreate( ... ); ABRecordSetValue(person, kABPersonBirthdayProperty, date, &error); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 68. Retrieve Multi Value Properties (ABMultiValueRef) // Getting multiplicity CFIndex count = ABMultiValueGetCount(multiValue); // and getting the value CFTypeRef value = ABMultiValueCopyValueAtIndex(mv, index); // and getting the lable CFStringRef label = ABMultiValueCopyLabelAtIndex(mv, index); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 69. Update Multi Value Properties // Get the multi value reference ABMultiValueRef urls = ABRecordCopyValue(person, kABPersonURLProperty); // Create the multi value mutable copy ABMutableMultiValueRef urlCopy = ABMultiValueCreateMutableCopy(urls); // Add the new value ABMultiValueAddValueAndLabel(urlCopy, “the url”, “url label”, NULL); ABRecordSetValue(person, urlCopy, kABPersonURLProperty); // Save the Address Book ABAddressBookSave(ab, &error); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 70. Person View Controller • ABPersonViewController • displayedPerson • displayedProperties • allowsEditing www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 71. Arguments • Dealing with data: User Defaults, SQLite • Touch events and Multi-Touch • Address book • Image Picker • Localization www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 72. Image Picker Interface • UIImagePickerController class • Handles all user and device interactions • Built on top of UIViewController • UIImagePickerControllerDelegate protocol • Implemented by your delegate object www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 73. Displaying the Image Picker • Check the source available • Assign a delegate object • Present the controller modality www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 74. Example Code if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypeCamera; picker.delegate = self; [self presentModalViewController:picker animated:YES]; } www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 75. UIImagePickerController delegate methods • Two methods: - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; - (void)imagePickerControllerDidCancel: (UIImagePickerController*)picker; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 76. Define your delegate object - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // Save or use the image picked here. UIImage *image = [info objectForKey: UIImagePickerControllerOriginalImage]; // Dismiss the image picker. [self dismissModalViewControllerAnimated:YES]; [picker release]; } www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 77. Define your delegate object - (void)imagePickerControllerDidCancel: (UIImagePickerController*)picker { // Dismiss the image picker. [self dismissModalViewControllerAnimated:YES]; [picker release]; } www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 78. Manipulating the returned Image • If allowsImageEditing property is YES: • User allowed to crop the returned image • Image metadata returned in “info” NSDictionary www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 79. Arguments • Dealing with data: User Defaults, SQLite • Touch events and Multi-Touch • Address book • Image Picker • Localization www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 80. Localizing an Application • Multiple Languages and locales in a single built application • Keep localized resources separate from everything else • Strings • Images • User Interfaces www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 81. Where do localized resources do? • MyApp.app/ • MyApp • English.lproj/ • Localizable.strings • MyView.nib • Italian,lproj/ • Localizable.strings • MyView.nib www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 82. Localized Strings • For user-visible strings in application code • Map from an non localized key to a localized string • Stored in .strings files • Key-value pairs • Use UTF-16 for encoding www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 83. Example of .strings • en.lproj/Greetings.strings “Hello” = “Hello”; “Welcome to %@” = “Welcome to%@”; • it.lproj/Greetings.strings “Hello” = “Ciao”; “Welcome to %@” = “Benvenuto a %@”; www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 84. Accessing localized strings // By default, uses Localizable.strings NSLocalizedString(@”Hello”, @”Greeting for welcome screen”); // Specify a table, uses Greetings.strings NSLocalizedStringFromTable(@”Hello”, @”Greetings”, @”Greeting for welcome screen”); www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 85. genstrings • Tool to scan your code and produce a .strings file • Inserts comments found in code as clues to localizer • Run the tool over your *.m files www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
  • 86. Localizing XIBs • Xcode allows you to generate localized version of your User Interface www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP