Home Application-development Xcode 4 iOS Development Beginner's Guide

Xcode 4 iOS Development Beginner's Guide

By Steven F. Daniel
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introducing Xcode 4 Tools for iOS Development
About this book

The iPhone is one of the hottest mobile devices on the planet. Whether you are just starting out with iOS Development or already have some knowledge in this area, you will benefit from what this book covers. Using this book's straightforward, step-by-step approach, you will go from Xcode 4 apprentice to Xcode 4 Jedi master in no time.

Xcode 4 iOS Development Beginner's Guide will help you learn to build simple, yet powerful applications for the iPhone from the ground up. You will master the Xcode 4 tools and skills needed to create applications that are simple yet, like Yoda, punch far above their weight.

You will start by learning about the Xcode 4 Development Tools, Xcode IDE, iOS Simulator, Objective-C 2, and Organizer. Then you will jump straight in and create applications using Xcode and Interface Builder. You finish up by learning how to build, package, and distribute your application to the Apple App Store.

This book will teach you how to go about building simple applications from scratch, you will master how to download and install the Xcode 4 Development Tools, get to know the development environment and how to build great user interfaces (using Interface Builder), learn about the different iOS frameworks, learn how to implement video and audio playback, learn how to sense motion using the Accelerometer and Gyroscope, and how to improve the reliability and performance of your applications.

After reading Xcode 4 iOS Development Beginner's Guide, you will be able to write your own applications for the iPhone with supreme efficiency. There are a lot of examples and images provided to get you up to speed quickly.

Publication date:
August 2011
Publisher
Packt
Pages
432
ISBN
9781849691307

 

Chapter 1. Introducing Xcode 4 Tools for iOS Development

Welcome to the exciting world of iPhone Programming using Xcode 4. Since the release of the original iPhone back in 2007, it has taken the world by storm and opened up a whole new world to developers. This unique device comprises a multi-touch interface, video and audio playback capabilities, stunning graphics and sound, map and localization services, always-on internet and Wi-Fi services, and a whole range of built-in sensors which can be used to create everything from stunning games to business applications.

You are probably eager to get stuck right in and start creating that next big thing to hit the AppStore, and start to join those other tens of thousands of developers. The goal of this chapter is to give you enough insight into Xcode and its components, the framework layers of the iOS architecture, and some basics of Objective-C.

By the end of this book, you will have a firm grasp of Cocoa-Touch, and understand most of the design patterns used by the Objective-C frameworks in order to go on and build some fantastic applications. These could be along the lines of a real estate application that shows a listing of all properties within the surrounding suburbs using an SQLite database to store its data, and core location services to display the property on the map, with directions on how to get there. You could even create an educational game using flash cards and sounds. The possibilities are endless; all it takes is an idea and you.

In this chapter, we will:

  • Learn about the features and components of the Xcode development tools

  • Learn about Xcode, Cocoa, Cocoa-Touch, and Objective-C

  • Take a look into each of the iOS technology layers and their components

  • Take a look into what comprises the Xcode developer set of tools

  • Take a look at the new features in the iOS4 SDK

There is a lot of fun stuff to cover, so let's get started.

Note

Throughout this chapter and the rest of this book, I will be making references to iOS. Apple is calling its new Operating System "iOS 4", and it is the next generation of the world's most innovative operating system and works for the iPhone, iPad, and iPod Touch.

 

Development using the Xcode tools


In order to develop for the iPhone or any other iOS device, you will need to download and install the Xcode developer tools. You can find these development tools on the CDs that come with your Mac. However, it is always best to download the latest version of the developer tools from the Apple website at http://developer.apple.com/.

Before you proceed to download these tools, Apple requires you to register as an iOS developer at http://developer.apple.com/programs/register/. The registration is free and provides you with access to the iOS SDK (software development kit) and other resources that are useful for getting started.

iPhone SDK core components

The iPhone SDK includes a suite of development tools to assist you with development of your iPhone, and other iOS device applications. We describe these in the table below:

COMPONENT

DESCRIPTION

Xcode

This is the main Integrated Development Environment (IDE) that enables you to manage, edit, and debug your projects.

DashCode

This enables you to develop web-based iPhone and iPad applications, and Dashboard widgets.

iPhone Simulator

The iPhone Simulator is a Cocoa-based application that provides a software simulator to simulate an iPhone or iPad on your Mac OS X.

