< Previous (iOS Programming – Part 1) | (iOS Programming – Part 3) Next >

If you haven’t created your own project yet with XCode please go to the part 1 of this tutorial: iOS Programming – Part 1

In this part, we are going to analyse the files that were generated by XCode when we created our project.

I am assuming that you have some knowledge in C/C++ and also about terms normally used in programming languages.
Either way, I will try to provide you with links and/or explanations of terms that I will be using.

  1. At your left you can see the files created by XCode:
  2. In Objective-C there are two kind of files. Files with the extension .h are called header files. Files with the extension .m are implementation files.

Example01AppDelegate.h

//
//  Example01AppDelegate.h
//  Example01
//
//  Created by Alejandro G. Carlstein Ramos Mejia on 9/24/11.
//  Copyright 2011 Alejandro G. Carlstein Ramos Mejia. All rights reserved.
//

#import <UIKit/UIKit.h>

@class Example01ViewController;

@interface Example01AppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window; // Added
    Example01ViewController *viewController; // Added
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet Example01ViewController *viewController;

@end

#import <UIKit/UIKit.h> is the header of the library UIKit framework. The UIKit framework are a set of classes, objects, event handling, windows, views and controls that allow you to create and administrate your application’s user interface.

@class Example01ViewController; is a forwarding declaration. A forwarding declaration tells the compiler that we will be using this class and we shall import it somewhere later. This reduce the changes of doing circular references.

@interface Example01AppDelegate : NSObject <UIApplicationDelegate>{
    UIWindow *window;
    Example01ViewController *viewController
}

@interface keyword indicate that we will be declaring the interface of our class. In this case, the name of our class is Example01AppDelegate.
This class will inherit the class NSObject and will be using the protocol UIApplicationDelegate. A class is a blueprint for creating one or more objects.

UIWindow *window; creates a pointer of type UIWindow. The UIWindow class provide methods that allow us to administrate the windows our application will displays on the screen and distribute the events to the views.

Example01ViewController *viewController; creates a pointer (similar to pointer in C/C++) of type Example01ViewController class which is a class listed in our project.  A view controller allow us to manage the view and help us with navigation and memory management. We shall analyse this class later.

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet Example01ViewController *viewController;

@property keyword allows us to declare a getter and setter accessor methods used for encapsulation, so we don’t have to write them. Inside the parenthesis we put the property attributes. In this case, we use nonatomic which indicates the compiler not to worry about multithreading. Also, we use retain which indicates the compiler to retain that we will take care of managing the passed-in variable before setting the instance variable. IBOutlet is a macro which defined variables and methods that can be referred to the Interface Builder.

@end

@end indicates that this is the end of our class definition

Example01ViewController.m

//
//  Example01AppDelegate.m
//  Example01
//
//  Created by Alejandro G. Carlstein Ramos Mejia on 9/24/11.
//  Copyright 2011 Alejandro G. Carlstein Ramos Mejia. All rights reserved.
//

#import 'Example01AppDelegate.h'
#import 'EAGLView.h'
#import 'Example01ViewController.h'

@implementation Example01AppDelegate

@synthesize window=_window;
@synthesize viewController=_viewController;

- (BOOL)applicationFrownUIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window.rootViewController = self.viewController;
    return YES;
}

- (void)applicationWillResignActiveFrownUIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    [self.viewController stopAnimation];
}

- (void)applicationDidEnterBackgroundFrownUIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForegroundFrownUIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActiveFrownUIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    [self.viewController startAnimation];
}

- (void)applicationWillTerminateFrownUIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
    [self.viewController stopAnimation];
}

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

@end

Lets begin analyzing this file.

@synthesize window=_window;
@synthesize viewController=_viewController;

The @synthesize keyword tells the compiler to create a getter and setter for (in this case) the variables (also called ivars) window and viewController.

- (BOOL)applicationFrownUIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window.rootViewController = self.viewController;
    return YES;
}

First, you may notice the hyphen “-”  in front of (BOOL). The hyphen “-” is to indicate that this is for an instance method. If you will see a plus “+” sign instead, this would indicate that this is a class method (similar to static in C++).

(BOOL) indicates what is going to be returned from the method. This type can be set to YES or NO (different to the keyword bool used in C++, which can be set in true or false).

application is the name of the method. The colon “:” after application is to indicate that the following are going to be the declaration of the parameters of the method.

(UIApplication *)application is a parameter of type UIApplication pointer the same as (NSDictionary *)launchOptions is a parameter too; however, you may notice that after application we have didFinishLaunchingWithOptions. didFinishLaunchingWithOptions is a parameter label. Parameter labels are used to differentiate methods with the same name but instead of doing it base on their types (as in C/C++), they are being differentiated by labels instead. They are the replacement of “pointers on member functions”. Pointers on member functions are expressed as Selector in Objective-C.

- (void)applicationWillResignActiveFrownUIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    [self.viewController stopAnimation];
}

Again you can see that this method is an instance method due the hyphen “-” used at the beginning. The name of the method is applicationWillResignActive and this method have one parameter application which is a pointer of type UIApplication.

As explained in the header of this class:

@interface Example01AppDelegate : NSObject <UIApplicationDelegate>

Example01AppDelegate is a class that inherits NSObject and use UIApplicationDelegate protocol.

The following are methods that are implemented in this class that are delegate methods from UIApplicationDelegate. These methods respond to the messages sent by the default notification center:

  • applicationWillResignActive: called before the application is deactivated, for example: The Home button is pressed by the user.
  • applicationDidEnterBackground: called after application begin working in the background
  • applicationWillEnterForeground: called before application gain focus again and stop working in the background.
  • applicationDidBecomeActive: called after the application becomes active.
  • applicationWillTerminate: called before the application terminates.

[self.viewController stopAnimation]; is calling the method stopAnimation which belongs to the object viewController that we are pointing at.

Finally, the dealloc method:

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

This is a method that we need to include in every class. As you may notice. we are relasing window and viewController to free memory, and we are calling the dealloc method of the superclass NSObject which we inherit. Almost every class in Objective-C inherits from NSObject, NSObject have the basic interface to the runtime system and allow them to behave as Objective-C objects. It provide allocation and initialization. Just to make sure, in cocoa touch, there is no garbage collection. The dealloc method is normally called when a class is no longer needed and its “retain counter” has reached zero.

< Previous (iOS Programming – Part 1) | (iOS Programming – Part 3) Next >

References

  • http://www.acarlstein.com/?p=996
  • http://www.raywenderlich.com/2712/using-properties-in-objective-c-tutorial
  • http://stackoverflow.com/questions/588866/atomic-vs-nonatomic-properties
  • http://stackoverflow.com/questions/1703943/what-does-the-retain-message-mean
  • http://en.wikipedia.org/wiki/Circular_reference#In_computer_programming
  • http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWindow_Class/UIWindowClassReference/UIWindowClassReference.html
  • http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
  • http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhone101/Articles/03_AddingViewController.html
  • http://pierre.chachatelier.fr/programmation/objective-c.php

Notification

These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code and information is given ‘as is’. I do not take responsibilities of how they are used.

 

© 2011, Alejandro G. Carlstein Ramos Mejia. All rights reserved.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*

Click to Insert Smiley

SmileBig SmileGrinLaughFrownBig FrownCryNeutralWinkKissRazzChicCoolAngryReally AngryConfusedQuestionThinkingPainShockYesNoLOLSillyBeautyLashesCuteShyBlushKissedIn LoveDroolGiggleSnickerHeh!SmirkWiltWeepIDKStruggleSide FrownDazedHypnotizedSweatEek!Roll EyesSarcasmDisdainSmugMoney MouthFoot in MouthShut MouthQuietShameBeat UpMeanEvil GrinGrit TeethShoutPissed OffReally PissedMad RazzDrunken RazzSickYawnSleepyDanceClapJumpHandshakeHigh FiveHug LeftHug RightKiss BlowKissingByeGo AwayCall MeOn the PhoneSecretMeetingWavingStopTime OutTalk to the HandLoserLyingDOH!Fingers CrossedWaitingSuspenseTremblePrayWorshipStarvingEatVictoryCurseAlienAngelClownCowboyCyclopsDevilDoctorFemale FighterMale FighterMohawkMusicNerdPartyPirateSkywalkerSnowmanSoldierVampireZombie KillerGhostSkeletonBunnyCatCat 2ChickChickenChicken 2CowCow 2DogDog 2DuckGoatHippoKoalaLionMonkeyMonkey 2MousePandaPigPig 2SheepSheep 2ReindeerSnailTigerTurtleBeerDrinkLiquorCoffeeCakePizzaWatermelonBowlPlateCanFemaleMaleHeartBroken HeartRoseDead RosePeaceYin YangUS FlagMoonStarSunCloudyRainThunderUmbrellaRainbowMusic NoteAirplaneCarIslandAnnouncebrbMailCellPhoneCameraFilmTVClockLampSearchCoinsComputerConsolePresentSoccerCloverPumpkinBombHammerKnifeHandcuffsPillPoopCigarette