SlideShare una empresa de Scribd logo
1 de 101
iPhone SDK a Ki k start
                                      iPh    SDK: Kick t t
                                                 Using Xcode 3.1 Developer Tools for iPhone OS




Copyright is held by the author/owner(s).
OOPSLA 2008, October 19–23, 2008, Nashville, Tennessee, USA.
ACM 978-1-60558-220-7/08/10.
Agenda

1.
1 Introduction
   Apple Developer Connection, iPhone platform; Tools for development;.

2. Objective-C language
   syntaxes; memory management; design patterns.

3. Creating a new project
   simple “Hello World” example; simple drawing; multi touch events; configuration list
      p                     p       p         g                           g

4. UI components
   windows, views and view controllers; using Interface Builder.

5. iPhone in action
   accelerometers; localization; media; openGL ES

6. Exercises and references


                                                                                          2
Our Objective



Using XCode 3.1 under Mac OS X 10.5 as our IDE, and Objective-C and iPhone API

as our programming t l we will create iPh
               i tools     ill     t iPhone applications (f
                                               li ti     (from b i t medium
                                                               basic to di

level) which finally can be loaded into an iPhone. We’ll start with the classical “Hello

World” d
W ld” and continue t d
             ti    to develop applications using graphical user i t f
                          l      li ti       i       hi l       interfaces, handling
                                                                            h dli

multi-touch and detect motion, communication with web application, and different

media.
  di




                                                                                           3
Material




       Google Groups :: OOPSLA08 iphone
       G   l G                   i h



http://groups.google.com/group/oopsla08-iphone
htt //            l     /     /    l 08 i h




                                                        4
Introduction
I t d ti
          1.1.
What is it ?

iPhone is a pretty new device that involve several t h l i ( h
iPh     i      tt      d i th t i      l         l technologies (phone, video,
                                                                         id
audio, images, and web among others).

The best in 2007 year according to Times Magazine,

Big winner in the 2008 British Technology Awards. Claimed the award for Gadget of
the Year , won the Best Mobile Technology, Most Stylish Technology, and
Technological Innovation of the Year awards.

It has captive the interest of different types of users and created a new emerging
market in various environments. Today thousands of programmers want to provide
applications on the iPhone.

It includes multi touch interface, sensors and a camera.




                                                                                     6
Go ahead




       7
Developer Connection




                   8
iPhone SDK


                • Sample code
Documentation   • Reference libraries
                • Coding how-to


                • UIKit
                • Foundation
 Frameworks     • Media
                • OpenGL / Quartz / Core Graphics
                   p                        p


                • Xcode,
    Tools       • Interface Builder
                • iPhone Simulator




                                                             9
Install

1. Boot into a partition with the Mac OS X v10.5.3 installed.

2. Download the iPhone SDK software.

3. Double-click on iPhone SDK installer package.

4. Follow the instructions in the Installer.

5. To i t ll Xcode 3.1 in directory other th th d f lt /D
5 T install X d 3 1 i a di t         th than the default /Developer, you must specify a
                                                              l             t     if
   new <Xcode> directory name on the "Custom Install" pane; e.g. Xcode3.1.


      Select the folder icon under "Location" next to the "Developer Tools Essentials"
      package name.
      Select "Other..." at the top of the pop-up.
      Navigate to the location for the new <Xcode> folder Select "New Folder".
                                                   folder.        New Folder

                                                                                         10
Install

       Enter folder
       E t a f ld name i th "N
                       in the "New F ld " window; e.g. X d 3 1 S l t "C t "
                                   Folder" i d         Xcode3.1. Select "Create".
       Finally, select "Choose" in the "Install Xcode Tools" pane.


6. If you need to install Mac OS X 10.3.9 Support or WebObjects, you must select
   "Customize", and check those packages on the "Custom Install" panel.

7. Authenticate as the administrative user. The first user you create when setting up Mac
                                                           y                     g p
   OS X has administrator privileges by default.



Developer applications such as Xcode, Instruments, and Interface Builder are

installed in <Xcode>/Applications.



                                                                                            11
Uninstall

To uninstall Xcode developer tools on the boot volume along with the <Xcode> directory from a
                                                                             directory,
Terminal window type:

$ sudo <Xcode>/Library/uninstall-devtools --mode=all

If you just want to remove the underlying developer content on the boot volume, but leave the
<Xcode> directory and supporting files untouched, from a Terminal window type:

$ sudo <Xcode>/Library/uninstall-devtools --mode=systemsupport

If you just want to just remove the UNIX development support on the boot volume, but leave
the <Xcode> directory and supporting files untouched, from a Terminal window type:

$ sudo <Xcode>/Library/uninstall-devtools --mode=unixdev

Finally, to just uninstall the <Xcode> directory you can simply drag it to the trash, or from a
Terminal window type:

$ sudo <Xcode>/Library/uninstall-devtools --mode=xcodedir
       <Xcode>/Library/uninstall devtools   mode xcodedir


                                                                                                  12
Time to Work 1
Install iPhone SDK
Tools for D
T l f Development
            l   t
               1.2
Tools

We are going to be working with:


    Xcode

    Interface Builder

    iPhone Simulator



  And also need to consider

    Instruments


                                       15
Xcode

The f
Th focus of your development experiences is th X d application. X d i
            f     d    l      t     i      i the Xcode      li ti     Xcode is
an integrated development environment (IDE) that provides all of the tools you
need to create and manage your iPhone projects and source files, build your
code into an executable, and run and debug y
                         ,               g your code either in iPhone
simulator or on a device.



To create a new iPhone application, you start by creating a new project in
Xcode. A project manages all of the information associated with your
application, including the source files, build settings, and rules needed to put all
of the pieces t
 f th i        together. The heart of every Xcode project is th project windows.
                   th Th h t f               X d        j t i the    j t i d




                                                                                   16
Xcode




    17
Xcode

                                      editor,
Xcode comes with an advanced text editor which supports features such as code
completion, syntax coloring, code folding (to hide code blocks temporarily), and
inline annotations for errors, warnings, and notes. The build system in Xcode
provides both appropriate default settings and the ability to customize the
environment.
environment And if you need documentation the Research Assistant provides
                                documentation,
context-sensitive documentation while the Xcode documentation window lets you
browse and search for information.



When you build your application in Xcode, you have a choice of building it for
iPhone simulator or for a device. The simulator provides a local environment for
testing your applications to make sure they behave essentially the way you want.
After you are satisfied with your application’s basic behavior, you can tell Xcode to
build it and run it on an iPhone or iPod touch connected to your computer. Running
on a device provides the ultimate test environment, and Xcode lets you attach the
built-in debugger to the code running on the device.


                                                                                        18
Xcode




    19
Interface Builder

Interface Builder is the tool you use to assemble your application s user interface
                                                         application’s
visually. Using Interface Builder, you assemble your application’s window by
dragging and dropping preconfigured components onto it. The components include
standard system controls such as switches, text fields, and buttons, and also
custom views to represent the views your application provides. After you’ve placed
the
th components on the window’s surface, you can position th
               t      th   i d ’        f                 iti them b d
                                                                    by dragging th
                                                                             i them
around, configure their attributes using the inspector, and establish the relationships
between those objects and your code. When your interface looks the way you want
it, you save the contents to a nib file, which is a custom resource file format.



The nib files you create in Interface Builder contain all the information that the UI Kit
needs to recreate the same objects in your application at runtime. Loading a nib file
creates runtime versions of all the objects stored in the file configuring them exactly
                                                           file,
as they were in Interface Builder. It also uses the connection information you
specified to establish connections between the newly created objects and any
existing objects in your application. These connections provide your code with
pointers to the nib-file objects and also provide the information the objects
themselves need t communicate user actions t your code.
th      l        d to           i t         ti    to          d

                                                                                        20
Interface Builder




                21
Instruments

To ensure that you deliver the best user experience for your software the
                                                                  software,
Instruments environment lets you analyze the performance of your iPhone
applications while running in the simulator or on a device. Instruments gathers data
from your running application and presents that data in a graphical display called
the timeline. You can gather data about your application’s memory usage, disk
activity, network activity, and graphics performance. Th ti li view can di l
   ti it    t    k ti it       d     hi      f           The timeline i         display
all of the different types of information side by side, letting you correlate the overall
behavior of your application, not just the behavior in one specific area. To get even
more detailed information, you can also view the detailed samples that Instruments
g
gathers.



In addition to providing the timeline view, Instruments provides tools to help you
analyze your application’s behavior over time For example the Instruments window
               application s               time.    example,
lets you store data from multiple runs so that you can see whether your
application’s behavior is actually improving or whether it still needs work. You can
save the data from these runs in an Instruments document and open them at any
time.


                                                                                            22
Instruments




          23
Instruments




          24
Time to Work 2
XCode,
XC d IB and Instruments example
          dI t       t       l
iPhone Pl tf
iPh    Platform
             1.3
Introduction

iPhone Pl tf
iPh     Platform comprises th operating system and t h l i th t you use
                        i    the      ti     t      d technologies that
to run applications natively on iPhone and iPod touch devices and iPhone OS.

Although it shares a common heritage and many underlying technologies with
Mac OS X, iPhone OS was designed to meet the needs of a mobile
environment, where user’s needs are slightly different. Existing Mac OS X
developers will find many familiar technologies, but they’ll also find
technologies that are available only on iPhone OS such as the Multi-Touch
                                               OS,
interface and accelerometer support.




                                                                             27
Key Concepts

iPhone SDK supports the creation of graphically oriented applications that run
                                    graphically-oriented
natively in iPhone OS.

Take advantage of built-in hardware such as the accelerometers, camera, and
graphics hardware
         hardware.

All of the application’s data is displayed in a single window. This has lead to the
creation of new views and controls that allow you to present your application’s
data in an organized manner
                       manner.

The event-handling model in iPhone OS also represents a significant departure
from traditional desktop applications. Instead of relying on the traditional mouse
and keyboard events iPhone OS introduces the idea of touch events
               events,                                           events.

User experience.

Memory management without a “garbage collector”.
                             garbage collector

                                                                                  28
Architecture

Layers
L



         Cocoa Touch


            Media


         Core Services


           Core OS



                                    29
Layers

Core OS and Core Services l
C           dC      S   i    layers contain th f d
                                       t i the fundamental i t f
                                                           t l interfaces f
                                                                          for
iPhone OS, including those used for accessing files, low-level data types,
Bonjour services, network sockets, and so on. These interfaces are mostly C
based and include technologies such as:
                           g


  Core Foundation,
  CFNetwork,
  SQLite,
  Access to POSIX threads,
  UNIX sockets
  Among others.



                                                                                30
Layers

Media layer contains th f d
M di l          t i the fundamental t h l i used t support 2D and 3D
                                    t l technologies   d to       t      d
drawing, audio, and video. This layer includes the C-based technologies:


  OpenGL ES,
  Quartz, and
  Core Audio,
  Core Animation, an advanced Objective-C based animation engine.




                                                                         31
Layers

In the Cocoa Touch layer most of the technologies use Objective C The
                     layer,                             Objective-C.
frameworks at these layers provide the fundamental infrastructure used by your
application. For example:


  the Foundation framework provides object-oriented support for collections,
  file management, network operations, and more.

  the UIKit framework provides the visual infrastructure for your application,
  including classes for windows, views, controls, and the controllers that
  manage those objects.

  Other frameworks at this level give you access to the user’s contact and
  photo information and to the accelerometers and other hardware features of
  the device.

                                                                                 32
Starting Point

The t ti
Th starting point for any new project is the C
              i tf               j t i th Cocoa T
                                                Touch l
                                                    h layer, and th UIKit
                                                               d the
framework in particular.

The higher-level frameworks make it easy to support standard system
behaviors with the least amount of effort on your part.




                                                                            33
Time to Work 3
Objective-C Language
Obj ti C L
                   2
Objective-C
                                                                 Objective C

The Objective-C language is a simple computer language designed to enable
     Objective C
sophisticated object-oriented programming. Objective-C extends the standard ANSI
C language by providing syntax for defining classes, methods, and properties, as
well as other constructs that promote dynamic extension of classes. The class
syntax and design are based mostly on Smalltalk, one of the first object-oriented
programming l
           i languages.

If you have programmed with object-oriented languages before, the following
information should help you learn the basic syntax of Objective-C. Many of the
traditional object-oriented concepts, such as encapsulation, inheritance, and
            object oriented
polymorphism, are all present in Objective-C. There are a few important differences,
but those differences are called out in this article and more detailed information is
available if you need it.

If you have never programmed using an object oriented language before you need
                                         object-oriented           before,
to have at least a basic understanding of the associated concepts before
proceeding. The use of objects and object-oriented constructs is fundamental to the
design of iPhone applications, and understanding how they interact is critical to
creating your applications.


                                                                                    36
Files


     Extension                              Source Type
.h               Header files. Header files contain class, type, function, and
                 constant declarations.

.m               Source files. This is the typical extension used for source files
                 and can contain both Objective-C and C code.

.mm              Source files. A source file with this extension can contain C++
                 code in addition to Objective-C and C code.

                 This t
                 Thi extension should be used only if you actually refer to C++
                             i    h ld b      d l            t ll    f t C
                 classes or features from your Objective-C code.




                                                                                     37
#import

When
Wh you want to include header fil i your source code, you can use th
               t t i l d h d files in                   d                the
standard #include compiler directive but Objective-C provides a better way.

The #import directive is identical to #include, except that it makes sure that the
same file is never included more than once.

The Objective-C samples and documentation all prefer the use of #import, and
your own code should too.




                                                                                     38
Strings

The NSSt i
Th NSString class provides an object wrapper f strings th t has all of th
                 l        id        bj t           for t i    that h     ll f the
advantages you would expect, including built-in memory management for
storing arbitrary-length strings, support for Unicode, printf-style formatting
utilities, and more. Because such strings are used commonly though,
         ,                              g                       y      g ,
Objective-C provides a shorthand notation for creating NSString objects from
constant values. To use this shorthand, all you have to do is precede a normal,
double-quoted string with the @ symbol, as shown in the following examples:


  NSString*     myString = @”Hello Worldn";


  NSString*     anotherString = [
       NSString stringWithFormat:@"%d %s", 1, @"String”
  ];


                                                                                    39
Note

Cocoa F
C     Framework i d i d f
               k is derived from th N XTSTEP and OPENSTEP
                                 the NeXTSTEP d
programming environments developed by NeXT in the late 1980s.

Apple acquired NeXT in December 1996, and subsequently went to work on
the Rhapsody operating system that was supposed to be the direct successor
of OPENSTEP.

The OPENSTEP base of libraries and binary support was termed Yellow Box.
Rhapsody evolved into Mac OS X, and the Yellow Box became Cocoa.

As a result, Cocoa classes begin with the acronym "NS" (standing either for the
NeXT-Sun
NeXT Sun creation of OPENSTEP or for the original proprietary term for the
                      OPENSTEP,
OPENSTEP framework, NeXTSTEP): NSString, NSArray, etc.




                                                                              40
Class

The specification of a class in Objective C requires two distinct pieces: the
                                Objective-C
interface and the implementation.

The interface portion contains the class declaration and defines the instance
variables and methods associated with the class
                                            class.

The implementation portion contains the actual code for the methods of the
class.

The class declaration always begins with the @interface compiler directive and
ends with the @end directive. Following the class name (and separated from it
by a colon) is the name of the parent class. The instance (or member) variables
of the class are declared in a code block that is delineated by braces ({ and })
                                                                              }).
