SlideShare a Scribd company logo
How to code for accelerometer
          and Core Location?
                    Desert Code Camp
                 Phoenix, Arizona 2010
Design Pattern
             1.
Model(delegate) + Controller + View




                         View                            Singleton
                                Include
                                XIB files




            Model                           Controller

Delegates




                                                                     3
Objective-C
          2.
Objective-C

  Is a simple computer language designed to enable sophisticated OO programming.


  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.



  Based mostly on Smalltalk (class syntax and design), one of the first object-oriented
  programming languages.



  Includes the traditional object-oriented concepts, such as encapsulation,
  inheritance, and polymorphism.



                                                                                           5
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 extension should be used only if you actually refer to C+
                 + classes or features from your Objective-C code.




                                                                                  6
#import

  To include header files in your source code, you can use the standard #include, but….
  Objective-C provides a better way #import. it makes sure that the same file is never
  included more than once.


 	
  #import	
  “MyAppDelegate.h”	
  
 	
  #import	
  “MyViewController.h”	
  

 	
  #import	
  <UIKit/UIKit.h>	
  




                                                                                           7
Class

  The specification of a class in Objective-C requires two distinct pieces: the
  interface (.h files) and the implementation (.m files).

  The interface portion contains the class declaration and defines the instance
  variables and methods associated with the class.
     @interface	
  
 	
  …	
  
 	
  @end	
  



  The implementation portion contains the actual code for the methods of the
  class.
 	
  @implementation	
  
 	
  …	
  
 	
  @end	
  



                                                                                   8
Class
                                             Class name

@interface	
  MyClass	
  :	
  NSObject	
                Parent class
{	
  
           	
  int	
  count;	
  
           	
  id	
  data;	
                                        Instance variables
           	
  NSString*	
  name;	
  
}	
  

-­‐	
  (id)initWithString:(NSString	
  *)aName;	
  
                                                                                methods
+	
  (MyClass	
  *)createMyClassWithString:	
  (NSString	
  *)	
  aName;	
  

@end	
  




                                                                                         9
Class
                                                                    Class name

@implementation	
  MyClass	
  

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

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

@end	
  


                                                                                                 10
Methods

  A class in Objective-C can declare two types of methods:
  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 must first create an
  instance of the class.

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



 Method type identifier               One or more signature keywords


 	
  -­‐(void)insertObject:(id)anObject	
  atIndex:(NSUInteger)index;	
  




           Return type                          Parameters with (type) and name
                                                                                           11
Methods

So	
  the	
  declaration	
  of	
  the	
  method	
  insertObject	
  would	
  be:	
  

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



     Method type identifier, is (-) to instance methods, (+) to class methods.




And	
  the	
  line	
  to	
  call	
  the	
  method	
  would	
  be:	
  

[myArray	
  insertObject:anObj	
  atIndex:0];	
  



                                                                                            12
Properties

  They are simply a shorthand for defining methods (getters and setters) that
  access existing instance variables.



  Properties do not create new instance variables in your class declaration.


  Reduce the amount of redundant code you have to write. Because most
  accessor methods are implemented in similar ways



  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.

                                                                                 13
Properties

In the interface we have:
{	
  
BOOL	
  flag;	
  
NSString*	
  myObject;	
  
UIView*	
  rootView;	
  
}	
  

@property	
  BOOL	
  flag;	
  
@property	
  (copy)	
  NSString*	
  myObject;	
  //	
  Copy	
  the	
  object	
  during	
  assignement	
  
@property	
  (readonly)	
  UIView*	
  rootView;	
  //	
  Create	
  only	
  a	
  getter	
  method.	
  
  	
         	
              	
          	
               	
  	
  

…	
  

And in the implementation side we have:
@syntetize	
  flag;	
  
@syntetize	
  myObject;	
  
@syntetize	
  rootView;	
  

…	
  
myObject.flag	
  =	
  YES;	
  