Interface Builder

This is the graphical visual editor for designing your user interfaces for your iPhone and iPad applications. In previous releases of Xcode, this was a separate standalone application. In Xcode 4, this has now been integrated as part of the development IDE.

Instruments

These are the Analysis tools that help you optimize your applications and monitor for memory leaks in real-time.

The Xcode tools require an Intel-based Mac running Mac OS X version 10.6 or later in order to function correctly.

 

Inside Xcode, Cocoa, and Objective-C


Xcode 4 is a complete toolset for building Mac OS X (Cocoa-Based) and iOS applications. The new single-windowed development interface has been redesigned to be a lot easier and even more helpful to use than it has been in previous releases. It can now also identify mistakes in both syntax and logical errors, and will even fix your code for you.

It provides you with the tools to enable you to speed up your development process, therefore becoming more productive. It also automates deployment of both your Mac OS X and iOS applications.

The Integrated Development Environment (IDE) allows you to do the following:

  • Create and manage projects, including specifying platforms, target requirements, dependencies, and build configurations

  • Supports syntax colouring and automatic indenting of code

  • Enables you to navigate and search through the components of a project, including header files and documentation

  • Enables you to Build and Run your project

  • Enables you to debug your project locally, run within the iOS simulator, or remotely, within a graphical source-level debugger

Xcode incorporates many new features and improvements, apart from the redesigned user interface; it features a new and improved LLVM (Low Level Virtual Machine) compiler that has been supercharged to run three times faster and 2.5 times more efficiently.

This new compiler is the next generation compiler technology designed for high-performance projects and completely supports C, Objective-C, and now C++. It is also incorporated into the Xcode IDE and compiles twice as fast and quickly as GCC and your applications will run faster.

The list below includes the many improvements made to this release:

  • The interface has been completely redesigned and features a single-window integrated development interface.

  • Interface Builder has now been fully integrated within the Xcode development IDE.

  • Code Assistant opens in a second window that shows you the file that you are working on, and can automatically find and open the corresponding header file(s).

  • Fix-it checks the syntax of your code and validates symbol names as you type. It will even highlight any errors that it finds and will fix them for you.

  • The new Version Editor works with GIT (Open-Source) version control software or Subversion. This will show you the file's entire SCM (software configuration management) history and will even compare any two versions of the file.

  • The LLDB debugger has now been improved to be even faster and it uses less memory than the GDB debugging engine.

  • The new Xcode 4 development IDE now lets you work on several interdependent projects within the same window. It automatically determines its dependencies so that it builds the projects in the right order.

Xcode allows you to create a number of build configurations to test your iOS applications, for debugging using the Static Analyzer, or profiling using the Instruments application. Xcode also allows you to archive your application in order to submit to the Apple App Store for review.

It supports several source-code management tools, namely, CVS "Version control software which is an important component of the Source Configuration Management (SCM)" and Subversion that allows you to add files to a repository, commit changes, get updated versions, and compare versions using the Version Editor tool.

 

The iPhone Simulator


The iPhone Simulator is a very useful tool that enables you to test your applications without using your actual device, whether this is your iPhone or any other iOS device. You do not need to launch this application manually, as this is done when you Build and Run your application within the Xcode Integrated Development Environment (IDE). Xcode installs your application on the iPhone Simulator for you automatically.

The iPhone Simulator also has the capability of simulating different versions of the iPhone OS, and this can become extremely useful if your application needs to be installed on different iOS platforms, as well as testing and debugging errors reported in your application when run under different versions of the iOS.

Note

While the iPhone Simulator acts as a good test bed for your applications, it is recommended to test your application on the actual device, rather than relying on the iPhone Simulator for testing. This is because the speed of the iPhone Simulator relies on the performance of your Mac instead of the actual device. The iPhone Simulator can be found at the following location: /Developer/Platforms/iPhoneSimulator.Platform/Developer/Applications.

 

Layers of the iOS architecture


Apple describes the set of frameworks and technologies that are currently implemented within the iOS operating system as a series of layers. Each of these layers is made up of a variety of different frameworks that can be used and incorporated into your applications:

We will now go into detail and explain each of the different layers of the iOS Architecture; this will give you a better understanding of what is covered within each of the Core layers.

The Core OS layer