Following the instance variable block is the list of methods declared by the
class. A semicolon character marks the end of each instance variable and
method declaration.


                                                                                41
Class

@interface MyClass : NSObject

{
        int count;
        id data;
        NSString* name;
}

- (id)initWithString:(NSString *)aName;

+ (MyClass *)createMyClassWithString: (NSString *) aName

@end




                                                               42
Class

@implementation MyClass

- (id)initWithString:(NSString *) aName
{
    if (self = [super init]) {
        count = 0;
        data = nil;
        name = [aName copy];
        return self;
    }
}

+ (MyClass *)createMyClassWithString: (NSString *) aName
{
    return [[[self alloc] initWithString:aName] autorelease];
}

@end




                                                                    43
Methods

A class in Objective C can declare two types of methods: instance methods
           Objective-C
and class methods.

An instance method is a method whose execution is scoped to a particular
instance of the class In other words before you call an instance method you
                class.         words,                            method,
must first create an instance of the class.

Class methods, by comparison, do not require you to create an instance.

The declaration of a method consists of the method type identifier, a return
type, one or more signature keywords, and the parameter type and name
information.

The colon characters declare the presence of a parameter. If a method has no
parameters, you omit the colon after the first (and only) signature keyword. In
this example, the method takes two parameters.


                                                                                  44
Methods

-(void)insertObject:(id)anObject atIndex:(NSUInteger)index
 (void)insertObject:(id)anObject

…

[ y
[myArray insertObject:anObj atIndex:0];
       y         j        j          ]




    Method Type

    Return Type

    Signature keywords

    Parameter Types

    Parameter Names

                                                                   45
Properties

Properties are a convenience notation used to replace accessor method
declarations. Properties do not create new instance variables in your class
declaration.

They are simply a shorthand for defining methods that access existing instance
variables. Classes that expose instance variables can do so using the property
notation instead of using getter and setter syntax. Classes can also use
properties to expose “virtual” instance variables—that is, pieces of data that are
computed dynamically and not actually stored in instance variables.
                                                            variables

Practically speaking, properties reduce the amount of redundant code you have
to write. Because most accessor methods are implemented in similar ways,
properties eliminate the need to provide a distinct getter and setter method for
each instance variable exposed in the class. Instead, you specify the behavior
you want using the property declaration and then synthesize actual getter and
setter methods based on that declaration at compile time.


                                                                                 46
Propierties

@property BOOL flag;

@property (copy) NSString* nameObject; //Copy the object during assignment.

@property (
 p p    y (readonly) UIView* rootView;
                  y)                     // Create only a g
                                                      y   getter method.



…



myObject.flag = YES;

CGRect   viewFrame = myObject.rootView.frame;




                                                                              47
Protocols and Delegates

A protocol declares methods that can be implemented by any class Protocols are not classes
                                                              class.
themselves. They simply define an interface that other objects are responsible for
implementing. When you implement the methods of a protocol in one of your classes, your
class is said to conform to that protocol.

In iPhone OS protocols are used frequently to implement delegate objects A delegate object is
           OS,                                                         objects.
an object that acts on behalf of, or in coordination with, another object.

By example, the UIApplication class implements the required behavior of an application.
Instead of forcing you to subclass UIApplication to receive simple notifications about the current
state of the application, the UIApplication class delivers those notifications by calling specific
methods of its assigned delegate object. An object that implements the methods of the
UIApplicationDelegate protocol can receive those notifications and provide an appropriate
response.

The dec a a o o a p o oco looks s
   e declaration of protocol oo s similar to that o a c ass interface, with the e cep o s that
                                       a o a of class e ace,                  e exceptions a
protocols do not have a parent class and they do not define instance variables.

In the case of many delegate protocols, adopting a protocol is simply a matter of implementing
the methods defined by that protocol. There are some protocols that require you to state
explicitly that y support the p
   p     y      you pp        protocol, and p
                                      ,     protocols can specify both required and optional
                                                           p    y        q            p
methods.

                                                                                                 48
Time to Work 4
A classical Fraction class
Fraction.h
                                   Fraction h

        <Foundation/NSObject.h>
#import <Foundation/NSObject h>

@interface Fraction: NSObject {

    int numerator;
    int denominator;

}

-(void) print;
-(void) setNumerator: (int) d;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;

@end




                                            50
Fraction.m
                                                                 Fraction m

        "Fraction.h"
#import "Fraction h"
#import <stdio.h>

@implementation Fraction

-(void) print {   printf( "%i/%i", numerator, denominator ); }

-(void) setNumerator: (int) n {     numerator = n; }

-(void) setDenominator: (int) d {     denominator = d; }

-(int) denominator {     return denominator; }

-(int) numerator {     return numerator; }

@end




                                                                          51
main.m
                                                main m

   p
#import <stdio.h>
#import "Fraction.h"

int main( int argc, const char *argv[] ) {

    Fraction *frac = [[Fraction alloc] init];
                     [[              ]     ]
    [frac setNumerator: 1];

    [frac setDenominator: 3];

    printf( "The fraction is: " );

    [frac print];

    printf( "n" );

    [f      l    ]
    [frac release];

    return 0;
}




                                                     52