CGRect	
  	
  	
  viewFrame	
  =	
  myObject.rootView.frame;	
  



                                                                                                                     14
Properties

Writability

  Readwrite. You can read/write it. This is the default value.
  Readonly. You can only read it.

Setter semantics (mutually exclusive)

  Assign. Specifies that the setter uses simple assignment. This is the default value.
  Retain. Specifies that a pointer should be retained.
  Copy. Specifies that a copy of the object should be used for assignment.

Atomicity (multithreading)

  Nonatomic. Specifies that accessor methods are not atomic.
  The default value is atomic but there is no need to specify it.


                                                                                          15
Protocols and Delegates

  Protocols are not classes themselves. They simply define an interface that other objects
  are responsible for implementing


  A protocol declares methods that can be implemented by any class.


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


  The declaration of a protocol looks similar to that of a class interface, with the exceptions
  that 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 you support the protocol, and protocols can specify
  both required and optional methods.
                                                                                               16
Example: Fraction

Fraction.h	
                                               Fraction.m	
  

#import	
  <Foundation/NSObject.h>	
  	
                   #import	
  "Fraction.h"	
  	
  
                                                           #import	
  <stdio.h>	
  	
  	
  
@interface	
  Fraction:	
  NSObject	
  {	
  	
  	
  	
  
	
  	
  	
  int	
  numerator;	
  	
  	
  	
  	
  	
  
                                                           @implementation	
  Fraction	
  
	
  	
  	
  int	
  denominator;	
  	
  
	
  }	
  	
  	
  
                                                           @synthesize	
  numerator;	
  
//Properties	
  instead	
  of	
  getters	
  and	
  	
      @synthesize	
  denominator;	
  
//setters	
  
@property	
  (nonatomic)	
  int	
  numerator;	
            //	
  Output	
  Print	
  
@property	
  (nonatomic)	
  int	
  denominator;	
          -­‐(void)	
  print	
  {	
  	
  	
  	
  	
  	
  
                                                           printf("%i/%i",	
  numerator,denominator);	
  	
  
                                                           }	
  	
  	
  
//Output	
  print	
                                        @end	
  	
  
-­‐(void)	
  print;	
  	
  

@end	
  	
  


                                                                                                                17
Example: Fraction

main.m


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

int main( int argc, const char *argv[] ) {
    Fraction *frac = [[Fraction alloc] init];
    frac.numerator = 1;
    frac.denominator=3;

    printf( "The fraction is: " );
    [frac print];
    printf( "n" );

    [frac release]
    return 0;
}




                                                                18
Strings

  The NSString class provides an object wrapper.
  Supports storing arbitrary-length strings, support for Unicode, printf-style
  formatting utilities, and more.

  Shorthand notation for creating NSString objects from constant values.
  Precede a normal, double-quoted string with the @ symbol.


  NSString*	
  	
  myString	
  =	
  @”Hello	
  Worldn";	
  


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




                                                                                                         19
Let us code:
Autorotate and Accelerometer
                           3
Accelerometer


Measure of Gravity acceleration:

0g

1g

2.3g




                              21
Reading the Accelerometer

  UIAccelerometer object in UIKit allow you to access to the raw accelerometer
     data directly. This object reports the current accelerometer values.

  To get an instance of this class, call the sharedAccelerometer method of
     UIAccelerometer class.

    The updateInterval property define the reporting interval in seconds.


-­‐(void)viewDidLoad	
  {	
  
	
  	
  UIAccelerometer	
  *accelerometer	
  =	
  [UIAccelerometer	
  sharedAccelerometer];	
  
	
  	
  accelerometer.delegate	
  =	
  self;	
  
	
  	
  accelerometer.updateInterval	
  =	
  	
  1.0/60;	
  
	
  	
  [super	
  viewDidLoad];	
  
}	
  



                                                                                              22
Reading the Accelerometer

  A delegate (UIAccelerometerDelegate) will receive acceleration events.