This is the bottom layer of the hierarchy and is responsible for the foundation of the operating system which the other layers sit on top of. This important layer is in charge of managing memory—allocating and releasing memory once the application has finished with it, taking care of file system tasks, handling networking, and other operating system tasks. It also interacts directly with the hardware.

The Core OS layer consists of the following components:

COMPONENT NAME

DESCRIPTION

OS X Kernel

Based on Mach 3.0, it is responsible for every aspect of the operating system.

Mach 3.0

A subset of the OS X Kernel responsible for running applications within a separate process.

BSD (Berkeley Standard Distribution)

Based on the kernel environment within the Mac OS X it is responsible for the drivers, and low-level UNIX interfaces of the operating system.

Sockets

Part of the CFNetwork Framework for providing access to BSD sockets, HTTP and FTP protocol requests.

Security

The Security Framework provides functions for performing cryptographic functions (encrypting/decrypting data). This includes interacting with the iPhone keychain to add, delete, and modify items.

Power Management

Conserves power by shutting down any hardware features that are not currently being used.

Keychain

Part of the Security Framework for handling and securing data.

Certificates

Part of the Security Framework for handling and securing data.

File System

The System Framework gives developers access to a subset of the typical tools they would find in an unrestricted UNIX development environment.

Bonjour

Part of the CFNetwork Framework for providing access to BSD sockets, HTTP and FTP protocol requests, and Bonjour discovery over a local-area-network.

The Core Services layer

The Core Services layer provides an abstraction over the services provided in the Core OS layer. It provides fundamental access to the iPhone OS services. The Core Services Layer consists of the following components:

COMPONENT NAME

DESCRIPTION

Collections

Part of the Core Foundation Framework which provides basic data management and service features for iOS applications.

Address Book

Provides access to the user's Address Book contacts on the iOS device.

Networking

This is part of the System Configuration Framework, which determines network availability and state on an iOS device.

File Access

Provides access to lower-level operating system services.

SQLite

This lets you embed a lightweight SQL database into your application without running a separate remote database server process.

Core Location

Used for determining the location and orientation of an iOS device.

Net Services

Part of the System Configuration to determine whether a Wi-Fi or cellular connection is in use and whether a particular host server can be accessed.

Threading

Part of the Core Foundation Framework which provides basic data management and service features for iOS applications.

Preferences

Part of the Core Foundation Framework which provides basic data management and service features for iOS applications.

URL Utilities

Part of the Core Foundation Framework which provides basic data management and service features for iOS applications.

The Media layer

The Media layer provides multimedia services that you can use within your iPhone, and other iOS devices. The Media layer is made up of the following components:

COMPONENT NAME

DESCRIPTION

Core Audio

Handles playback and recording of audio files and streams and also provides access to the device's built-in audio processing units.

OpenGL

Used for creating 2D and 3D animations

Audio Mixing

Part of the Core Audio Framework, provides the possibility to mix system announcements with background audio. For example, iOS would announce callerID while fading in/out the background media.

Audio Recording

Provides the ability to record sound on the iPhone using the AVAudioRecorder class.

Video Playback

Provides the ability to playback Video using the MPMoviePlayerController class.

Image Formats: JPG, PNG, and TIFF

Provides interfaces for reading and writing most image formats – part of the Image I/O Framework.

PDF

Provides a sophisticated text layout and rendering engine.

Quartz

Framework for image and video processing, and animation using the Core Animation technology.

Core Animations

Provides advanced support for animating views and other content. This is part of the Quartz Framework.

OpenGL ES

This is a subset of the OpenGL Framework for creating 2D and 3D animations.

The Cocoa-Touch layer

The Cocoa-Touch layer provides an abstraction layer to expose the various libraries for programming the iPhone, and other IOS devices. You probably can understand why Cocoa-Touch is located at the top of the hierarchy due to its support for Multi-Touch capabilities. The Cocoa-Touch layer is made up of the following components:

COMPONENT NAME

DESCRIPTION

Multi-Touch Events

These are the events which are used to determine when a Tap, Swipe, Pinch, double-tap has happened. That is, TouchesMoved, TouchesBegan, TouchesEnded.

Multi-Touch Controls

Based on the Multi-Touch model, this determines when a user has placed one or more fingers touching the screen before responding to the action accordingly.

View Hierarchy

Deals with the Model-View-Controller and the objects within the view.

Alerts

Using the UIAlertView class, these are used to communicate to the user when an error happens, or to request further input.

