User Interface Application

Ratings:
(4)
Views:834
Banner-Img
  • Share this blog:

UIApplication and UIApplicationDelegate

Key Skills & Concepts

Understanding the UIApplication class Understanding the UIApplicationDelegate protocol Handling application startup and termination Handling application interruptions Every iPhone application has one UIApplication. UIApplication is an iPhone application’s starting point and is responsible for initializing and displaying your application’s UIWindow. It is also responsible for loading your application’s first UIView into the UIWindow. Another responsibility UIApplication has is managing your application’s life cycle. UIApplication fulfils this management responsibility using a delegate called UIApplicationDelegate.Although UIApplication receives events, it’sthe UIApplication Delegate that handles how an application responds to those events. Events the UIApplicationDelegate might handle include application life cycle events, such as startup and shutdown, and system events like incoming phone calls and calendar alerts. In this chapter, after learning how to load an application’s root view into the UIWindow, you explore handling system events using the UIApplicationDelegate protocol. Adding a UIView and UIViewController to a UIApplicationDelegate Before continuing, create this chapter’s project; this chapter uses the same project throughout. In this project, you start with the simplest iPhone template, a Window-based application and you create an application from scratch. You first create a xib and corresponding view controller. You then modify the application’s delegate so it loads the view.

  1. Create a new Window-based Application from the New Project Name the project AddViewProject.
  2. In Groups & Files, expand the Classes This folder contains the AddViewProject AppDelegate.h and AddViewProjectAppDelegate.m files. These two files implement the project’s custom class that adopts the UIApplicationDelegate protocol.
  3. Highlight the Resources folder. CTRL-Click and Select Add | New File from the popup menu. Select User Interfaces from the New File dialog, and select Empty XIB(Figure6-1).

   Slide4                                                                                Figure 6-1 Creating an Empty XIB Interface Builder  

  1. Name the xib FirstViewController and click
  2. Highlight the Classes folder in Groups & Select File | New File from the menu.
  3. Select the UIViewController subclass from the Cocoa Touch Classes and click Next (Figure 6-2).

NOTE You could have created the view controller first and then checked the ―With XIB for user interface,‖ check box and Xcode would have generated the xib for you.

  1. Name the file FirstViewController.m and ensure the Also Create "FirstViewController.h" check box is selected. Click Finish.
  1. Double-click FirstViewController.xib and open it in Interface Builder.

   Slide5                                                                                           Figure 6-2 Creating a UIViewController  

  1. Select a view from the library, and drag-and-drop it onto the xib Document window.
  2. In the Document window, highlight File’s Owner and select FirstViewController as the class in the First View Controller Identity Inspector (Figure 6-3).
  3. In the Inspector, set the newly created view as FirstViewController’s view outlet (Figure 6-4).
  4. Select the view and change its color using the inspector (Figure 6-5).
  5. Save xib and exit Interface Builder.
  6. Open  h,   import   FirstViewController.h,   and   create   a property referencing the FirstViewController class (Listing 6-1).

  Slide6 Figure 6-3 Select FirstViewController as the file’s owner   Slide7   Figure 6-4 Setting the view as the File’s Owner view   Slide8 Figure 6-5 Changing the view’s color  

  1. Open m, synthesize first, and modify applicationDidFinish Launching: so it obtains a reference to FirstViewController from FirstViewController.xib and then adds its view as a subview to the window. FirstViewController.m should appear identical to Listing 6-2.
  2. Click Build And Your colored view should load into the iPhone Simulator (Figure 6-6).

  Listing 6-1 AddViewProjectAppDelegate.h interface #import <UIKit/UIKit.h> #import "FirstViewController.h"; @interface AddViewProjectAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; FirstViewController *first; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) FirstViewController *first; @end   Slide9   Figure 6-6 The application in iPhone Simulator     Listing 6-2 AddViewProjectAppDelegate.m implementation #import "AddViewProjectAppDelegate.h" @implementation AddViewProjectAppDelegate @synthesize window; @synthesize first;

  • (void)applicationDidFinishLaunching:(UIApplication *)application { first = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];