Creating
C ti an A li ti
         Application
                  3.1
Introduction

At a high l
     hi h level, th process f creating an iPh
               l the        for    ti     iPhone application i similar t th t
                                                    li ti is i il to that
for creating a Mac OS X application.

Both use the same tools and many of the same basic libraries. Despite the
similarities, there are also significant differences.

An iPhone is not a desktop computer; it has a different purpose and requires a
very different design approach. That approach needs to take advantage of the
strengths of iPhone OS and forego features that might be irrelevant or
impractical in a mobile environment.

The smaller size of the iPhone and iPod touch screens also means that your
application's user interface should be well organized and always focused on the
information the user needs most.



                                                                                 54
Steps

1. Main

2. Delegate

3.
3 Views




                  55
Views

1. Main

2. Delegate

3.
3 Views




                  56
Steps

Initializing the
I iti li i th application
                 li ti



Displaying a window



Drawing custom content



Handling touch events




                                57
Project Window Based
                          Window-Based

1. Foundation

2. CoreGraphics

3.
3 UIKit




                                     58
main.m
                                                                   main m

int main(int argc, char *argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int retVal = UIApplicationMain(argc, argv, nil, nil);

    [pool release];

    return retVal;

}




                                                                        59
Application Delegate

One f th
O of the most important architectural d t il of your project i d fi i th
                ti    t t     hit t l details f             j t is defining the
application delegate object, which is instantiated from a class you provide in
your project.

The application delegate class declares its interface in a *.h file and defines its
implementation in a *.m file.

Delegate is responsible of creating the window and views of the apps: using
interface Builder or programatically.




                                                                                      60
Application Delegate


#import <UIKit/UIKit.h>

@class MiVista;

@interface HolaMundoAppDelegate : NSObject <UIApplicationDelegate>
{

    UIWindow *window;

    MiVista *vista;

}

@property (nonatomic, retain) UIWindow *window;

@property (nonatomic, retain) MiVista *vista;

@end


                                                                     61
Application Delegate

         HOLAMUNDOAPPDELEGATE.H
#IMPORT "HOLAMUNDOAPPDELEGATE H”
#IMPORT "MIVISTA.H”

@IMPLEMENTATION HOLAMUNDOAPPDELEGATE

@SYNTHESIZE WINDOW;
@SYNTHESIZE VISTA
            VISTA;

-    (VOID)APPLICATIONDIDFINISHLAUNCHING :(UIAPPLICATION *)APPLICATION {
    SELF.WINDOW =
    [[[UIWINDOW ALLOC] INITWITHFRAME:[[UISCREEN MAINSCREEN] BOUNDS]] AUTORELEASE];
    SELF.VISTA =
    [[[MIVISTA ALLOC] INITWITHFRAME:[[UISCREEN MAINSCREEN] APPLICATIONFRAME]] AUTORELEASE];
    [WINDOW ADDSUBVIEW:VISTA];
    [WINDOW MAKEKEYANDVISIBLE];

}

- (VOID)DEALLOC {
  [VISTA RELEASE];
  [WINDOW RELEASE];
  [SUPER DEALLOC];
}

@END


                                                                                              62
Create a view (programatically)

import <UIKit/UIKit.h>
i
#          i /   i h
@interface MiVista : UIView {

    UILabel *miTexto;

}

@property (nonatomic, retain) UILabel *miTexto;

@end




                                                              63
Create a view (programatically)

          MiVista.h
##import "MiVista h”
@implementation MiVista(id)initWithFrame:(CGRect)rectangulo {

-(id)initWithFrame:(CGRect)rectangulo   {
    [super initWithFrame:rectangulo];

     self.backgroundColor =[UIColor whiteColor];
       lf b k      dC l    [UIC l    hit C l ]
    CGRect contenidoRectangulo = self.frame;
    CGFloat margenIzquierdo = 90.0;
    CGFloat anchoTextField = contenidoRectangulo.size.width * 0.72;
    CGFloat posicionTextField = (contenidoRectangulo.size.width - anchoTextField)/2.0;
    CGRect etiqueta =
    CGRectMake(posicionTextField,margenIzquierdo,anchoTextField,FONT_SIZE* HEIGHT_MULTIPLIER);
    UILabel *miTexto = [[UILabel alloc] initWithFrame:etiqueta];
    miTexto.text = @"Hola Mundo"; miTexto.font = [UIFont systemFontOfSize:FONT_SIZE];
    miTexto.textColor = [UIColor redColor];
    miTexto.textAlignment = UITextAlignmentCenter;
    [self addSubview:miTexto];
    [miTexto release];         return self;}
}

-(void)dealloc  {
    [super dealloc];
}
@end



                                                                                                 64
Touch E
T   h Events
          t
          3.2
Handling Touch Events

    UIView are part of UIR
All UIVi          t f UIResponder and can i l
                              d     d     implement E
                                                  t Event “li t
                                                        t “listener”
                                                                   ”



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



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



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




                                                                       66
Handling Touch Events




                    67
Plist file
Pli t fil
        3.3
plist file

<?xml version="1.0" encoding="UTF-8"?>
    l     i   "1 0"     di    "   8"
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
       y                      y
    <key>CFBundleIconFile</key>
    <string>Icon.png</string>
    <key>CFBundleIdentifier</key>
    <string>com.yourcompany.${PRODUCT_NAME:identifier}</string>




                                                                           69
plist file

    <key>CFBundleInfoDictionaryVersion</key>
     k        dl   f i i           i   /k
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>1.0</string>
    <key>UIStatusBarHidden</key>
    <true/>
    <key>NSMainNibFile</key>
    <string>MainWindow</string>
</dict>
</plist>


                                                        70
Time to Work 5
UI components
           4.1
Interface Builder

File’s Owner, it i a proxy object. It i a
Fil ’ O          is         bj t is
placeholder for the object responsible of
manage the content.



The library




                                                            73
View-Based
                                             View Based Project

Create
C t a view-based project
       i   b   d    j t



ViewController f
    C           files are created
automatically (h, m y xib)



Open ViewController.xib: add text field, a
label, and a button.

Add a UIImage if you want, to complete the
GUI.



                                                              74
Connecting the UI with the code

    STEP 1: open ViewController h:
                 ViewController.h:


#import <UIKit/UIKit.h>

@interface IBViewController : UIViewController {

IBOutlet UITextField *txtName;

IBOutlet UILabel *lbHello;

}

@property (nonatomic, retain) IBOutlet UITextField *txtName;

@property (nonatomic, retain) IBOutlet UILabel *lbHello;

-   (IBAction) updateText:(id) sender;

@end



                                                                  75
IBOutlet and IBAction



IBOutlet is a null-defined macro, which the C
preprocessor

An outlet is an instance variable that identifies an
object

IBAction, like IBOutlet, is a null defined macro,
which the C preprocessor removes at compile
time




                                                                    76
Connecting the UI with the code

STEP 2: open ViewController.xib:
     2       Vi C t ll       ib

Click in the view (outside button, label and so) : connections inspector : new
reference outlet : and connect to file’s owner proxy object.

Click in the textfield : connections inspector : new reference outlet : and
connect to file’s owner proxy object.

Click in the label : connections inspector : new reference outlet : and connect
to file’s owner proxy object.

Click in the label : connections inspector : Touch up inside: and connect to
file’s owner proxy object.




                                                                                  77
Connecting the UI with the code

    STEP 3: open ViewController.m:
         3       Vi C t ll

#import "IBViewController.h”
@implementation IBViewController@synthesize txtName, lbHello;

-(IBAction) updateText:(id) sender {NSString *text;
   if ([txtName.text length] == 0) {
      text = @"escibe tu nombre";
   } else {
      text = [[NSString alloc] initWithFormat:@"Hola %@!", txtName.text];
   }
   lbHello.text = text;[text release];
}

-    (void)dealloc {
    [super dealloc];
}

@end




                                                                            78
Navigation
Na igation Based
              4.2
Navigation-Based
                                        Navigation Based Project

Create
C t a navigation-based project
         i ti b      d    j t



ViewController f
     C         files are created and include
a UITable component automatically (h, m y
xib)

Execute the code




                                                               80
Updating UITable data

At RootViewController.m
   R tVi C t ll




                                              81
UITable and more views together

One
O more View
       Vi

 Double click RootViewController.xib to open Interface Builder

 Click un File New : and select View
 C

 Add a Label or TextView to the View

 Save it inside the project directory. Close Interface Builder and drag the new
 XIB file to Resources Folder.




                                                                                  82
UITable and more views together

One more ViewController
    File : New : and select UIViewController subclass.
    You need a new m and h file.
    In the h file add a new outlet for the textview:
#import <UIKit/UIKit.h>

@interface VistaDosViewController : UIViewController {

    IBOutlet UITextView* texto;

}

@property (nonatomic, retain) IBOutlet UITextView *texto;
@                 i       i                   i

@end

    Open IB, select TextView : conections inspector : new outlet, and link with File’s
    owner (and select the corresponding ViewController)


                                                                                         83
UITable and more views together

One
O more ViewController ( m fil )
       Vi C t ll          file)




                                                          84
Associate view and view controller

Double li k in the file VistaDos.xib
D bl click i th fil Vi t D        ib

Click File’s Owner, then click tools -> identity inspector

Select VistaDosViewControler in the dropdown class
S                  C

Click in any place of the view to select it, next tools – connections inspector,
new reference outlet, and drag to file owner.
                               g




                                                                                   85
Manipulation
Data Manip lation
               4.3
Simple Object

Create
C t a new Fil of NSObj t subclass t
          File f NSObject b l     type.
#import <UIKit/UIKit.h>
@interface Fruta : NSObject {
   NSString *nombre;NSString *descripcion;
}
@property(nonatomic, copy) NSString *nombre;
@property(nonatomic, copy) NSString *descripcion;

-(id) initWithNombre:(NSString*)n descripcion:(NSString *) d;
@end