People Picker

Based on the AddressBook Framework, which displays the person's contact details.

Controllers

Based on the Model-View-Controller for presenting standard system interfaces and provides much of the logic needed to manage basic application behaviors. For example, managing the reorientation of views in response to device orientation changes.

Accelerometer/Gyroscope

Responds to motion and measures the degree of acceleration, and rate of rotation around a particular axis.

Localization/Geographical

Adds maps and satellite images to location-based apps, similar to the one provided by the Maps application.

Web Views

Provides a view to embed web content and display rich HTML.

Image Picker

Provides a potentially multi-dimensional user-interface element consisting of rows and components.

 

Understanding Cocoa, the language of the Mac


Cocoa is defined as the development framework used for the development of most native Mac OS X applications. A good example of a Cocoa-related application is Mail or Text Edit.

This framework consists of a collection of shared object code libraries known as the Cocoa frameworks. It consists of a runtime system and a development environment. This set of frameworks provides you with a consistent and optimized set of pre-built code modules that will speed up your development process.

Cocoa provides you with a rich layer of functionality, as well as a comprehensive object-oriented like structure and APIs on which you can build your applications. Cocoa uses the Model-View-Controller (MVC) design pattern.

What are Design Patterns?

Design Patterns represent and handle specific solutions to problems that arise when developing software within a particular context. These can be either a description or a template, on how to solve a problem in a variety of different situations.

What is the difference between Cocoa and Cocoa-Touch?

Cocoa-Touch is the programming language framework that drives user interaction on iOS. It consists of and uses technology derived from the Cocoa framework and was redesigned to handle multi-touch capabilities. The power of the iPhone and its user interface are available to developers throughout the Cocoa-Touch frameworks.

Cocoa-Touch is built upon the Model-View-Controller structure; it provides a solid stable foundation for creating mind blowing applications. Using the Interface Builder developer tool, developers will find it both very easy and fun to use the new drag-and-drop method when designing their next great masterpiece application on iOS.

 

The Model-View-Controller


We will just touch on this subject briefly as this will be covered in Chapter 5, Designing Application Interfaces using MVC. Basically, the Model-View-Controller (MVC) comprises of a logical way of dividing up the code that makes up the GUI (Graphical User Interface) of an application. Object-Oriented applications like Java and .Net have adopted the MVC design pattern.

The MVC model comprises of three distinctive categories:

  • Model: This part defines your application's underlying data engine. It is responsible for maintaining the integrity of that data.

  • View: This part defines the user interface for your application and has no explicit knowledge of the origin of data displayed in that interface. It is made up of Windows, controls, and other elements that the user can see and interact with.

  • Controller: This part acts as a bridge between the model and view and facilitates updates between them. It binds the Model and View together and the application logic decides how to handle the user's inputs.

 

What is Object-Oriented Programming?


Object-Oriented programming (OOP), provides an abstraction layer of the data on which you operate. It provides a concrete foundation between the data and the operations that you perform with the data, in effect, giving the data behavior.

By using the power of Object-Oriented programming, we can create classes and later extend its characteristics to incorporate additional functionality. Objects within a class can be protected to prevent those elements from being exposed; this is called "Data Hiding".

What is Data Hiding?

Data Hiding is an aspect of Object-Oriented Programming (OOP) that allows developers to protect private data and hide implementation details by encapsulating this within a class.

In the following Java code example, we take a look at how we implement hiding of variables, and only exposing those methods to extract this information:

public class Dog {
// public - a violation of data hiding 'rules'
  public string name;

// private - not visible outside the class
  Private float age;
  .
  .
  .

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

In the partial Dog class snippet above, we show how we are able to expose and hide variables within a class. In the following example below, we look at how we go about using the Getters and Setters to store and retrieve information, without directly assigning values to the variables:

public class Dog {
  private String name;
  private String gender;
  private String breed; 
  private float weight;
  private float height;
  private float age;

// Here are 'get' and 'set' methods for the private variable declared above.
  public void setName(String name){
    this.name = name;  
  }
  public String getName() { return name;}
  public void setGender (String gender){
    this.gender = gender;  
  }
  public String getGender() { return gender;}
  public void setBreed (String breed){
    this.breed = breed;  
  }
  public String getBreed() { return breed;}
  public void setHeight(float height ) {
     If (height >= 0) { this.height = height;}
  } 
  public float getHeight() { return height;}
  public void setWeight(float weight){
    if (weight >= 0) { this.weight = weight;}
  }
  public float getWeight() { return weight;}
  public float getAge() { return age;}
  public void setAge(float age){
    if (age >= 0) { this.age = age;}
  }
}

In the above code snippet, we have declared a number of different variable data types as well as the getters and setters to retrieve and assign values to these variables. Generally speaking, all variables declared within a class should be made private; since these types are not made visible outside the class. The only methods which should be made visible to a class must be made public and therefore supplemented with the "get" and "set" methods. In the following code snippet, we look at how we use the getters and setters to store and retrieve the data:

public class Main {

