SlideShare une entreprise Scribd logo
1  sur  86
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

Contenu connexe

Tendances

JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHoward Lewis Ship
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Javameysholdt
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 

Tendances (20)

JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Objective c
Objective cObjective c
Objective c
 
Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Runtime
RuntimeRuntime
Runtime
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Java
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 

En vedette

Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightGiuseppe Arici
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingGiuseppe Arici
 
Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013Giuseppe Arici
 
Iphone programming: Objective c
Iphone programming: Objective cIphone programming: Objective c
Iphone programming: Objective cKenny Nguyen
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps DevelopmentProf. Erwin Globio
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 

En vedette (15)

Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Digital Universitas
Digital UniversitasDigital Universitas
Digital Universitas
 
GDB Mobile
GDB MobileGDB Mobile
GDB Mobile
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Objective-C @ ITIS
Objective-C @ ITISObjective-C @ ITIS
Objective-C @ ITIS
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Objective-C
Objective-CObjective-C
Objective-C
 
Iphone programming: Objective c
Iphone programming: Objective cIphone programming: Objective c
Iphone programming: Objective c
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps Development
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Apple iOS
Apple iOSApple iOS
Apple iOS
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Similaire à Parte II Objective C

Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.pptAshwathGupta
 
Learn java
Learn javaLearn java
Learn javaPalahuja
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
First class Variables in Pharo
First class Variables in PharoFirst class Variables in Pharo
First class Variables in PharoESUG
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaMatthias Noback
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsRobert Brown
 

Similaire à Parte II Objective C (20)

Inheritance
InheritanceInheritance
Inheritance
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Learn java
Learn javaLearn java
Learn java
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
First class Variables in Pharo
First class Variables in PharoFirst class Variables in Pharo
First class Variables in Pharo
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Advanced oops concept using asp
Advanced oops concept using aspAdvanced oops concept using asp
Advanced oops concept using asp
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
Actionscript
ActionscriptActionscript
Actionscript
 
Inheritance Mixins & Traits
Inheritance Mixins & TraitsInheritance Mixins & Traits
Inheritance Mixins & Traits
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Cappuccino
CappuccinoCappuccino
Cappuccino
 
Variables in Pharo
Variables in PharoVariables in Pharo
Variables in Pharo
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 

Dernier

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 

Dernier (20)

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 

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