#import "Fruta.h“
@implementation Fruta {
@synthesize nombre, descripcion;
-(id) initWithNombre:(NSString*)n descripcion:
(NSString )d {self nombre
(NSString*)d {self.nombre = n;
self.descripcion = d;
return self;}
@end

If you want to create a method constructor this must return “self”.



                                                                                  87
An Array

Open the Delegate.h Fil
O    th D l    t h File:


#import <UIKit/UIKit.h>
@interface TablaAppDelegate : NSObject <UIApplicationDelegate> {
   UIWindow *window;
   UINavigationController *navigationController;
   NSMutableArray *frutas;
}
@p p y (nonatomic, retain) IBOutlet UIWindow *window;
@property (           ,     )                            ;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) NSMutableArray *frutas;
@end




   Create array and add a property



                                                                                              88
An Array

Open the Delegate.m File:
#import "TablaAppDelegate.h“
#import "RootViewController.h“
#import "Fruta.h“

@implementation TablaAppDelegate
@synthesize window;
@   th i      i d
@synthesize navigationController;
@synthesize frutas;

-(void)applicationDidFinishLaunching:(UIApplication *)application {
    Fruta *manzana = [[Fruta alloc] initWithNombre:@"Manzana" descripcion:@"rojas y verdes son deliciosas!"];
    Fruta *naranja = [[Fruta alloc] initWithNombre:@"Naranja" descripcion:@"ideal para jugo! ];
            naranja                 initWithNombre:@ Naranja descripcion:@ ideal        jugo!"];
    Fruta *melon = [[Fruta alloc] initWithNombre:@"Melon" descripcion:@"una fruta poco recomendable!"];
    self.frutas =[[NSMutableArray alloc] initWithObjects:manzana, naranja, melon, nil];
    // Configure and show the window
    [window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}
-(void)applicationWillTerminate:(UIApplication *)application {
    // Save data if appropriate
}
-(void)dealloc {
    [navigationController release];
    [window release];
    [super dealloc];
}
@end

                                                                                                                       89
Principal ViewControler

Open the RootViewController.m File:

-(NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section {
   TablaAppDelegate *appDelegate = (TablaAppDelegate*)[[UIApplication sharedApplication] delegate];
   return appDelegate.frutas.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];   }
   TablaAppDelegate *appDelegate = (TablaAppDelegate )[[UIApplication sharedApplication] delegate];
                            appDelegate (TablaAppDelegate*)[[UIApplication
   Fruta *f = (Fruta*) [appDelegate.frutas objectAtIndex:indexPath.row];[cell setText:f.nombre];
   // [cell setText:@"Hola Mundo"];// Set up the cell return cell;}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic -- create and push a new view controllerTablaAppDelegate *appDelegate =
    (TablaAppDelegate )[[UIApplication
    (TablaAppDelegate*)[[UIApplication sharedApplication] delegate];
    Fruta *fruta = (Fruta*) [appDelegate.frutas objectAtIndex:indexPath.row];I
    f (self.vistaDosViewController == nil) {
                VistaDosViewController *vistaDos = [[VistaDosViewController alloc] initWithNibName:@"VistaDos"
    bundle:[NSBundle mainBundle]];
                self.vistaDosViewController = vistaDos;[vistaDos release];}
    [self.navigationController pushViewController:self vistaDosViewController
    [self navigationController pushViewController:self.vistaDosViewController animated:YES];
    self.vistaDosViewController.title = [fruta nombre];
    [self.vistaDosViewController.texto setText:[fruta descripcion]];
}
                                                                                                                              90
Time to Work 6
Working more

SQLite
SQLit



 iPphone suport the use of databases SQLite.
                         f           SQ

 One interesting work outside of this presentation is to convert this simple
 Array based table in a database application.
     y                             pp




                                                                               92
iPhone in action
               5
Using the Accelerometers

Provide input for the system and for your own custom applications

Measures changes in velocity along a single linear axis.

iPhone have three accelerometers in a 3D space, to detect motion in any direction.
                                          p                           y

By tracking which accelerometers are registering acceleration, and the extent of
that acceleration, you can detect the physical orientation of a device in 3D space.
You can then apply this orientation and its changes as inputs to your application.

The UIViewController class provides the infrastructure needed to rotate your
interface and adjust the position of views automatically in response to orientation
changes.

UIAccelerometer object in UIKit allow you t access to the raw accelerometer d t
UIA     l       t   bj t i          ll       to        t th             l     t data
directly. This object reports the current accelerometer values. You can also use the
data to detect the device's orientation or to detect other types of instantaneous
motion, such as the user shaking the device back and forth. You can then use this
information as input to a g
                  p        game or other application.
                                            pp


                                                                                       94
Using the Accelerometers
                                 Classes,
                                 Classes objects and methods

Every application h
E        li ti have an UIA l
                       UIAcelerometer object.
                                  t    bj t

To get an instance of this class, you use sharedAccelerometer method of
UIAccelerometer.

Whit this object you set (updateInterval) the reporting interval (minum 10
miliseg = 100 Hz) and a delegate to receive acceleration events
(UIAccelerometerDelegate).

Use accelerometer:didAccelerate : method to process accelerometer data.
  - (void)accelerometer:(UIAccelerometer *) accelerometer
  didAccelerate:(UIAcceleration *) acceleration.
  didA     l t (UIA      l ti          l ti
  UIAccelerationValue object could store the value of an axis.




                                                                             95
Using the Accelerometers

Isolating the Gravity Component From Acceleration Data (detect changes of orientation) using a low-
                                                                                                low
pass filter. accelX, accelY and accelZ are member variables that settle out quickly and respond slowly
to sudden changes in motion.



Isolating Instantaneous Motion From Acceleration Data (movement changes) using a high-pass filt
I l ti I t t            M ti F      A   l ti D t (            t h      ) i       hi h      filter



Current Device Orientation
  Use UIDevice l
  U UID i class methods:  th d
     beginGeneratingDeviceOrientationNotifications
     current orientation is stored at orientation properties
     UIDeviceOrientationChangeNotification posted whenever orientations change
     UIDeviceOrientation constants (landscape or portrait, face up or down)
                                                     portrait


Disabling orientation notifications
   Use the endGeneratingDeviceOrientationNotifications



                                                                                                     96
Example




      97
Getting the User's Current Location
                                          User s

                                                      go.
Devices that run iPhone OS are meant for users on the go

Therefore the software you write for these devices should also take this fact into account. And
because the Internet and web make it possible to do business anywhere, being able to tailor
information for the user's current location can make for a compelling user experience.

The Core Location framework monitors signals coming from cell phone towers and Wi-Fi
hotspots and uses them to triangulate the user's current position.

You can use this framework to grab an initial location fix only or you can be notified whenever
                                                           only,
the user's location changes. With this information, you can filter the information your application
provides or use it in other ways.

Retrive Current Location. Create an instance of CLLocationManager class.

To begin receiving notifications, assign a delegate and call the startUpdatingLocation method.

When new location information is available the manager notifies the delegate.



                                                                                                  98
Playing Audio and Video

iPhone OS supports audio features in your application through the Core Audio and
OpenAL frameworks, and provides video playback support using the Media Player
framework.

Core Audio provides an advanced interface for playing, recording, and manipulating
sound and f parsing streamed audio. Y can use i to play b k simple sound
     d d for        i           d di You               it   l back i l          d
effects or multichannel audio, mix sounds and position them in an audio field, and
even trigger the vibrate feature of an iPhone. If you are a game developer and
already have code that takes advantage of OpenAL, you can use your code in
iPhone OS to position and play back audio in your games.

The Media Player framework is what you use to play back full-screen video files.
This framework supports the playback of many standard movie file formats and
gives you control over the playback environment, including whether to display user
controls and how to configure the aspect ratio of video content
                                                        content.

Game developers might use this framework to play cut scenes or other prerendered
content, while media-based applications can also use this framework to play back
movie files.


                                                                                     99
Exercises and
  References
            6
iPhone Dev Center




http://developer.apple.com/iphone




                                          101

Más contenido relacionado

Destacado (20)

Week14 Presentation Group-C
Week14 Presentation Group-CWeek14 Presentation Group-C
Week14 Presentation Group-C
 
Phenomenal Oct 1, 2009
Phenomenal Oct 1, 2009Phenomenal Oct 1, 2009
Phenomenal Oct 1, 2009
 
Urban Cottage + IceMilk Aprons
Urban Cottage + IceMilk ApronsUrban Cottage + IceMilk Aprons
Urban Cottage + IceMilk Aprons
 
201001 Face-Based Emotion Recognition
201001 Face-Based Emotion Recognition201001 Face-Based Emotion Recognition
201001 Face-Based Emotion Recognition
 
Deutsche Telekom BarCamp 03, 25 June 2009
Deutsche Telekom BarCamp 03, 25 June 2009Deutsche Telekom BarCamp 03, 25 June 2009
Deutsche Telekom BarCamp 03, 25 June 2009
 
201506 CSE340 Lecture 16
201506 CSE340 Lecture 16201506 CSE340 Lecture 16
201506 CSE340 Lecture 16
 
Team Visit
Team VisitTeam Visit
Team Visit
 
201506 CSE340 Lecture 09
201506 CSE340 Lecture 09201506 CSE340 Lecture 09
201506 CSE340 Lecture 09
 
Jay Cross Vivo Versao Final Corrigida
Jay Cross Vivo Versao Final CorrigidaJay Cross Vivo Versao Final Corrigida
Jay Cross Vivo Versao Final Corrigida
 
201506 CSE340 Lecture 22
201506 CSE340 Lecture 22201506 CSE340 Lecture 22
201506 CSE340 Lecture 22
 
Thehub euromed
Thehub   euromedThehub   euromed
Thehub euromed
 
201506 CSE340 Lecture 07
201506 CSE340 Lecture 07201506 CSE340 Lecture 07
201506 CSE340 Lecture 07
 
Thehub Milan Startup Weekend
Thehub   Milan Startup WeekendThehub   Milan Startup Weekend
Thehub Milan Startup Weekend
 
Temlate Of Module
Temlate Of ModuleTemlate Of Module
Temlate Of Module
 
Phenomenal Oct 22, 2009
Phenomenal Oct 22, 2009Phenomenal Oct 22, 2009
Phenomenal Oct 22, 2009
 
Livre resumes 2007 angeio
Livre resumes 2007 angeioLivre resumes 2007 angeio
Livre resumes 2007 angeio
 
201106 WICSA
201106 WICSA201106 WICSA
201106 WICSA
 
Week10
Week10Week10
Week10
 
Phenomenal Oct 8, 2009
Phenomenal Oct 8, 2009Phenomenal Oct 8, 2009
Phenomenal Oct 8, 2009
 
Séptimo Básico.Pp
Séptimo Básico.PpSéptimo Básico.Pp
Séptimo Básico.Pp
 

Similar a 200810 - iPhone Tutorial

iPhone application development training day 1
iPhone application development training day 1iPhone application development training day 1
iPhone application development training day 1Shyamala Prayaga
 
iOS App Development Presented by Edifyself
iOS App Development Presented by EdifyselfiOS App Development Presented by Edifyself
iOS App Development Presented by EdifyselfEdifyself
 
Mobile application development
Mobile application developmentMobile application development
Mobile application developmentrohithn
 
Sumbited by heena saini
Sumbited by heena sainiSumbited by heena saini
Sumbited by heena sainiSaini Heena
 
How to Build Cross-Platform Mobile Apps Using Python
How to Build Cross-Platform Mobile Apps Using PythonHow to Build Cross-Platform Mobile Apps Using Python
How to Build Cross-Platform Mobile Apps Using PythonAndolasoft Inc
 
I phone first app ducat
I phone first app ducatI phone first app ducat
I phone first app ducatPragati Singh
 
IOS vs Android presentation by Saikrishna
IOS vs Android presentation by SaikrishnaIOS vs Android presentation by Saikrishna
IOS vs Android presentation by SaikrishnaSaikrishna Tanguturu
 
Best iOS Application Development Tools.pdf
Best iOS Application Development Tools.pdfBest iOS Application Development Tools.pdf
Best iOS Application Development Tools.pdfFuGenx Technologies
 
iPhone Developer_ankush
iPhone Developer_ankushiPhone Developer_ankush
iPhone Developer_ankushankush Ankush
 
Know about Android Operating System
Know about Android Operating SystemKnow about Android Operating System
Know about Android Operating SystemTrailukya Dutta
 
I phone programming project report
I phone programming project reportI phone programming project report
I phone programming project reportDhara Shah
 
LAP2 iOS and Android Development environment setup
LAP2 iOS and Android Development environment setupLAP2 iOS and Android Development environment setup
LAP2 iOS and Android Development environment setupUniversity of Catania
 
Creating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for AndroidCreating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for AndroidMotorola Mobility - MOTODEV
 
Java Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage EssayJava Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage EssayLiz Sims
 

Similar a 200810 - iPhone Tutorial (20)

201010 SPLASH Tutorial
201010 SPLASH Tutorial201010 SPLASH Tutorial
201010 SPLASH Tutorial
 
200910 - iPhone at OOPSLA
200910 - iPhone at OOPSLA200910 - iPhone at OOPSLA
200910 - iPhone at OOPSLA
 
iPhone application development training day 1
iPhone application development training day 1iPhone application development training day 1
iPhone application development training day 1
 
Ios - Introduction to swift programming
Ios - Introduction to swift programmingIos - Introduction to swift programming
Ios - Introduction to swift programming
 
iOS App Development Presented by Edifyself
iOS App Development Presented by EdifyselfiOS App Development Presented by Edifyself
iOS App Development Presented by Edifyself
 
Mobile application development
Mobile application developmentMobile application development
Mobile application development
 
Sumbited by heena saini
Sumbited by heena sainiSumbited by heena saini
Sumbited by heena saini
 
Internship presentation
Internship presentationInternship presentation
Internship presentation
 
How to Build Cross-Platform Mobile Apps Using Python
How to Build Cross-Platform Mobile Apps Using PythonHow to Build Cross-Platform Mobile Apps Using Python
How to Build Cross-Platform Mobile Apps Using Python
 
I phone first app ducat
I phone first app ducatI phone first app ducat
I phone first app ducat
 
IOS vs Android presentation by Saikrishna
IOS vs Android presentation by SaikrishnaIOS vs Android presentation by Saikrishna
IOS vs Android presentation by Saikrishna
 
MSR iOS Tranining
MSR iOS TraniningMSR iOS Tranining
MSR iOS Tranining
 
Best iOS Application Development Tools.pdf
Best iOS Application Development Tools.pdfBest iOS Application Development Tools.pdf
Best iOS Application Development Tools.pdf
 
iPhone Developer_ankush
iPhone Developer_ankushiPhone Developer_ankush
iPhone Developer_ankush
 
Know about Android Operating System
Know about Android Operating SystemKnow about Android Operating System
Know about Android Operating System
 
I phone programming project report
I phone programming project reportI phone programming project report
I phone programming project report
 
Android session 1
Android session 1Android session 1
Android session 1
 
LAP2 iOS and Android Development environment setup
LAP2 iOS and Android Development environment setupLAP2 iOS and Android Development environment setup
LAP2 iOS and Android Development environment setup
 
Creating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for AndroidCreating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for Android
 
Java Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage EssayJava Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage Essay
 

Más de Javier Gonzalez-Sanchez (20)

201804 SER332 Lecture 01
201804 SER332 Lecture 01201804 SER332 Lecture 01
201804 SER332 Lecture 01
 
201801 SER332 Lecture 03
201801 SER332 Lecture 03201801 SER332 Lecture 03
201801 SER332 Lecture 03
 
201801 SER332 Lecture 04
201801 SER332 Lecture 04201801 SER332 Lecture 04
201801 SER332 Lecture 04
 
201801 SER332 Lecture 02
201801 SER332 Lecture 02201801 SER332 Lecture 02
201801 SER332 Lecture 02
 
201801 CSE240 Lecture 26
201801 CSE240 Lecture 26201801 CSE240 Lecture 26
201801 CSE240 Lecture 26
 
201801 CSE240 Lecture 25
201801 CSE240 Lecture 25201801 CSE240 Lecture 25
201801 CSE240 Lecture 25
 
201801 CSE240 Lecture 24
201801 CSE240 Lecture 24201801 CSE240 Lecture 24
201801 CSE240 Lecture 24
 
201801 CSE240 Lecture 23
201801 CSE240 Lecture 23201801 CSE240 Lecture 23
201801 CSE240 Lecture 23
 
201801 CSE240 Lecture 22
201801 CSE240 Lecture 22201801 CSE240 Lecture 22
201801 CSE240 Lecture 22
 
201801 CSE240 Lecture 21
201801 CSE240 Lecture 21201801 CSE240 Lecture 21
201801 CSE240 Lecture 21
 
201801 CSE240 Lecture 20
201801 CSE240 Lecture 20201801 CSE240 Lecture 20
201801 CSE240 Lecture 20
 
201801 CSE240 Lecture 19
201801 CSE240 Lecture 19201801 CSE240 Lecture 19
201801 CSE240 Lecture 19
 
201801 CSE240 Lecture 18
201801 CSE240 Lecture 18201801 CSE240 Lecture 18
201801 CSE240 Lecture 18
 
201801 CSE240 Lecture 17
201801 CSE240 Lecture 17201801 CSE240 Lecture 17
201801 CSE240 Lecture 17
 
201801 CSE240 Lecture 16
201801 CSE240 Lecture 16201801 CSE240 Lecture 16
201801 CSE240 Lecture 16
 
201801 CSE240 Lecture 15
201801 CSE240 Lecture 15201801 CSE240 Lecture 15
201801 CSE240 Lecture 15
 
201801 CSE240 Lecture 14
201801 CSE240 Lecture 14201801 CSE240 Lecture 14
201801 CSE240 Lecture 14
 
201801 CSE240 Lecture 13
201801 CSE240 Lecture 13201801 CSE240 Lecture 13
201801 CSE240 Lecture 13
 
201801 CSE240 Lecture 12
201801 CSE240 Lecture 12201801 CSE240 Lecture 12
201801 CSE240 Lecture 12
 
201801 CSE240 Lecture 11
201801 CSE240 Lecture 11201801 CSE240 Lecture 11
201801 CSE240 Lecture 11
 

Último

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Último (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

200810 - iPhone Tutorial

  • 1. iPhone SDK a Ki k start iPh SDK: Kick t t Using Xcode 3.1 Developer Tools for iPhone OS Copyright is held by the author/owner(s). OOPSLA 2008, October 19–23, 2008, Nashville, Tennessee, USA. ACM 978-1-60558-220-7/08/10.
  • 2. Agenda 1. 1 Introduction Apple Developer Connection, iPhone platform; Tools for development;. 2. Objective-C language syntaxes; memory management; design patterns. 3. Creating a new project simple “Hello World” example; simple drawing; multi touch events; configuration list p p p g g 4. UI components windows, views and view controllers; using Interface Builder. 5. iPhone in action accelerometers; localization; media; openGL ES 6. Exercises and references 2
  • 3. Our Objective Using XCode 3.1 under Mac OS X 10.5 as our IDE, and Objective-C and iPhone API as our programming t l we will create iPh i tools ill t iPhone applications (f li ti (from b i t medium basic to di level) which finally can be loaded into an iPhone. We’ll start with the classical “Hello World” d W ld” and continue t d ti to develop applications using graphical user i t f l li ti i hi l interfaces, handling h dli multi-touch and detect motion, communication with web application, and different media. di 3
  • 4. Material Google Groups :: OOPSLA08 iphone G l G i h http://groups.google.com/group/oopsla08-iphone htt // l / / l 08 i h 4
  • 6. What is it ? iPhone is a pretty new device that involve several t h l i ( h iPh i tt d i th t i l l technologies (phone, video, id audio, images, and web among others). The best in 2007 year according to Times Magazine, Big winner in the 2008 British Technology Awards. Claimed the award for Gadget of the Year , won the Best Mobile Technology, Most Stylish Technology, and Technological Innovation of the Year awards. It has captive the interest of different types of users and created a new emerging market in various environments. Today thousands of programmers want to provide applications on the iPhone. It includes multi touch interface, sensors and a camera. 6
  • 9. iPhone SDK • Sample code Documentation • Reference libraries • Coding how-to • UIKit • Foundation Frameworks • Media • OpenGL / Quartz / Core Graphics p p • Xcode, Tools • Interface Builder • iPhone Simulator 9
  • 10. Install 1. Boot into a partition with the Mac OS X v10.5.3 installed. 2. Download the iPhone SDK software. 3. Double-click on iPhone SDK installer package. 4. Follow the instructions in the Installer. 5. To i t ll Xcode 3.1 in directory other th th d f lt /D 5 T install X d 3 1 i a di t th than the default /Developer, you must specify a l t if new <Xcode> directory name on the "Custom Install" pane; e.g. Xcode3.1. Select the folder icon under "Location" next to the "Developer Tools Essentials" package name. Select "Other..." at the top of the pop-up. Navigate to the location for the new <Xcode> folder Select "New Folder". folder. New Folder 10
  • 11. Install Enter folder E t a f ld name i th "N in the "New F ld " window; e.g. X d 3 1 S l t "C t " Folder" i d Xcode3.1. Select "Create". Finally, select "Choose" in the "Install Xcode Tools" pane. 6. If you need to install Mac OS X 10.3.9 Support or WebObjects, you must select "Customize", and check those packages on the "Custom Install" panel. 7. Authenticate as the administrative user. The first user you create when setting up Mac y g p OS X has administrator privileges by default. Developer applications such as Xcode, Instruments, and Interface Builder are installed in <Xcode>/Applications. 11
  • 12. Uninstall To uninstall Xcode developer tools on the boot volume along with the <Xcode> directory from a directory, Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=all If you just want to remove the underlying developer content on the boot volume, but leave the <Xcode> directory and supporting files untouched, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=systemsupport If you just want to just remove the UNIX development support on the boot volume, but leave the <Xcode> directory and supporting files untouched, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=unixdev Finally, to just uninstall the <Xcode> directory you can simply drag it to the trash, or from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=xcodedir <Xcode>/Library/uninstall devtools mode xcodedir 12
  • 13. Time to Work 1 Install iPhone SDK
  • 14. Tools for D T l f Development l t 1.2
  • 15. Tools We are going to be working with: Xcode Interface Builder iPhone Simulator And also need to consider Instruments 15
  • 16. Xcode The f Th focus of your development experiences is th X d application. X d i f d l t i i the Xcode li ti Xcode is an integrated development environment (IDE) that provides all of the tools you need to create and manage your iPhone projects and source files, build your code into an executable, and run and debug y , g your code either in iPhone simulator or on a device. To create a new iPhone application, you start by creating a new project in Xcode. A project manages all of the information associated with your application, including the source files, build settings, and rules needed to put all of the pieces t f th i together. The heart of every Xcode project is th project windows. th Th h t f X d j t i the j t i d 16
  • 17. Xcode 17
  • 18. Xcode editor, Xcode comes with an advanced text editor which supports features such as code completion, syntax coloring, code folding (to hide code blocks temporarily), and inline annotations for errors, warnings, and notes. The build system in Xcode provides both appropriate default settings and the ability to customize the environment. environment And if you need documentation the Research Assistant provides documentation, context-sensitive documentation while the Xcode documentation window lets you browse and search for information. When you build your application in Xcode, you have a choice of building it for iPhone simulator or for a device. The simulator provides a local environment for testing your applications to make sure they behave essentially the way you want. After you are satisfied with your application’s basic behavior, you can tell Xcode to build it and run it on an iPhone or iPod touch connected to your computer. Running on a device provides the ultimate test environment, and Xcode lets you attach the built-in debugger to the code running on the device. 18
  • 19. Xcode 19
  • 20. Interface Builder Interface Builder is the tool you use to assemble your application s user interface application’s visually. Using Interface Builder, you assemble your application’s window by dragging and dropping preconfigured components onto it. The components include standard system controls such as switches, text fields, and buttons, and also custom views to represent the views your application provides. After you’ve placed the th components on the window’s surface, you can position th t th i d ’ f iti them b d by dragging th i them around, configure their attributes using the inspector, and establish the relationships between those objects and your code. When your interface looks the way you want it, you save the contents to a nib file, which is a custom resource file format. The nib files you create in Interface Builder contain all the information that the UI Kit needs to recreate the same objects in your application at runtime. Loading a nib file creates runtime versions of all the objects stored in the file configuring them exactly file, as they were in Interface Builder. It also uses the connection information you specified to establish connections between the newly created objects and any existing objects in your application. These connections provide your code with pointers to the nib-file objects and also provide the information the objects themselves need t communicate user actions t your code. th l d to i t ti to d 20
  • 22. Instruments To ensure that you deliver the best user experience for your software the software, Instruments environment lets you analyze the performance of your iPhone applications while running in the simulator or on a device. Instruments gathers data from your running application and presents that data in a graphical display called the timeline. You can gather data about your application’s memory usage, disk activity, network activity, and graphics performance. Th ti li view can di l ti it t k ti it d hi f The timeline i display all of the different types of information side by side, letting you correlate the overall behavior of your application, not just the behavior in one specific area. To get even more detailed information, you can also view the detailed samples that Instruments g gathers. In addition to providing the timeline view, Instruments provides tools to help you analyze your application’s behavior over time For example the Instruments window application s time. example, lets you store data from multiple runs so that you can see whether your application’s behavior is actually improving or whether it still needs work. You can save the data from these runs in an Instruments document and open them at any time. 22
  • 25. Time to Work 2 XCode, XC d IB and Instruments example dI t t l
  • 26. iPhone Pl tf iPh Platform 1.3
  • 27. Introduction iPhone Pl tf iPh Platform comprises th operating system and t h l i th t you use i the ti t d technologies that to run applications natively on iPhone and iPod touch devices and iPhone OS. Although it shares a common heritage and many underlying technologies with Mac OS X, iPhone OS was designed to meet the needs of a mobile environment, where user’s needs are slightly different. Existing Mac OS X developers will find many familiar technologies, but they’ll also find technologies that are available only on iPhone OS such as the Multi-Touch OS, interface and accelerometer support. 27
  • 28. Key Concepts iPhone SDK supports the creation of graphically oriented applications that run graphically-oriented natively in iPhone OS. Take advantage of built-in hardware such as the accelerometers, camera, and graphics hardware hardware. All of the application’s data is displayed in a single window. This has lead to the creation of new views and controls that allow you to present your application’s data in an organized manner manner. The event-handling model in iPhone OS also represents a significant departure from traditional desktop applications. Instead of relying on the traditional mouse and keyboard events iPhone OS introduces the idea of touch events events, events. User experience. Memory management without a “garbage collector”. garbage collector 28
  • 29. Architecture Layers L Cocoa Touch Media Core Services Core OS 29
  • 30. Layers Core OS and Core Services l C dC S i layers contain th f d t i the fundamental i t f t l interfaces f for iPhone OS, including those used for accessing files, low-level data types, Bonjour services, network sockets, and so on. These interfaces are mostly C based and include technologies such as: g Core Foundation, CFNetwork, SQLite, Access to POSIX threads, UNIX sockets Among others. 30
  • 31. Layers Media layer contains th f d M di l t i the fundamental t h l i used t support 2D and 3D t l technologies d to t d drawing, audio, and video. This layer includes the C-based technologies: OpenGL ES, Quartz, and Core Audio, Core Animation, an advanced Objective-C based animation engine. 31
  • 32. Layers In the Cocoa Touch layer most of the technologies use Objective C The layer, Objective-C. frameworks at these layers provide the fundamental infrastructure used by your application. For example: the Foundation framework provides object-oriented support for collections, file management, network operations, and more. the UIKit framework provides the visual infrastructure for your application, including classes for windows, views, controls, and the controllers that manage those objects. Other frameworks at this level give you access to the user’s contact and photo information and to the accelerometers and other hardware features of the device. 32
  • 33. Starting Point The t ti Th starting point for any new project is the C i tf j t i th Cocoa T Touch l h layer, and th UIKit d the framework in particular. The higher-level frameworks make it easy to support standard system behaviors with the least amount of effort on your part. 33
  • 36. Objective-C Objective C The Objective-C language is a simple computer language designed to enable Objective C sophisticated object-oriented programming. Objective-C extends the standard ANSI C language by providing syntax for defining classes, methods, and properties, as well as other constructs that promote dynamic extension of classes. The class syntax and design are based mostly on Smalltalk, one of the first object-oriented programming l i languages. If you have programmed with object-oriented languages before, the following information should help you learn the basic syntax of Objective-C. Many of the traditional object-oriented concepts, such as encapsulation, inheritance, and object oriented polymorphism, are all present in Objective-C. There are a few important differences, but those differences are called out in this article and more detailed information is available if you need it. If you have never programmed using an object oriented language before you need object-oriented before, to have at least a basic understanding of the associated concepts before proceeding. The use of objects and object-oriented constructs is fundamental to the design of iPhone applications, and understanding how they interact is critical to creating your applications. 36
  • 37. Files Extension Source Type .h Header files. Header files contain class, type, function, and constant declarations. .m Source files. This is the typical extension used for source files and can contain both Objective-C and C code. .mm Source files. A source file with this extension can contain C++ code in addition to Objective-C and C code. This t Thi extension should be used only if you actually refer to C++ i h ld b d l t ll f t C classes or features from your Objective-C code. 37
  • 38. #import When Wh you want to include header fil i your source code, you can use th t t i l d h d files in d the standard #include compiler directive but Objective-C provides a better way. The #import directive is identical to #include, except that it makes sure that the same file is never included more than once. The Objective-C samples and documentation all prefer the use of #import, and your own code should too. 38
  • 39. Strings The NSSt i Th NSString class provides an object wrapper f strings th t has all of th l id bj t for t i that h ll f the advantages you would expect, including built-in memory management for storing arbitrary-length strings, support for Unicode, printf-style formatting utilities, and more. Because such strings are used commonly though, , g y g , Objective-C provides a shorthand notation for creating NSString objects from constant values. To use this shorthand, all you have to do is precede a normal, double-quoted string with the @ symbol, as shown in the following examples: NSString* myString = @”Hello Worldn"; NSString* anotherString = [ NSString stringWithFormat:@"%d %s", 1, @"String” ]; 39
  • 40. Note Cocoa F C Framework i d i d f k is derived from th N XTSTEP and OPENSTEP the NeXTSTEP d programming environments developed by NeXT in the late 1980s. Apple acquired NeXT in December 1996, and subsequently went to work on the Rhapsody operating system that was supposed to be the direct successor of OPENSTEP. The OPENSTEP base of libraries and binary support was termed Yellow Box. Rhapsody evolved into Mac OS X, and the Yellow Box became Cocoa. As a result, Cocoa classes begin with the acronym "NS" (standing either for the NeXT-Sun NeXT Sun creation of OPENSTEP or for the original proprietary term for the OPENSTEP, OPENSTEP framework, NeXTSTEP): NSString, NSArray, etc. 40
  • 41. Class The specification of a class in Objective C requires two distinct pieces: the Objective-C interface and the implementation. The interface portion contains the class declaration and defines the instance variables and methods associated with the class class. The implementation portion contains the actual code for the methods of the class. The class declaration always begins with the @interface compiler directive and ends with the @end directive. Following the class name (and separated from it by a colon) is the name of the parent class. The instance (or member) variables of the class are declared in a code block that is delineated by braces ({ and }) }). Following the instance variable block is the list of methods declared by the class. A semicolon character marks the end of each instance variable and method declaration. 41
  • 42. Class @interface MyClass : NSObject { int count; id data; NSString* name; } - (id)initWithString:(NSString *)aName; + (MyClass *)createMyClassWithString: (NSString *) aName @end 42
  • 43. Class @implementation MyClass - (id)initWithString:(NSString *) aName { if (self = [super init]) { count = 0; data = nil; name = [aName copy]; return self; } } + (MyClass *)createMyClassWithString: (NSString *) aName { return [[[self alloc] initWithString:aName] autorelease]; } @end 43
  • 44. Methods A class in Objective C can declare two types of methods: instance methods Objective-C and class methods. An instance method is a method whose execution is scoped to a particular instance of the class In other words before you call an instance method you class. words, method, must first create an instance of the class. Class methods, by comparison, do not require you to create an instance. The declaration of a method consists of the method type identifier, a return type, one or more signature keywords, and the parameter type and name information. The colon characters declare the presence of a parameter. If a method has no parameters, you omit the colon after the first (and only) signature keyword. In this example, the method takes two parameters. 44
  • 45. Methods -(void)insertObject:(id)anObject atIndex:(NSUInteger)index (void)insertObject:(id)anObject … [ y [myArray insertObject:anObj atIndex:0]; y j j ] Method Type Return Type Signature keywords Parameter Types Parameter Names 45
  • 46. Properties Properties are a convenience notation used to replace accessor method declarations. Properties do not create new instance variables in your class declaration. They are simply a shorthand for defining methods that access existing instance variables. Classes that expose instance variables can do so using the property notation instead of using getter and setter syntax. Classes can also use properties to expose “virtual” instance variables—that is, pieces of data that are computed dynamically and not actually stored in instance variables. variables Practically speaking, properties reduce the amount of redundant code you have to write. Because most accessor methods are implemented in similar ways, properties eliminate the need to provide a distinct getter and setter method for each instance variable exposed in the class. Instead, you specify the behavior you want using the property declaration and then synthesize actual getter and setter methods based on that declaration at compile time. 46
  • 47. Propierties @property BOOL flag; @property (copy) NSString* nameObject; //Copy the object during assignment. @property ( p p y (readonly) UIView* rootView; y) // Create only a g y getter method. … myObject.flag = YES; CGRect viewFrame = myObject.rootView.frame; 47
  • 48. Protocols and Delegates A protocol declares methods that can be implemented by any class Protocols are not classes class. themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol. In iPhone OS protocols are used frequently to implement delegate objects A delegate object is OS, objects. an object that acts on behalf of, or in coordination with, another object. By example, the UIApplication class implements the required behavior of an application. Instead of forcing you to subclass UIApplication to receive simple notifications about the current state of the application, the UIApplication class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate protocol can receive those notifications and provide an appropriate response. The dec a a o o a p o oco looks s e declaration of protocol oo s similar to that o a c ass interface, with the e cep o s that a o a of class e ace, e exceptions a protocols do not have a parent class and they do not define instance variables. In the case of many delegate protocols, adopting a protocol is simply a matter of implementing the methods defined by that protocol. There are some protocols that require you to state explicitly that y support the p p y you pp protocol, and p , protocols can specify both required and optional p y q p methods. 48
  • 49. Time to Work 4 A classical Fraction class
  • 50. Fraction.h Fraction h <Foundation/NSObject.h> #import <Foundation/NSObject h> @interface Fraction: NSObject { int numerator; int denominator; } -(void) print; -(void) setNumerator: (int) d; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator; @end 50
  • 51. Fraction.m Fraction m "Fraction.h" #import "Fraction h" #import <stdio.h> @implementation Fraction -(void) print { printf( "%i/%i", numerator, denominator ); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(int) denominator { return denominator; } -(int) numerator { return numerator; } @end 51
  • 52. main.m main m p #import <stdio.h> #import "Fraction.h" int main( int argc, const char *argv[] ) { Fraction *frac = [[Fraction alloc] init]; [[ ] ] [frac setNumerator: 1]; [frac setDenominator: 3]; printf( "The fraction is: " ); [frac print]; printf( "n" ); [f l ] [frac release]; return 0; } 52
  • 53. Creating C ti an A li ti Application 3.1
  • 54. Introduction At a high l hi h level, th process f creating an iPh l the for ti iPhone application i similar t th t li ti is i il to that for creating a Mac OS X application. Both use the same tools and many of the same basic libraries. Despite the similarities, there are also significant differences. An iPhone is not a desktop computer; it has a different purpose and requires a very different design approach. That approach needs to take advantage of the strengths of iPhone OS and forego features that might be irrelevant or impractical in a mobile environment. The smaller size of the iPhone and iPod touch screens also means that your application's user interface should be well organized and always focused on the information the user needs most. 54
  • 57. Steps Initializing the I iti li i th application li ti Displaying a window Drawing custom content Handling touch events 57
  • 58. Project Window Based Window-Based 1. Foundation 2. CoreGraphics 3. 3 UIKit 58
  • 59. main.m main m int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } 59
  • 60. Application Delegate One f th O of the most important architectural d t il of your project i d fi i th ti t t hit t l details f j t is defining the application delegate object, which is instantiated from a class you provide in your project. The application delegate class declares its interface in a *.h file and defines its implementation in a *.m file. Delegate is responsible of creating the window and views of the apps: using interface Builder or programatically. 60
  • 61. Application Delegate #import <UIKit/UIKit.h> @class MiVista; @interface HolaMundoAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; MiVista *vista; } @property (nonatomic, retain) UIWindow *window; @property (nonatomic, retain) MiVista *vista; @end 61
  • 62. Application Delegate HOLAMUNDOAPPDELEGATE.H #IMPORT "HOLAMUNDOAPPDELEGATE H” #IMPORT "MIVISTA.H” @IMPLEMENTATION HOLAMUNDOAPPDELEGATE @SYNTHESIZE WINDOW; @SYNTHESIZE VISTA VISTA; - (VOID)APPLICATIONDIDFINISHLAUNCHING :(UIAPPLICATION *)APPLICATION { SELF.WINDOW = [[[UIWINDOW ALLOC] INITWITHFRAME:[[UISCREEN MAINSCREEN] BOUNDS]] AUTORELEASE]; SELF.VISTA = [[[MIVISTA ALLOC] INITWITHFRAME:[[UISCREEN MAINSCREEN] APPLICATIONFRAME]] AUTORELEASE]; [WINDOW ADDSUBVIEW:VISTA]; [WINDOW MAKEKEYANDVISIBLE]; } - (VOID)DEALLOC { [VISTA RELEASE]; [WINDOW RELEASE]; [SUPER DEALLOC]; } @END 62
  • 63. Create a view (programatically) import <UIKit/UIKit.h> i # i / i h @interface MiVista : UIView { UILabel *miTexto; } @property (nonatomic, retain) UILabel *miTexto; @end 63
  • 64. Create a view (programatically) MiVista.h ##import "MiVista h” @implementation MiVista(id)initWithFrame:(CGRect)rectangulo { -(id)initWithFrame:(CGRect)rectangulo { [super initWithFrame:rectangulo]; self.backgroundColor =[UIColor whiteColor]; lf b k dC l [UIC l hit C l ] CGRect contenidoRectangulo = self.frame; CGFloat margenIzquierdo = 90.0; CGFloat anchoTextField = contenidoRectangulo.size.width * 0.72; CGFloat posicionTextField = (contenidoRectangulo.size.width - anchoTextField)/2.0; CGRect etiqueta = CGRectMake(posicionTextField,margenIzquierdo,anchoTextField,FONT_SIZE* HEIGHT_MULTIPLIER); UILabel *miTexto = [[UILabel alloc] initWithFrame:etiqueta]; miTexto.text = @"Hola Mundo"; miTexto.font = [UIFont systemFontOfSize:FONT_SIZE]; miTexto.textColor = [UIColor redColor]; miTexto.textAlignment = UITextAlignmentCenter; [self addSubview:miTexto]; [miTexto release]; return self;} } -(void)dealloc { [super dealloc]; } @end 64
  • 65. Touch E T h Events t 3.2
  • 66. Handling Touch Events UIView are part of UIR All UIVi t f UIResponder and can i l d d implement E t Event “li t t “listener” ” - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; )touches )event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; 66
  • 68. Plist file Pli t fil 3.3
  • 69. plist file <?xml version="1.0" encoding="UTF-8"?> l i "1 0" di " 8" <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> y y <key>CFBundleIconFile</key> <string>Icon.png</string> <key>CFBundleIdentifier</key> <string>com.yourcompany.${PRODUCT_NAME:identifier}</string> 69
  • 70. plist file <key>CFBundleInfoDictionaryVersion</key> k dl f i i i /k <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.0</string> <key>UIStatusBarHidden</key> <true/> <key>NSMainNibFile</key> <string>MainWindow</string> </dict> </plist> 70
  • 73. Interface Builder File’s Owner, it i a proxy object. It i a Fil ’ O is bj t is placeholder for the object responsible of manage the content. The library 73
  • 74. View-Based View Based Project Create C t a view-based project i b d j t ViewController f C files are created automatically (h, m y xib) Open ViewController.xib: add text field, a label, and a button. Add a UIImage if you want, to complete the GUI. 74
  • 75. Connecting the UI with the code STEP 1: open ViewController h: ViewController.h: #import <UIKit/UIKit.h> @interface IBViewController : UIViewController { IBOutlet UITextField *txtName; IBOutlet UILabel *lbHello; } @property (nonatomic, retain) IBOutlet UITextField *txtName; @property (nonatomic, retain) IBOutlet UILabel *lbHello; - (IBAction) updateText:(id) sender; @end 75
  • 76. IBOutlet and IBAction IBOutlet is a null-defined macro, which the C preprocessor An outlet is an instance variable that identifies an object IBAction, like IBOutlet, is a null defined macro, which the C preprocessor removes at compile time 76
  • 77. Connecting the UI with the code STEP 2: open ViewController.xib: 2 Vi C t ll ib Click in the view (outside button, label and so) : connections inspector : new reference outlet : and connect to file’s owner proxy object. Click in the textfield : connections inspector : new reference outlet : and connect to file’s owner proxy object. Click in the label : connections inspector : new reference outlet : and connect to file’s owner proxy object. Click in the label : connections inspector : Touch up inside: and connect to file’s owner proxy object. 77
  • 78. Connecting the UI with the code STEP 3: open ViewController.m: 3 Vi C t ll #import "IBViewController.h” @implementation IBViewController@synthesize txtName, lbHello; -(IBAction) updateText:(id) sender {NSString *text; if ([txtName.text length] == 0) { text = @"escibe tu nombre"; } else { text = [[NSString alloc] initWithFormat:@"Hola %@!", txtName.text]; } lbHello.text = text;[text release]; } - (void)dealloc { [super dealloc]; } @end 78
  • 80. Navigation-Based Navigation Based Project Create C t a navigation-based project i ti b d j t ViewController f C files are created and include a UITable component automatically (h, m y xib) Execute the code 80
  • 81. Updating UITable data At RootViewController.m R tVi C t ll 81
  • 82. UITable and more views together One O more View Vi Double click RootViewController.xib to open Interface Builder Click un File New : and select View C Add a Label or TextView to the View Save it inside the project directory. Close Interface Builder and drag the new XIB file to Resources Folder. 82
  • 83. UITable and more views together One more ViewController File : New : and select UIViewController subclass. You need a new m and h file. In the h file add a new outlet for the textview: #import <UIKit/UIKit.h> @interface VistaDosViewController : UIViewController { IBOutlet UITextView* texto; } @property (nonatomic, retain) IBOutlet UITextView *texto; @ i i i @end Open IB, select TextView : conections inspector : new outlet, and link with File’s owner (and select the corresponding ViewController) 83
  • 84. UITable and more views together One O more ViewController ( m fil ) Vi C t ll file) 84
  • 85. Associate view and view controller Double li k in the file VistaDos.xib D bl click i th fil Vi t D ib Click File’s Owner, then click tools -> identity inspector Select VistaDosViewControler in the dropdown class S C Click in any place of the view to select it, next tools – connections inspector, new reference outlet, and drag to file owner. g 85
  • 87. Simple Object Create C t a new Fil of NSObj t subclass t File f NSObject b l type. #import <UIKit/UIKit.h> @interface Fruta : NSObject { NSString *nombre;NSString *descripcion; } @property(nonatomic, copy) NSString *nombre; @property(nonatomic, copy) NSString *descripcion; -(id) initWithNombre:(NSString*)n descripcion:(NSString *) d; @end #import "Fruta.h“ @implementation Fruta { @synthesize nombre, descripcion; -(id) initWithNombre:(NSString*)n descripcion: (NSString )d {self nombre (NSString*)d {self.nombre = n; self.descripcion = d; return self;} @end If you want to create a method constructor this must return “self”. 87
  • 88. An Array Open the Delegate.h Fil O th D l t h File: #import <UIKit/UIKit.h> @interface TablaAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UINavigationController *navigationController; NSMutableArray *frutas; } @p p y (nonatomic, retain) IBOutlet UIWindow *window; @property ( , ) ; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController; @property (nonatomic, retain) NSMutableArray *frutas; @end Create array and add a property 88
  • 89. An Array Open the Delegate.m File: #import "TablaAppDelegate.h“ #import "RootViewController.h“ #import "Fruta.h“ @implementation TablaAppDelegate @synthesize window; @ th i i d @synthesize navigationController; @synthesize frutas; -(void)applicationDidFinishLaunching:(UIApplication *)application { Fruta *manzana = [[Fruta alloc] initWithNombre:@"Manzana" descripcion:@"rojas y verdes son deliciosas!"]; Fruta *naranja = [[Fruta alloc] initWithNombre:@"Naranja" descripcion:@"ideal para jugo! ]; naranja initWithNombre:@ Naranja descripcion:@ ideal jugo!"]; Fruta *melon = [[Fruta alloc] initWithNombre:@"Melon" descripcion:@"una fruta poco recomendable!"]; self.frutas =[[NSMutableArray alloc] initWithObjects:manzana, naranja, melon, nil]; // Configure and show the window [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; } -(void)applicationWillTerminate:(UIApplication *)application { // Save data if appropriate } -(void)dealloc { [navigationController release]; [window release]; [super dealloc]; } @end 89
  • 90. Principal ViewControler Open the RootViewController.m File: -(NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section { TablaAppDelegate *appDelegate = (TablaAppDelegate*)[[UIApplication sharedApplication] delegate]; return appDelegate.frutas.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } TablaAppDelegate *appDelegate = (TablaAppDelegate )[[UIApplication sharedApplication] delegate]; appDelegate (TablaAppDelegate*)[[UIApplication Fruta *f = (Fruta*) [appDelegate.frutas objectAtIndex:indexPath.row];[cell setText:f.nombre]; // [cell setText:@"Hola Mundo"];// Set up the cell return cell;} -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic -- create and push a new view controllerTablaAppDelegate *appDelegate = (TablaAppDelegate )[[UIApplication (TablaAppDelegate*)[[UIApplication sharedApplication] delegate]; Fruta *fruta = (Fruta*) [appDelegate.frutas objectAtIndex:indexPath.row];I f (self.vistaDosViewController == nil) { VistaDosViewController *vistaDos = [[VistaDosViewController alloc] initWithNibName:@"VistaDos" bundle:[NSBundle mainBundle]]; self.vistaDosViewController = vistaDos;[vistaDos release];} [self.navigationController pushViewController:self vistaDosViewController [self navigationController pushViewController:self.vistaDosViewController animated:YES]; self.vistaDosViewController.title = [fruta nombre]; [self.vistaDosViewController.texto setText:[fruta descripcion]]; } 90
  • 92. Working more SQLite SQLit iPphone suport the use of databases SQLite. f SQ One interesting work outside of this presentation is to convert this simple Array based table in a database application. y pp 92
  • 94. Using the Accelerometers Provide input for the system and for your own custom applications Measures changes in velocity along a single linear axis. iPhone have three accelerometers in a 3D space, to detect motion in any direction. p y By tracking which accelerometers are registering acceleration, and the extent of that acceleration, you can detect the physical orientation of a device in 3D space. You can then apply this orientation and its changes as inputs to your application. The UIViewController class provides the infrastructure needed to rotate your interface and adjust the position of views automatically in response to orientation changes. UIAccelerometer object in UIKit allow you t access to the raw accelerometer d t UIA l t bj t i ll to t th l t data directly. This object reports the current accelerometer values. You can also use the data to detect the device's orientation or to detect other types of instantaneous motion, such as the user shaking the device back and forth. You can then use this information as input to a g p game or other application. pp 94
  • 95. Using the Accelerometers Classes, Classes objects and methods Every application h E li ti have an UIA l UIAcelerometer object. t bj t To get an instance of this class, you use sharedAccelerometer method of UIAccelerometer. Whit this object you set (updateInterval) the reporting interval (minum 10 miliseg = 100 Hz) and a delegate to receive acceleration events (UIAccelerometerDelegate). Use accelerometer:didAccelerate : method to process accelerometer data. - (void)accelerometer:(UIAccelerometer *) accelerometer didAccelerate:(UIAcceleration *) acceleration. didA l t (UIA l ti l ti UIAccelerationValue object could store the value of an axis. 95
  • 96. Using the Accelerometers Isolating the Gravity Component From Acceleration Data (detect changes of orientation) using a low- low pass filter. accelX, accelY and accelZ are member variables that settle out quickly and respond slowly to sudden changes in motion. Isolating Instantaneous Motion From Acceleration Data (movement changes) using a high-pass filt I l ti I t t M ti F A l ti D t ( t h ) i hi h filter Current Device Orientation Use UIDevice l U UID i class methods: th d beginGeneratingDeviceOrientationNotifications current orientation is stored at orientation properties UIDeviceOrientationChangeNotification posted whenever orientations change UIDeviceOrientation constants (landscape or portrait, face up or down) portrait Disabling orientation notifications Use the endGeneratingDeviceOrientationNotifications 96
  • 97. Example 97
  • 98. Getting the User's Current Location User s go. Devices that run iPhone OS are meant for users on the go Therefore the software you write for these devices should also take this fact into account. And because the Internet and web make it possible to do business anywhere, being able to tailor information for the user's current location can make for a compelling user experience. The Core Location framework monitors signals coming from cell phone towers and Wi-Fi hotspots and uses them to triangulate the user's current position. You can use this framework to grab an initial location fix only or you can be notified whenever only, the user's location changes. With this information, you can filter the information your application provides or use it in other ways. Retrive Current Location. Create an instance of CLLocationManager class. To begin receiving notifications, assign a delegate and call the startUpdatingLocation method. When new location information is available the manager notifies the delegate. 98
  • 99. Playing Audio and Video iPhone OS supports audio features in your application through the Core Audio and OpenAL frameworks, and provides video playback support using the Media Player framework. Core Audio provides an advanced interface for playing, recording, and manipulating sound and f parsing streamed audio. Y can use i to play b k simple sound d d for i d di You it l back i l d effects or multichannel audio, mix sounds and position them in an audio field, and even trigger the vibrate feature of an iPhone. If you are a game developer and already have code that takes advantage of OpenAL, you can use your code in iPhone OS to position and play back audio in your games. The Media Player framework is what you use to play back full-screen video files. This framework supports the playback of many standard movie file formats and gives you control over the playback environment, including whether to display user controls and how to configure the aspect ratio of video content content. Game developers might use this framework to play cut scenes or other prerendered content, while media-based applications can also use this framework to play back movie files. 99
  • 100. Exercises and References 6