Beginning iOS Programming For Dummies Cheat Sheet - dummies
Cheat Sheet

Beginning iOS Programming For Dummies Cheat Sheet

From Beginning iOS Programming For Dummies

By Rajiv Ramnath

Although iOS powers only about 13 percent of smartphone users in the U.S., its programs have a usage share of 55 percent when you consider the heavy traffic over the Internet and that iOS devices are bought by people who use their devices frequently. Also, iOS comes with a well-designed Objective-C-based software development kit (SDK) with rich functionality to make developing apps straightforward and fun. In other words, iOS is a perfect target market for an innovative app developer.

Getting Started with Object-Oriented iOS Programming

iOS programming, Objective-C, object-orientation, and OO design go together. Read on for some helpful quick tips for OO Design. It’s time to get up to speed!

Designing “good” classes

Your classes must be highly cohesive and loosely coupled. Here is a checklist to quickly test whether a class is good: A “No” answer to any of the questions means that you may need to rethink your class.

  • Can you give the class a name that captures its reason for being?

  • Can you give it a description that says that it does just one thing?

  • Does it have responsibilities (methods)? Are all the responsibilities in alignment with the description?

  • Does it have collaborators?

  • Does it — or its components — maintain long-lived state?

Making a type a subclass of an existing class or use delegation

Say that you need a type named Tiger and it seems to share the responsibilities of an Animal. Therefore, you’re trying to decide whether you should declare Tiger as a subclass of a class named Animal, or perhaps declare a member variable of type Animal and delegate animalistic responsibilities to this member variable.

Say these two sentences out loud:

  • Tiger IS-A an Animal.

  • Tiger CAN-BE an Animal.

If the first makes more sense (which in this case it does), Tiger should be a subclass of Animal.

Meeting the iOS App Methods and Platforms

When writing an iOS app, it’s very important to understand and weave app-specific code into its lifecycle. Trying to figure out which lifecycle method to use? Check this list:

  • Use willFinishLaunchingWithOptions to do any processing right after the app starts up and before it displays its first window, and before it even has a restored state.

    You typically use this method to check whether the startup parameters to the app (such as a URL) are correct. You could also check the environment in which the app is launched (for example, did it launch on an iPad that has the ability to make cellular calls). Incidentally, this method will not work on a device with an iOS version older than iOS 6.

  • Use didFinishLaunchingWithOptions to do any processing after you’re sure that the app is going to start.

    For example, you can use this method to restore a global state.

  • Use applicationDidBecomeActive in order to restart a process that was paused while the app was inactive.

    For example, you could start to listen for location changes or even refresh the UI with fresh data.

  • Use applicationWillResignActive to pause your app while the user gives his attention to another activity — such as answering a phone call.

  • Use applicationDidEnterBackground to release resources and save user data along with enough app state information to restore your app to its current state in case it’s terminated later.

    You are allowed approximately five seconds of processing in this method, so don’t do any tasks that may not terminate — such as prompting the user.

  • Use applicationWillEnterForeground to undo what you did in applicationDidEnterBackground.

  • Use applicationWillTerminate to do any final cleanup tasks.

Making Your iOS Apps Fit for Consumption

iOS program performance is more than background processes. A few simple tricks can save time and increase performance. For the straight story, check out these hints.

Quickly finding and opening relevant files in Xcode

Use the Open Quickly command to find and open a file at a specific line, using its filename, type, or a symbol in the file (like a variable or function name), as follows:

  1. Choose File→ Open Quickly.

  2. In the search field, type characters in the name of the file or symbol you want to view.

  3. Type a dot followed by one or more characters of the filename extension.

  4. To have the file open at a specific line, type a colon followed by the line number.

  5. Choose a file from the results list.

This dialog also lets you decide where to place a file in Xcode. Just press and hold CMD+OPT+SHIFT while double-clicking the file.

Configuring behaviors

You can configure how Xcode responds to common events by setting its behavior using the Xcode→Preferences→Behavior settings page to set behavior preferences.