[window addSubview: [first view]]; [window makeKeyAndVisible]; }

  • (void)dealloc {
  • [window release];
  • [first release];
  • [super dealloc];

} @end In steps 10 and 11, you manually connected AddViewProjectAppDelegate to its UIView. Moreover, you placed that view in its own nib. Every nib has an owner. Recall that every application has one UIWindow. UIWindow is in a project’s MainWindow.xib. That nib’s owner is UIApplication. Also notice that Xcode added the AddViewProjectAppDelegate to MainWindow.xib and connected it to the UIWindow and set the UIApplication’s delegate. Nibs you create should have a class adopting the UIViewController protocol as an owner, which is what you did in step 10. In step 9, you tied the UIView created in the nib in Interface Builder to the UIViewController created in Xcode. This is how the two objects ―know‖ about each other. You learn more about UIViewControllers and UIViews—and connecting them—in Chapter 7.     NOTE Notice that you created FirstViewController’s view in its own FirstViewController.xib file. You could have opened MainWindow.xib, dragged a view onto the window, and used this nib for your user interface. But this is not the preferred way of using views in nibs. Apple recommends one nib per view. The reason for this recommendation is that an application must load all views and all controls that reside in the same nib. Using one nib per view reduces your application’s memory use because you only load views as needed. Q: What is that initWithNibName line in Listing 6-2? A: This method allows initializing a UIViewController’s view from a nib file rather than from code. You use this method when you want to write code that initializes a view controller whose view resides in a nib. You should note that this is just one of several different ways you might load a view from a nib into a class. By book’s end, you will be familiar with most of them. In the previous section, I only briefly mentioned the connections in MainWindow.xib. But these connections warrant a closer look if you want to understand what the template actually did. Notice the UIWindow in Listing 6-1 is an IBOutlet. Your first experience with IBOutlets was in Chapter 1, you learn more on it in Chapter 7. But realize the window ―lives‖ in the xib, not in the delegate. Although the window is released by the delegate in the dealloc method, it is neither allocated nor initialized by the delegate’s code in Listing 6-2. Remember, all the dealloc method in Listing 6-2 is doing is releasing the class’s reference to the window, not deallocating the window. Instead, MainWindow.xib handles allocating, initializing, and deallocating the UIWindow.UIApplication knows to load MainWindow.xib by consulting the NSMainNibFile key in Info.plist file. If you open the AddViewProject project’s Info.plist, you will see that the ―Main nib file base name‖ is set to MainWindow. While loading, the nib sets  AddViewProjectAppDelegate as UIApplication’s delegate and UIWindow as AddViewProjectAppDelegate’s window. Both are outlets of their respective class in Interface Builder. Exploring MainWindow.xib

  1. Open xib and display the document window.
  2. Highlight the File’s Notice it is set to UIApplication (Figure 6-7). UIApplication loads MainWindow.xib.
  3. Notice that the template added the AddViewProjectAppDelegate
  4. Notice AddViewProjectAppDelegate’s IBOutlet, window, is set to the UIWindow in the nib (Figure 6-8). Also notice that the UIApplication’s delegate is set as AddViewProject

   Slide10                                                                                           Figure 6-7 UIApplication in the Document window     Slide11 Figure 6-8 AddViewProjectAppDelegate’s connections   Ignore UIApplication—you almost never modify it. Just know that UIApplication receives system events. It is your job to write code that handles those system events. You write that code in a class adopting the UIApplicationDelegate protocol. This protocol has several life cycle methods that handle application and system events. Table 6-1 lists UIApplicationDelegate’s methods. If you begin with a template, Xcode creates the class adopting the UIApplicationDelegate for you, but Xcode does not implement the UIApplicationDelegate’s optional event-handling methods. For instance, in this chapter’s project, Xcodecreated the AddViewProject  AppDelegate.h and AddViewProjectAppDelegate.m files. The Add ViewProject AppDelegate class extends NSObject and adopts the UIApplication Delegate. @interface AddViewProjectAppDelegate : NSObject <UIApplicationDelegate> The application’s UIApplication, defined in MainWindow.xib, has a reference to its UIApplicationDelegate as an outlet (Figure 6-8). As UIApplication receives one of the events related to the methods in Table 6-1, it calls the appropriate method in its delegate if implemented.

Ask the Expert

Q: What is a delegate? A: A delegate is a way to simplify the separation of processing logic from another class. It also avoids inheritance. For instance, subclassing the UIApplication object would be painful. Instead, Apple provides a UIApplicationDelegate. The UIApplication has a reference to the class implementing the UIApplicationDelegate. If implemented,the UIApplication delegates handling an event to the appropriate method in the UIApplicationDelegate. It appears as if UIApplication is handling the event; in reality, its delegate, UIApplicationDelegate, handles the event. Delegates are a common object- oriented design pattern. For more information on delegates and object-oriented programming, refer to the ―delegation pattern‖ on Wikipedia (www.wikipedia.org).  

The main.m file

In the AddViewProject project, open main.m in the Other Sources folder in Groups & Files. The file’s code is listed in Listing 6-3. Listing 6-3 File main.m in project #import <UIKit/UIKit.h> int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }     Main creates one UIApplication instance using the UIApplicationMain method. Every project has exactly one UIApplication object. You can obtain a reference to that object by calling UIApplication’s sharedApplication class method. This method returns a singleton reference to your application’s UIApplication object. UIApplication * myApplication = [UIApplication sharedApplication]; You usually will not do much with the UIApplication object other than obtain a reference to its UIApplicationDelegate. You obtain a reference to the UIApplicationDelegate through the following code: UIApplicationDelegate * myDelegate = [[UIApplication sharedApplication] delegate];

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/15

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox