IPhoneDev

From M-Gate Labs Wiki

Jump to: navigation, search

This page is still under development, I have been working with the iPhone SDK and finally go the Interface builder to work, more updates will follow.

--SlashAndBurn 19:16, 30 June 2008 (MST)

Contents

Objective C

File Types

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

Include

  • #include
    • Same as C, C++ #include statement
  • #import
    • Like #include, but will not reference the same file more then once

Strings

  • Shortcut
    • Append a @ to the front of a double quoted string
  NSString*  myString = @"My String\n";
  NSString*  anotherString = [NSString stringWithFormat:@"%d %s", 1, @"String"]; 
  // Create an Objective-C string from a C string
  NSString*  fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding];

Classes

interface

  @interface MyClass : NSObject
  {
     int  count;
     id   data;
     NSString* name;
  }
  - (id)initWithString:(NSString*)aName;
  + (MyClass*)createMyClassWithString:(NSString*)aName;
  @end

implementation

  @implementation MyClass
  - (id)initWithString:(NSString *) aName
  {
     if (self = [super init])
     {
        count count = 0;
        data = nil;
        name = [aName copy];
        return self;
      }
  }
  + (MyClass *)createMyClassWithString: (NSString *) aName
  {
      return [[[self alloc] initWithString:aName] autorelease];
  }
  @end

variables

strong typed

  MyClass* myObject1;
  • Object types should be declared as a pointer

weak typed

  id myObject2;
  • id type is a pointer type

methods

instance

  • Starts with a -
  • is a method whose execution is scoped to a particular instance of the class
  • before you call an instance method, you must first create an instance of the class

class

  • starts with a +
  • do not require you to create an instance
  • basically a static method

declaration

- (void)insertObject:(id)anObject asIndex:(NSUInteger)index
  • -
    • Method type indentifier
  • (void)
    • Return Type
  • insertObject
    • Method Signature
  • (id)
    • Parameter Type
  • anObject
    • Parameter Names
  • atIndex
    • Method Signature
  • (NSUInteger)
    • Parameter Type
  • index
    • Parameter Names

calling

  [myArray insertObject:anObj atIndex:0]
  • [
  • myArray
    • Referenced Object
  • insertObject
    • signature
  • anObj
    • value
  • atIndex
    • signature
  • 0
    • value
  • ]

Properties

  • Properties are a convenience notation used to replace accessor method declarations
  • shorthand for defining methods that access existing instance variables
  • reduce the amount of redundant code you have to write
  @property BOOL flag;
  @property (copy) NSString* nameObject;  // Copy the object during assignment.
  @property (readonly) UIView* rootView;  // Create only a getter method.
  • Another benefit of properties is that you can use dot syntax when accessing them in your code, as shown in the following example:
  myObject.flag = YES;
  //[myObject setFlag:YES];
  CGRect   viewFrame = myObject.rootView.frame;
  //CGRect   viewFrame = [[myObject rootView] frame];

Protocols & Delegates

protocols

  • protocol declares methods that can be implemented by any class
  • define an interface that other objects are responsible for implementing

delegates

  • a delegate object is an object that acts on behalf of, or in coordination with, another object

declaration

  @protocol MyProtocol
  - (void)myProtocolMethod;
  @end

Application

problems

  • iPhone OS does not support memory management using the garbage collection feature that is in Mac OS X v10.5 and later.

entry point

  int main(int argc, char *argv[])
  {
     //creates the application's top-level autorelease pool, whose job is to reclaim the memory for Objective-C objects that are freed using their autorelease method
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
     //calls the UIApplicationMain function to create the MoveMe application's key objects, initialize those objects, and start the event-processing loop. The application does not return from this function until it quits
     int retVal = UIApplicationMain(argc, argv, nil, nil);
     [pool release];
     return retVal;
  }

application delegate

  • use Interface Builder to designate the class as the application delegate
  • application delegate object works in tandem with the standard UIApplication object to respond to changing conditions in the application
  • application object does most of the heavy lifting, but the delegate is responsible for several key behaviors
    • Setting up the application's window and initial user interface
    • Performing any additional initialization tasks needed for your custom data engine
    • Opening content associated with the application's custom URL schemes
    • Responding to changes in the orientation of the device
    • Handling low-memory warnings
    • Handling system requests to quit the application
  • at launch time, the most immediate concern for the delegate object is to set up and present the application window to the user
  • when the application quits, the delegate needs to perform an orderly shutdown of the application and save any state information needed for the next launch cycle