@interface	
  FooViewController:	
  UIViewController	
  <UIAccelerometerDelegate>	
  



  Use   accelerometer:didAccelerate: method to process accelerometer data.


-­‐(void)accelerometer:(UIAccelerometer	
  *)accelerometer	
  didAccelerate:
                	
  (UIAcceleration	
  *)acceleration	
  {	
  	
  	
  	
  	
  
	
  	
  NSString	
  *s	
  =	
  [[NSString	
  alloc]	
  initWithFormat:@"%f,	
  %f,	
  %f",	
   	
     	
  
                	
  acceleration.x,	
  acceleration.y,	
  acceleration.z];	
  
    	
  accLabel.text	
  =	
  s;	
  
	
  	
  [s	
  release];	
  
}
                                                                                                        23
AutoRotate

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


-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation interfaceOrientation {
   return YES;
   //return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


interfaceOrientation values:

  UIInterfaceOrientationPortrait
  UIInterfaceOrientationPortraitUpsideDown
  UIInterfaceOrientationLandscapeLeft
  UIInterfaceOrientationLandscapeRight

                                                                                             24
AutoRotate adjustments




                     25
Core Location
            4
Core Location


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.




                                                                               27
Getting the User's Current Location

  Create an instance of CLLocationManager class.
It	
  is	
  necessary	
  to	
  include	
  the	
  CoreLocation.framework	
  

#import	
  <CoreLocation/CoreLocation.h>	
  

@interface	
  FooViewController:	
  UIViewController<CLLocationManagerDelegate>	
  	
  



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


-­‐(void)viewDidLoad	
  {	
  
	
  	
  CLLocationManager	
  *locationManager=	
  [[CLLocationManager	
  alloc]	
  init];	
  
	
  	
  [locationManager	
  startUpdatingLocation];locationManager.delegate	
  =	
  self;	
  
	
  	
  locationManager.distanceFilter	
  =	
  kCLDistanceFilterNone;	
  	
  	
  	
  
	
  	
  locationManager.desiredAccuracy	
  =	
  kCLLocationAccuracyBest;	
  
}	
  

                                                                                                28
Using the Core Location

  We need implement this:

-­‐  (void)locationManager:(CLLocationManager	
  *)manager	
  didUpdateToLocation:
  (CLLocation	
  *)newLocation	
  fromLocation:(CLLocation	
  *)oldLocation	
  {	
  

	
  	
  NSString	
  *latitudeString	
  =	
  [[NSString	
  alloc]	
  initWithFormat:@"%g°",	
  
             	
         	
       	
            	
  newLocation.coordinate.latitude];	
  

	
  	
  latitudeLabel.text	
  =	
  latitudeString;	
  
	
  	
  [latitudeString	
  release];	
  
    	
  NSString	
  *longitudeString	
  =	
  [[NSString	
  alloc]	
  initWithFormat:@"%g°",	
  	
  
    	
       	
         	
  newLocation.coordinate.longitude];	
  

	
  	
  longitudeLabel.text	
  =	
  longitudeString;	
  
	
  	
  [longitudeString	
  release];	
  
}	
  


                                                                                                      29
Exercises and
  References
            5
iPhone Dev Center




http://developer.apple.com/iphone




                                           31

More Related Content

PPTX
Basics of Object Oriented Programming in Python
PPT
Objective-C for iOS Application Development
PPTX
Objective c slide I
PDF
Introduction to objective c
PPTX
Object oriented programming in python
PPTX
iOS Basic
PPTX
Introduction to Objective - C
PPT
core java
Basics of Object Oriented Programming in Python
Objective-C for iOS Application Development
Objective c slide I
Introduction to objective c
Object oriented programming in python
iOS Basic
Introduction to Objective - C
core java

What's hot (20)

PPTX
Object oriented programming with python
PDF
Object oriented approach in python programming
PDF
Aspect oriented programming_with_spring
PPS
Java session05
PDF
iOS 101 - Xcode, Objective-C, iOS APIs
PPTX
Python – Object Oriented Programming
PPT
Objective c
PDF
iPhone Seminar Part 2
PDF
Getting started with the JNI
PPTX
Object Oriented Programming in Python
PPTX
CLASS OBJECT AND INHERITANCE IN PYTHON
PPTX
Python OOPs
PDF
Introduction to Objective - C
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPTX
Python oop third class
PPTX
Java Programming For Android
PPTX
OOP C++
PPTX
Advance OOP concepts in Python
PDF
Java ppt Gandhi Ravi ([email protected])
PPTX
About Python
Object oriented programming with python
Object oriented approach in python programming
Aspect oriented programming_with_spring
Java session05
iOS 101 - Xcode, Objective-C, iOS APIs
Python – Object Oriented Programming
Objective c
iPhone Seminar Part 2
Getting started with the JNI
Object Oriented Programming in Python
CLASS OBJECT AND INHERITANCE IN PYTHON
Python OOPs
Introduction to Objective - C
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Python oop third class
Java Programming For Android
OOP C++
Advance OOP concepts in Python
Java ppt Gandhi Ravi ([email protected])
About Python
Ad

Viewers also liked (20)

PPT
Barya Perception
PDF
201506 CSE340 Lecture 10
PDF
Thehub bocconi law
PDF
Dynamic Object Flow Analysis (PhD Defense)
PPT
The San Diego LGBT Community Center
PDF
Wolko1- Afiches de cine
PDF
Tracking Objects To Detect Feature Dependencies
PPT
Financial planning introduction fall 2010
PPT
簡介創用CC授權
KEY
Urban Cottage + IceMilk Aprons
PDF
Week5-Group-J
PDF
Amazon resource for bioinformatics
PDF
200905 - Sociable machines
PPT
漫谈php和java
PDF
Phenomenal Oct 8, 2009
PPT
Uip Romain
PDF
201101 mLearning
PDF
Valvuloplastie
PDF
Paul Harris Fellow Clubs En
PPT
New Venture Presentatie
Barya Perception
201506 CSE340 Lecture 10
Thehub bocconi law
Dynamic Object Flow Analysis (PhD Defense)
The San Diego LGBT Community Center
Wolko1- Afiches de cine
Tracking Objects To Detect Feature Dependencies
Financial planning introduction fall 2010
簡介創用CC授權
Urban Cottage + IceMilk Aprons
Week5-Group-J
Amazon resource for bioinformatics
200905 - Sociable machines
漫谈php和java
Phenomenal Oct 8, 2009
Uip Romain
201101 mLearning
Valvuloplastie
Paul Harris Fellow Clubs En
New Venture Presentatie
Ad

Similar to 201005 accelerometer and core Location (20)

PDF
Iphone course 1
PPT
iOS Application Development
PPTX
iOS Session-2
KEY
Fwt ios 5
PPTX
Presentation 3rd
PDF
iOS Programming Intro
PDF
Louis Loizides iOS Programming Introduction
PDF
Objective-C
KEY
iPhone Development Intro
PDF
Objective-C Is Not Java
PPTX
iOS development introduction
PDF
What Makes Objective C Dynamic?
PDF
Lecture 03
PDF
Никита Корчагин - Programming Apple iOS with Objective-C
PDF
Programming with Objective-C
PDF
Intro to iOS Development • Made by Many
KEY
Objective C 基本介紹
KEY
Parte II Objective C
PPTX
Presentation 1st
PDF
Bootstrapping iPhone Development
Iphone course 1
iOS Application Development
iOS Session-2
Fwt ios 5
Presentation 3rd
iOS Programming Intro
Louis Loizides iOS Programming Introduction
Objective-C
iPhone Development Intro
Objective-C Is Not Java
iOS development introduction
What Makes Objective C Dynamic?
Lecture 03
Никита Корчагин - Programming Apple iOS with Objective-C
Programming with Objective-C
Intro to iOS Development • Made by Many
Objective C 基本介紹
Parte II Objective C
Presentation 1st
Bootstrapping iPhone Development

More from Javier Gonzalez-Sanchez (20)

PDF
201804 SER332 Lecture 01
PDF
201801 SER332 Lecture 03
PDF
201801 SER332 Lecture 04
PDF
201801 SER332 Lecture 02
PDF
201801 CSE240 Lecture 26
PDF
201801 CSE240 Lecture 25
PDF
201801 CSE240 Lecture 24
PDF
201801 CSE240 Lecture 23
PDF
201801 CSE240 Lecture 22
PDF
201801 CSE240 Lecture 21
PDF
201801 CSE240 Lecture 20
PDF
201801 CSE240 Lecture 19
PDF
201801 CSE240 Lecture 18
PDF
201801 CSE240 Lecture 17
PDF
201801 CSE240 Lecture 16
PDF
201801 CSE240 Lecture 15
PDF
201801 CSE240 Lecture 14
PDF
201801 CSE240 Lecture 13
PDF
201801 CSE240 Lecture 12
PDF
201801 CSE240 Lecture 11
201804 SER332 Lecture 01
201801 SER332 Lecture 03
201801 SER332 Lecture 04
201801 SER332 Lecture 02
201801 CSE240 Lecture 26
201801 CSE240 Lecture 25
201801 CSE240 Lecture 24
201801 CSE240 Lecture 23
201801 CSE240 Lecture 22
201801 CSE240 Lecture 21
201801 CSE240 Lecture 20
201801 CSE240 Lecture 19
201801 CSE240 Lecture 18
201801 CSE240 Lecture 17
201801 CSE240 Lecture 16
201801 CSE240 Lecture 15
201801 CSE240 Lecture 14
201801 CSE240 Lecture 13
201801 CSE240 Lecture 12
201801 CSE240 Lecture 11

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPT
Teaching material agriculture food technology
PDF
Approach and Philosophy of On baking technology
PDF
cuic standard and advanced reporting.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Empathic Computing: Creating Shared Understanding
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
A Presentation on Artificial Intelligence
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Programs and apps: productivity, graphics, security and other tools
NewMind AI Weekly Chronicles - August'25-Week II
Diabetes mellitus diagnosis method based random forest with bat algorithm
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
cuic standard and advanced reporting.pdf
A comparative analysis of optical character recognition models for extracting...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Electronic commerce courselecture one. Pdf
Getting Started with Data Integration: FME Form 101
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation_ Review paper, used for researhc scholars
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Spectroscopy.pptx food analysis technology
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Empathic Computing: Creating Shared Understanding
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
A Presentation on Artificial Intelligence
MYSQL Presentation for SQL database connectivity
Programs and apps: productivity, graphics, security and other tools

201005 accelerometer and core Location

  • 1. How to code for accelerometer and Core Location? Desert Code Camp Phoenix, Arizona 2010
  • 3. Model(delegate) + Controller + View View Singleton Include XIB files Model Controller Delegates 3
  • 5. Objective-C   Is a simple computer language designed to enable sophisticated OO programming.   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.   Based mostly on Smalltalk (class syntax and design), one of the first object-oriented programming languages.   Includes the traditional object-oriented concepts, such as encapsulation, inheritance, and polymorphism. 5
  • 6. 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 extension should be used only if you actually refer to C+ + classes or features from your Objective-C code. 6
  • 7. #import   To include header files in your source code, you can use the standard #include, but….   Objective-C provides a better way #import. it makes sure that the same file is never included more than once.  #import  “MyAppDelegate.h”    #import  “MyViewController.h”    #import  <UIKit/UIKit.h>   7
  • 8. Class   The specification of a class in Objective-C requires two distinct pieces: the interface (.h files) and the implementation (.m files).   The interface portion contains the class declaration and defines the instance variables and methods associated with the class. @interface    …    @end     The implementation portion contains the actual code for the methods of the class.  @implementation    …    @end   8
  • 9. Class Class name @interface  MyClass  :  NSObject   Parent class {    int  count;    id  data;   Instance variables  NSString*  name;   }   -­‐  (id)initWithString:(NSString  *)aName;   methods +  (MyClass  *)createMyClassWithString:  (NSString  *)  aName;   @end   9
  • 10. Class Class name @implementation  MyClass   -­‐  (id)initWithString:(NSString  *)  aName   {          if  (self  =  [super  init])  {                  count  =  0;                  data  =  nil;   methods                name  =  [aName  copy];                  return  self;          }   }   +  (MyClass  *)createMyClassWithString:  (NSString  *)  aName   {          return  [[[self  alloc]  initWithString:aName]  autorelease];   }   @end   10
  • 11. Methods   A class in Objective-C can declare two types of methods:   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 must first create an instance of the class.   Class methods, by comparison, do not require you to create an instance. Method type identifier One or more signature keywords  -­‐(void)insertObject:(id)anObject  atIndex:(NSUInteger)index;   Return type Parameters with (type) and name 11
  • 12. Methods So  the  declaration  of  the  method  insertObject  would  be:   -­‐(void)insertObject:(id)anObject  atIndex:(NSUInteger)index   Method type identifier, is (-) to instance methods, (+) to class methods. And  the  line  to  call  the  method  would  be:   [myArray  insertObject:anObj  atIndex:0];   12
  • 13. Properties   They are simply a shorthand for defining methods (getters and setters) that access existing instance variables.   Properties do not create new instance variables in your class declaration.   Reduce the amount of redundant code you have to write. Because most accessor methods are implemented in similar ways   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. 13
  • 14. Properties In the interface we have: {   BOOL  flag;   NSString*  myObject;   UIView*  rootView;   }   @property  BOOL  flag;   @property  (copy)  NSString*  myObject;  //  Copy  the  object  during  assignement   @property  (readonly)  UIView*  rootView;  //  Create  only  a  getter  method.               …   And in the implementation side we have: @syntetize  flag;   @syntetize  myObject;   @syntetize  rootView;   …   myObject.flag  =  YES;   CGRect      viewFrame  =  myObject.rootView.frame;   14
  • 15. Properties Writability   Readwrite. You can read/write it. This is the default value.   Readonly. You can only read it. Setter semantics (mutually exclusive)   Assign. Specifies that the setter uses simple assignment. This is the default value.   Retain. Specifies that a pointer should be retained.   Copy. Specifies that a copy of the object should be used for assignment. Atomicity (multithreading)   Nonatomic. Specifies that accessor methods are not atomic.   The default value is atomic but there is no need to specify it. 15
  • 16. Protocols and Delegates   Protocols are not classes themselves. They simply define an interface that other objects are responsible for implementing   A protocol declares methods that can be implemented by any class.   In iPhone OS, protocols are used frequently to implement delegate objects. A delegate object is an object that acts on behalf of, or in coordination with, another object.   The declaration of a protocol looks similar to that of a class interface, with the exceptions that 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 you support the protocol, and protocols can specify both required and optional methods. 16
  • 17. Example: Fraction Fraction.h   Fraction.m   #import  <Foundation/NSObject.h>     #import  "Fraction.h"     #import  <stdio.h>       @interface  Fraction:  NSObject  {              int  numerator;             @implementation  Fraction        int  denominator;      }       @synthesize  numerator;   //Properties  instead  of  getters  and     @synthesize  denominator;   //setters   @property  (nonatomic)  int  numerator;   //  Output  Print   @property  (nonatomic)  int  denominator;   -­‐(void)  print  {             printf("%i/%i",  numerator,denominator);     }       //Output  print   @end     -­‐(void)  print;     @end     17
  • 18. Example: Fraction main.m #import <stdio.h> #import "Fraction.h" int main( int argc, const char *argv[] ) { Fraction *frac = [[Fraction alloc] init]; frac.numerator = 1; frac.denominator=3; printf( "The fraction is: " ); [frac print]; printf( "n" ); [frac release] return 0; } 18
  • 19. Strings   The NSString class provides an object wrapper.   Supports storing arbitrary-length strings, support for Unicode, printf-style formatting utilities, and more.   Shorthand notation for creating NSString objects from constant values. Precede a normal, double-quoted string with the @ symbol. NSString*    myString  =  @”Hello  Worldn";   NSString*    anotherString  =                  [NSString  stringWithFormat:@"%d  %s",  1,  @"String”];   19
  • 20. Let us code: Autorotate and Accelerometer 3
  • 21. Accelerometer Measure of Gravity acceleration: 0g 1g 2.3g 21
  • 22. Reading the Accelerometer   UIAccelerometer object in UIKit allow you to access to the raw accelerometer data directly. This object reports the current accelerometer values.   To get an instance of this class, call the sharedAccelerometer method of UIAccelerometer class.   The updateInterval property define the reporting interval in seconds. -­‐(void)viewDidLoad  {      UIAccelerometer  *accelerometer  =  [UIAccelerometer  sharedAccelerometer];      accelerometer.delegate  =  self;      accelerometer.updateInterval  =    1.0/60;      [super  viewDidLoad];   }   22
  • 23. Reading the Accelerometer   A delegate (UIAccelerometerDelegate) will receive acceleration events. @interface  FooViewController:  UIViewController  <UIAccelerometerDelegate>     Use accelerometer:didAccelerate: method to process accelerometer data. -­‐(void)accelerometer:(UIAccelerometer  *)accelerometer  didAccelerate:  (UIAcceleration  *)acceleration  {              NSString  *s  =  [[NSString  alloc]  initWithFormat:@"%f,  %f,  %f",        acceleration.x,  acceleration.y,  acceleration.z];    accLabel.text  =  s;      [s  release];   } 23
  • 24. AutoRotate The UIViewController class provides the infrastructure needed to rotate your interface and adjust the position of views automatically in response to orientation changes. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation interfaceOrientation { return YES; //return (interfaceOrientation == UIInterfaceOrientationPortrait); } interfaceOrientation values:   UIInterfaceOrientationPortrait   UIInterfaceOrientationPortraitUpsideDown   UIInterfaceOrientationLandscapeLeft   UIInterfaceOrientationLandscapeRight 24
  • 27. Core Location 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. 27
  • 28. Getting the User's Current Location   Create an instance of CLLocationManager class. It  is  necessary  to  include  the  CoreLocation.framework   #import  <CoreLocation/CoreLocation.h>   @interface  FooViewController:  UIViewController<CLLocationManagerDelegate>       To begin receiving notifications, assign a delegate and call the startUpdatingLocation method. -­‐(void)viewDidLoad  {      CLLocationManager  *locationManager=  [[CLLocationManager  alloc]  init];      [locationManager  startUpdatingLocation];locationManager.delegate  =  self;      locationManager.distanceFilter  =  kCLDistanceFilterNone;            locationManager.desiredAccuracy  =  kCLLocationAccuracyBest;   }   28
  • 29. Using the Core Location   We need implement this: -­‐  (void)locationManager:(CLLocationManager  *)manager  didUpdateToLocation: (CLLocation  *)newLocation  fromLocation:(CLLocation  *)oldLocation  {      NSString  *latitudeString  =  [[NSString  alloc]  initWithFormat:@"%g°",          newLocation.coordinate.latitude];      latitudeLabel.text  =  latitudeString;      [latitudeString  release];    NSString  *longitudeString  =  [[NSString  alloc]  initWithFormat:@"%g°",          newLocation.coordinate.longitude];      longitudeLabel.text  =  longitudeString;      [longitudeString  release];   }   29
  • 30. Exercises and References 5