  /**
  * @param args the command line arguments
  */
  public static void main(String[] args) {
    Dog myDog = new Dog();

    // Use the 'set' method to assign each property.
    myDog.setName("Frodo");
    myDog.setGender("Male");
    myDog.setBreed("Pug");
    myDog.setWeight((float)9.0);
    myDog.setHeight((float)36.0)
    myDog.setAge((float)10.0);

    // Output each of the values using the Getters. 
    System.out.println("Name   = " + myDog.getName ());
    System.out.println("Gender = " + myDog.getGender());
    System.out.println("Breed  = " + myDog.getBreed());
    System.out.println("Weight = " + myDog.getWeight());
    System.out.println("Height = " + myDog.getHeight());
    System.out.println("Age  = " + myDog.getAge());
  }
}

In the above code snippet, we declare a new instance of our Dog class and then use the Setters method to add values to each of our private method variables, before finally displaying this information out to the screen via the Getters methods.

Note

If you are interested in learning more about Object-Oriented Programming, please consult the Apple Developer documentation or via the following link: https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/OOP_ObjC/Articles/ooOOP.html

 

What is Objective-C?


When I first started to develop for the iPhone, I realised that I needed to learn Objective-C, as this is the development language for Mac and iOS. I found it to be one of the strangest looking languages I had ever come across. Today, I really enjoy developing and working with it, so will you too.

Objective-C is an object-oriented programming language used by Apple primarily for programming Mac OS X, iPhone, and other iOS applications. It is an extension of the C Programming Language. If you have not done any OOP programming before, I would seriously recommend that you read the OOP document from the Apple Developer website.

On the other hand, if you have used and are familiar with C++, .Net or Java, learning Objective-C should be relatively easy for you to understand.

Objective-C consists of two types of files:

  • .h: These types of files are called 'Header' or 'Interface files'

  • .m: These types of files are those which contain your program code logic and make use of the 'Header' files. These are also referred to as 'implementation' files.

Most Object-Oriented development environments consist of the following parts:

  • An Object-Oriented programming language

  • An extensive library consisting of objects

  • A development suite of developer tools