application window

  • your application is the only thing running after it is launched
  • your application should never need more than one window—an instance of the UIWindow class
    • In situations where you need to change your user interface, you change the views displayed by your window
  • windows provide the drawing surface for your user interface, but view objects provide the actual content
  • a view object is an instance of the UIView class that draws some content and responds to interactions with that content

At launch time

  • The window is unarchived from the MainWindow.xib nib file
  • When the application reaches a state where it is launched and ready to start processing events, the UIApplication object sends the delegate an applicationDidFinishLaunching: message
  • the initWithCoder: method called when the MoveMeView object is unarchived from its nib file
  - (void)applicationDidFinishLaunching:(UIApplication *)application
  {
     // Set up the view controller
     UIViewController *aViewController = [[UIViewController alloc]
              initWithNibName:@"MoveMeView" bundle:[NSBundle mainBundle]];
     self.viewController = aViewController;
     [aViewController release];

     // Add the view controller's view as a subview of the window
     UIView *controllersView = [viewController view];
     [window addSubview:controllersView];
     [window makeKeyAndVisible];
  }
  - (void)setUpPlacardView
  {		
     // Create the placard view -- it calculates its own frame based on its image
     PlacardView *aPlacardView = [[PlacardView alloc] init];
     self.placardView = aPlacardView;
     [aPlacardView release];
     placardView.center = self.center;
     [self addSubview:placardView];
  }

drawing

  • custom rendering can be achieved by overloading the drawRect: method
  - (void)drawRect:(CGRect)rect
  {
      // Draw the placard at 0, 0
      [placardImage drawAtPoint:(CGPointMake(0.0, 0.0))];
   
      /*
       Draw the current display string.
       This could be done using a UILabel, but this serves to illustrate
       the UIKit extensions to NSString. The text is drawn center of the
       view twice - first slightly offset in black, then in white -- to give
       an embossed appearance. The size of the font and text are calculated
       in setupNextDisplayString.
       */
   
      // Find point at which to draw the string so it will be in the center of the view
      CGFloat x = self.bounds.size.width/2 - textSize.width/2;
      CGFloat y = self.bounds.size.height/2 - textSize.height/2;
      CGPoint point;
   
      // Get the font of the appropriate size
      UIFont *font = [UIFont systemFontOfSize:fontSize];
   
      [[UIColor blackColor] set];
      point = CGPointMake(x, y + 0.5);
      [currentDisplayString drawAtPoint:point
                  forWidth:(self.bounds.size.width-STRING_INDENT)
                  withFont:font
                  fontSize:fontSize
                  lineBreakMode:UILineBreakModeMiddleTruncation
                  baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
   
      [[UIColor whiteColor] set];
      point = CGPointMake(x, y);
  			
      [currentDisplayString drawAtPoint:point
                  forWidth:(self.bounds.size.width-STRING_INDENT)
                  withFont:font
                  fontSize:fontSize
                  lineBreakMode:UILineBreakModeMiddleTruncation
  }

touching

  • UIView disables multitouch by default
  • you can reenable multi-touch support using the setMultipleTouchEnabled: method of the UIView class
  • a class detects taps by overriding the following methods of UIResponder:
  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
  - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {
      // We only support single touches, so anyObject
      // retrieves just that touch from touches
      UITouch *touch = [touches anyObject];
   
      // Only move the placard view if the touch was in the placard view
      if ([touch view] != placardView)
      {
          // In case of a double tap outside the placard view,
          // update the placard's display string
          if ([touch tapCount] == 2)
          {
              [placardView setupNextDisplayString];
          }
          return;
      }
      // Animate the first touch
      CGPoint touchPoint = [touch locationInView:self];
      [self animateFirstTouchAtPoint:touchPoint];
  }
  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  {
      UITouch *touch = [touches anyObject];
   
      // If the touch was in the placardView, move the placardView
      // to its location
      if ([touch view] == placardView)
      {
          CGPoint location = [touch locationInView:self];
          placardView.center = location;
          return;
      }
  }
  - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  {
      UITouch *touch = [touches anyObject];
   
      // If the touch was in the placardView, bounce it back to the center
      if ([touch view] == placardView)
      {
          // Disable user interaction so subsequent touches
          // don't interfere with animation
          self.userInteractionEnabled = NO;
          [self animatePlacardViewToCenter];
          return;
      }
  }

accelerometer

  • use the UIAccelerometer to get position information
Personal tools