For example, you can have a certain set of tabs appear when Xcode runs your app. Or, if a build fails, you can make Xcode save a snapshot and open the debug area in your workspace window.

Creating a .gitignore file

Xcode can easily connect with git, a popular source code management system. If used without any configuration, git will try to archive everything in a project, even files with compiled object code, executables, and temporary files used by Xcode.

To fix this issue, you need to create configure git appropriately. To do this, navigate to the project folder and create a .gitignore file with the following content:

OS X Finder
# Xcode per-user config
# Build products
# Automatic backup files

Popping up an Alert view

Your app often needs to pop up an alert to let the user know something happened and that she has a choice of actions. Here is a quick checklist for how to set up an alert.

  1. Implement the clickedButtonAtIndex method in the class that will cause the alert to pop up.

    The following example code shows you how:

        - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
            if (buttonIndex == 0){
                [self playNewGame];
            } else if (buttonIndex == 1) {
  2. Create, initialize, and show the alert.

    The following snippet of code shows you how:

    UIAlertView *alert = [[UIAlertView alloc] init];
    [alert setTitle:@"Game Over!"];
    [alert setMessage:@"Play Another Game?"];
    [alert addButtonWithTitle:@"Yes"];
    [alert addButtonWithTitle:@"No"];
    [alert setDelegate:self];
    [alert show];

Connecting Your iOS Apps

Your iOS application may need to communicate with a variety of other resources. Fortunately, the iOS toolbox has a variety of specialized connections. Pick one up and put it to work.

Opening a browser from your app

Here’s a quick and dirty way of having your app open a web page in a browser. See the following example code:

    - (IBAction)helpViaBrowser: (id) sender{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@""]];

Yes, it is that simple!

Converting an address to a geolocation

Most mapping or location-based apps have a need to convert a text string containing an address or a location to geo-coded coordinates. Luckily the iOS framework provides a built-in geocoder. The following code shows you how to use the geocoder:

NSString *findString = [findTextField text]; // the string is read from a text field
    [myGeocoder geocodeAddressString:findString completionHandler:
                                       ^(NSArray* placemarks, NSError* error){
        MKPlacemark *aPlacemark = [placemarks objectAtIndex:0];
        // aPlacemark contains the geocoded information

Testing for network capabilities

It’s a good idea to test what network capabilities are available before your app tries to use the network. Here’s how you can do this test:

    + (void) listCapabilities{
       // Testing for the network
       NSString *networkReachability=nil;
       Reachability *reachFacade = [Reachability reachabilityForInternetConnection];
       NetworkStatus status = [reachFacade currentReachabilityStatus];
       if (status==NotReachable) networkReachability = @"No networkn";
       else if (status==ReachableViaWiFi) networkReachability = @"Wifi availablen";
       else if (status==ReachableViaWWAN) networkReachability = @"WAN availablen";
       [textVal appendString:networkReachability];

Starting sensors

Before you can read sensed values, you have to start and configure the motion manager. The following code shows you how:

        // Set up the motion manager
        self->motionManager = [[CMMotionManager alloc] init];
        self->motionManager.accelerometerUpdateInterval = 1;
        self->motionManager.gyroUpdateInterval = 1;
        self->motionManager. magnetometerUpdateInterval = 1;

However, just starting the motion manager is not enough. You also have to start monitoring the sensors, as shown here:

- (IBAction) startMonitoringSensors:(id)sender{
                 [NSOperationQueue currentQueue]
                    withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
                        [self handleAccelerationUpdates:accelerometerData.acceleration];
                 [NSOperationQueue currentQueue]
                    withHandler:^(CMGyroData *gyroscopeData, NSError *error) {
                        [self handleGyroUpdates:gyroscopeData.rotationRate];
                 [NSOperationQueue currentQueue]
                    withHandler:^(CMMagnetometerData *magnetometerData, NSError *error) {
                        [self handleMagnetometerUpdates:magnetometerData. magneticField];