  • A runtime environment

For example, here is a piece of code written in Objective-C:

-(int)method:(int)i {
  return [self square_root: i];
}

Now, let's examine the code line by line to understand what is happening.

We declare a function called method and a variable i, which is passed in as a parameter. We then pass the value to a function called square_root to calculate the value and the calculated result is returned.

If we were to compare this same code to how it would be written within C, it would look like this:

int function(int i) {
  return square_root(i);
}

Directives

In C/C++, we use directives to include any other header files that our application will need to access. This is done by using #include. In Objective-C, we use the #import directive. If you observe the content of the MyClass.h file, you will notice that at the top of the file is a #import statement:

#import <UIKit/UIKit.h>
@Interface myClass : NSObject{
}
@end

The #import statement is known as a "pre-processor directive." As I mentioned previously, in C/C++, you use the #include pre-processor directive to include a files content with the current source file. In Objective-C, you use the #import statement to do the same, with the exception that the compiler ensures that the file is only included once.

To import a header file from one of the framework libraries, you would specify the header filename using the angle brackets (< >), within the #import statement. If you wanted to import one of your own header files to be used within your project, you would specify and make use of the double quote marks (" "), as you can see from our code file, MyClass.m:

#import "MyClass.h"
@implementation MyClass
@end
 

Objective-C classes


A Class can simply be defined as a representation of a type of object; think of it as a blueprint that describes the object. Just as a single blueprint can be used to build multiple versions of a car engine, a class can be used to create multiple copies of an object. In Objective-C, you will spend most of your time dealing with classes and class objects. An example of a class object is the NSObject class. NSObject is the root class of most of the Objective-C classes. It defines the basic interface of a class and contains methods that are common to all classes that inherit from it.

The @interface directive

To declare a class, you use the @interface compiler directive that is declared within MyClass.h, as follows:

@interface MyClass : NSObject {
}

The @implementation directive

To implement a class declared within a header file, you use the @implementation compiler directive, as follows:

#import "MyClass.h"
@implementation MyClass
@end

Class instantiation

In Objective-C, in order for us to create an instance of a class, you would typically use the alloc keyword to allocate memory for the object and then return the variable in a class type. This is shown in the following example:

MyClass *myClass = [MyClass alloc];

If you are familiar with other languages such as Java or C#.Net, instantiating a class can be done as follows:

MyClass myClass = new MyClass();

Class access privileges

In OOP, when you are defining your classes, bear in mind that by default, the access privilege of all fields within a class are @protected. These fields can also be defined as @public, or @private.

The following table below shows the various access privileges that a class can contain:

ACCESS PRIVILEGE

DESCRIPTION

@private

A class member is only visible to the class that declares it.

@public

A class member is made visible to all classes that instantiate this class.

@protected

Class members are made visible to the class that declares it as well as other classes which inherit from the base class.

Note

We have only covered a small part of the Objective-C programming concepts. If you are interested in reading a bit more about this area, please refer to the following website: http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf

 

Introducing the Xcode Developer set of tools


The Xcode developer set of tools comprise of the Xcode Integrated Development Environment (IDE), Interface Builder, iPhone Simulator, and Instruments for Performance Analysis. These tools have been designed to integrate and work harmoniously together.

Introducing the core tools

The Xcode IDE is a complete full-featured development environment, which has been redesigned and built around to allow for a better smoother workflow development environment. With the integration of the GUI designer (Interface Builder), it allows a better way to integrate the editing of source code, building, compiling, and debugging.

The Interface Builder is an easy to use GUI designer which enables you to design every aspect of your applications UI, for Mac OS X and iOS applications.

All of your form objects are stored within one or more resource files, these files contain the associated relationships to each of the objects. Any changes that you make to the form design are automatically synchronized back to your code.

The iPhone Simulator provides you with a means of testing your application out, and to see how it will appear on the actual device. The Simulator makes it a perfect choice to ensure that your user interface works and behaves the way you intended it to and makes it easier for you to debug your application. The iPhone Simulator does contain some limitations, which cannot be used to test certain features, so it is always better to deploy your app to your iOS device.

The Welcome to Xcode screen

To launch Xcode, double-click on the Xcode icon located in the /Developer/Applications folder. Alternatively, you can use Spotlight to search for this: simply type Xcode into the search box and Xcode should be displayed in the list at the top.

When Xcode is launched, you should see the Welcome to Xcode screen as shown in the screenshot below. From this screen, you are able to create new projects, check out existing projects from the SCM, and modify those files within the Xcode integrated development environment. It also contains some information about learning Xcode as well as Apple Developer resources.

The panel to the right-hand side of the screen will display any recent projects which you have opened. These can be opened and loaded into the IDE by clicking on them:

The Xcode Integrated Development Environment

The Xcode Integrated Development Environment is what you will be using to start to code your iPhone applications.

This consists of a single-window user interface, consisting of the Project Window, Jump and Navigation Bars, and the newly integrated Interface Builder designer. We will talk more about the Xcode 4 workspace environment in Chapter 2, Introducing the Xcode 4 Workspace:

Features of the iPhone Simulator

The "iPhone Simulator" simulates various features of a real iOS device.

The screenshot below displays the iPhone 4 simulator:

Below we list some of the features which you are able to test using the iPhone Simulator:

TYPE

DESCRIPTION

Screen Rotation:

Left, Top, and Right

Support for gestures:

Tap

Touch and Hold

Double Tap

Swipe

Flick

Drag

Pinch

Low-Memory warning simulations

Notifies all running applications whenever the amount of free memory falls below a safe threshold. This can happen when memory is allocated to objects, but never released.

Although the iPhone simulator is just a simulator to simulate certain tasks, it does come with the following limitations:

  • Making phone calls

  • Accessing the Accelerometer/Gyroscope

  • Sending and receiving SMS messages.

  • Installing applications from the App Store

  • Accessibility to the camera

  • Use of the microphone

  • Several core OpenGL ES features

 

Companion tools and features


These tools are classified as profiling tools which are the instruments that handle the following:

  • Performance and Power Analysis tools

  • Unit testing tools

  • Source Code Management (SCM)/Subversion

  • Version Comparison tool

 

Instruments


The Xcode instruments allow you to dynamically trace and profile the performance of your Mac OS X, iPhone, and iPad applications. You can also create your own Instruments using DTrace and the Instruments custom builder.

Note

We do not cover DTrace in this book, if you are interested in reading a bit more about this area; please consult the Apple Developer Documentation at the following: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/dtrace.1.html#//apple_ref/doc/man/1/dtrace. DTrace has not been ported to iOS, so it is not possible to create a custom instrument for devices running iOS.

Through the use of instruments, you can achieve the following:

  • Ability to perform stress-tests on your applications

  • Monitor your applications for memory leaks, which can cause unexpected results

  • Gain a deeper understanding of the execution behaviour of your applications

  • Track down difficult-to-reproduce problems in your applications

  • In the screenshot displayed below, it shows you the current list of available instrument templates which you can choose from, to perform a variety of different traces on your iOS applications. We will be discussing and using these in greater detail, when we come to Chapter 10, Making your Applications run smoothly.

  • In the following screenshot, we display the Instruments environment where you can start to create your robust test harness for your application to ensure that any memory leaks and resource-intensive tasks are rectified to avoid problems later when your users download your app and experience issues:

    Note

    If you are interested in learning more about the other applications that are included with Xcode and the iOS 4 SDK, please consult the Apple Developer documentation at the following: http://developer.apple.com/

 

iPhone OS4 SDK new features


The iOS4 SDK comes with over 1,500 APIs that contain some high quality enhancements and improvements which allow endless possibilities for developers to create some stunning applications. The table below provides an overview of these features:

FEATURE

DESCRIPTION

Multi-Tasking

This is perhaps the most awaited feature. It is an assortment of seven different services: Audio, VoIP, location, local and push notifications, task completions, and fast app switching that will make it possible and simple enough to use many applications at the same time. This will allow you to play the audio continuously, receive calls while your device is locked or other apps are being used. Location-based applications will continue to guide you, and receiving alerts will be possible without the app running and the app will finish even when the customer leaves in the middle of it.

Apps Folder

Another important feature in iOS4 is the Apps Folder. This feature allows you to drag an icon on top of another one and a new folder will be automatically created. It will be named according to the name of the category the particular icon or application comes from.

Game Center

Game Center provides social networking services, where you can take part in leader boards and participate in other online activities with other players.

iAd

iAd is a mobile advertising platform to allow developers to incorporate advertisements into their application. It is currently supported on iPhone, iPod Touch, and iPad.

Note

The list above contains some of the important new features of iOS 4. If you are interested in a more detailed listing of all of the features in each of the releases; check out the following: http://en.wikipedia.org/wiki/iPhone_OS_Version_History.

 

Summary


In this chapter, hopefully you have gained a good understanding of Xcode and the development tools and the new and improved single-windowed development IDE. We have also covered some of the basics relating to Object-Oriented Programming and Objective-C. It will soon become apparent why Objective-C was chosen as the language of choice for developing Mac OS X and iOS applications.

Now that we've learned about what comprises the Xcode developer tools, we are now ready to get stuck into and learn about the new Xcode 4 workspace and development environment.

In the next chapter, we will dive right in and take a closer look at the Xcode 4 workspace environment as well as using some of the tools we have explained in this chapter. We will also start to develop a simple application using Xcode and Interface Builder.

About the Author
  • Steven F. Daniel

    Steven F. Daniel is the CEO and founder of GENIESOFT STUDIOS, a software development company based in Melbourne, Victoria, that focuses primarily on developing games and business applications for the iOS, Android, and Mac OS X platforms. He is an experienced software engineer with more than 17 years' experience and is extremely passionate about making people employable by helping them use their existing skills in iOS, Android, and Xamarin to get the job done. He is a member of the SQL Server Special Interest Group (SQLSIG), CocoaHeads, and the Java Community. He was the co-founder and Chief Technology Officer (CTO) at SoftMpire Pty Ltd., a company focused primarily on developing business applications for the iOS and Android platforms.

    Browse publications by this author
Xcode 4 iOS Development Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now