MOBILE

Cocoa Fundamentals

9/15/2010 11:52:32 AM

Thousands of classes are available in the iOS SDK, but most of your applications will be using a small set of classes to implement 90% of their features. To familiarize you with the classes and their purposes, let’s review some of the names you’re going to be seeing very, very frequently over the next few hours. Before we begin, keep these few key points in mind:

  • Apple sets up much of the structure of your application for you in Xcode. This means that even though you need some of these classes, you won’t have to lift a finger to use them. Just create a new Xcode project and they’re added for you.

  • You’ll be adding instances of many of these objects to your projects just by dragging icons in the Interface Builder application. Again, no coding needed!

  • When a class is used, I tell you why it is needed, what it does, and how it is used in the project. I don’t want you to have to jump around digging for references in the book, so focus on the concepts, not memorization.

  • In the next section of this hour’s lesson, you’ll learn about the Apple documentation tools. These helpful utilities will enable you to find all the class, property, and method information that you could ever hope for. If it’s gritty details you want, you’ll have them at your fingertips!

Core Application Classes

When you create a new application with even the most basic user interaction, you’ll be taking advantage of a collection of common core classes. Many of these you won’t be touching, but they still perform an important role. Let’s review several of these classes now.

The Root Class (NSObject)

As you learned in this article, “Discovering Objective-C: The Language of Apple Platforms,” the power of object-oriented programming is that when you create a subclass of an object, you inherit that object’s functionality. The root class, from which almost all Objective-C classes inherit, is NSObject. This object defines methods common to all classes, such as alloc, dealloc, and init. You will not need to create NSObject instances manually in this book, but you will use methods inherited from this class to create and manage new objects.

The Application Object (UIApplication)

Every application on the iPhone implements a subclass of UIApplication. This class handles events, such as notification of when an application has finished loading, as well as application configuration, such as controlling the status bar and setting badges (the little red numbers that can appear on application icons). Like NSObject, you won’t need to create this yourself; just be aware it exists.

Window Objects (UIWindow)

The UIWindow class provides a container for the management and display of views. In iOS-speak, a view is more like a typical desktop application “window,” whereas an instance of UIWindow is just a container that holds the view. You will be using only a single UIWindow instance in this book, and it will be created automatically in the project templates that Xcode provides for us.

Views (UIView)

The UIView class defines a rectangular area and manages all the onscreen display within that region—what we will refer to as a view. Most of your applications will start by adding a view to an instance of UIWindow.

Views can be nested to form a hierarchy; they rarely exist as a single object. A top-level view, for example, may contain a button and field. These controls would be referred to as subviews and the containing view as the superview. Multiple levels of views can be nested, creating a complex hierarchy of subviews and superviews. You’ll be creating almost all of your views visually in Interface Builder, so don’t worry: Complex doesn’t mean difficult!

Responders (UIResponder)

The UIResponder class provides a means for classes that inherit from it to respond to the touch events produced by the iPhone. UIControl, the superclass for nearly all onscreen controls, inherits from UIView, and subsequently, UIResponder. An instance of UIResponder is just called a responder.

Because there can be multiple objects that could potentially respond to an event, iOS will pass events up what is referred to as a chain of responders. The responder instance that can handle the event is given the designation first responder. When you’re editing a field, for example, the field has first responder status because it is actively handling user input. When you leave the field, it “resigns” first responder status. For most of your iOS development work, you won’t be directly managing responders in code.

Onscreen Controls (UIControl)

The UIControl class inherits from UIView and is used as the superclass for almost all onscreen controls, such as buttons, fields, and sliders. This class is responsible for handling the triggering of actions based on touch events, such as “pressing” a button.

As you’ll learn in the next hour, a button defines a handful of events that you can respond to; Interface Builder enables you to tie those events to actions that you’ve coded. UIControl is responsible for implementing this behavior behind the scenes.

View Controllers (UIViewController)

You’ll be using the UIViewController class in almost all the application projects throughout this book to manage the contents of your views. You’ll use a UIViewController subclass, for example, to determine what to do when a user taps a button. Make a sound? Display an image? However you choose to react, the code you use to carry out your action will be implemented as part of a view controller instance. You’ll learn much more about view controllers over the next two hours.

Data Type Classes

An object can potentially hold data. In fact, most of the classes we’ll be using contain a number of properties that store information about an object. There are, however, a set of Foundation classes that you’ll be using throughout this book for the sole purpose of storing and manipulating information.

By the Way

If you’ve used C or C-like languages before, you might find that these data type objects are similar to data types already defined outside of Apple’s frameworks. By using the Foundation framework implementations, you gain access to a wide range of methods and features that go well beyond the C/C++ data types. You will also be able to work with the objects in Objective-C using the same development patterns as any other object.


Strings (NSString/NSMutableString)

Strings are collections of characters—numbers, letters, and symbols. You’ll be using strings to collect user input and to create and format user output frequently throughout the book.

As with many of the data type objects you’ll be using, there are two string classes: NSString and NSMutableString. The difference, as the name describes, is that one of the classes can be used to create strings that can be changed (mutable). An NSString instance remains static once it is initialized, whereas an NSMutableString can be changed (lengthened, shortened, replaced, and so on).

Strings are used so frequently in Cocoa Touch applications that you can create and initialize an NSString using the notation @"<my string value>". For example, if you needed to set the text property of an object called myLabel to a new string that reads "Hello World!", you could use the following:

myLabel.text=@"Hello World!"

Strings can also be initialized with the values of other variables, such as integers, floating-point numbers, and so on.

Arrays (NSArray/NSMutableArray)

A useful category of data type is a collection. Collections enable your applications to store multiple pieces of information in a single object. An NSArray is an example of a collection data type that can hold multiple objects, accessed by a numeric index.

You might, for instance, create an array that contains all the user feedback strings you want to display in an application:

myMessages = [[NSArray alloc] initWithObjects: @"Good Job!",@"Bad job!",nil]

A nil value is always used to end the list of objects when initializing an array. To access the strings, you use the index value. This is the number that represents its position in the list, starting with zero. To return the "Bad job!" message, we would use the objectAtIndex method:
[myMessages objectAtIndex: 1]

As with strings, there is a mutable NSMutableArray class that creates an array capable of being changed after it has been created.

Dictionaries (NSDictionary/NSMutableDictionary)

Like arrays, dictionaries are another collection data type, but with an important difference. Whereas the objects in an array are accessed by a numeric index, dictionaries store information as object/key pairs. The key is an arbitrary string, whereas the object can be anything you want, such as a string. If the previous array were to be created as an NSDictionary instead, it might look like this:

myMessages = [[NSDictionary alloc] initwithObjectsAndKeys:@"Good Job!",@"positive",@"Bad
Job!",@"negative",nil];

Now, instead of accessing the strings by a numeric index, they can be accessed by the keys “positive” and “negative” with the objectForKey method, as follows:
[myMessages objectForKey:@"negative"]

Dictionaries are useful because they let you store and access data in abstract ways rather than in a strict numeric order. Once again, the mutable form of the dictionaries, NSMutableDictionary, can be modified after it has been created.

Numbers (NSNumber/NSDecimalNumber)

We can store strings and collections of objects, but what about numbers? Working with numbers is a bit different. In general, if you need to work with an integer, you’ll use the C data type int, and for floating-point numbers, float. You won’t need to worry about classes and methods and object-oriented programming at all.

So, what about the classes that refer to numbers? The purpose of the NSNumber class is to take a numeric C data type and store it as an NSNumber object. The following line creates a number object with the value 100:

myNumberObject = [[NSNumber alloc] numberWithInt: 100]

You can then work with the number as an object—adding it to arrays, dictionaries, and so on. NSDecimalNumber, a subclass of NSNumber, can be used to perform decimal arithmetic on very large numbers, but will be needed only in special cases.

Dates (NSDate)

If you’ve ever tried to work with a date manually (interpreting a date string in a program, or even just doing date arithmetic by hand), you know it can be a great cause of headaches. How many days were there in September? Was this a leap year? And so on. The NSDate class provides a convenient way to work with dates as an object.

For example, assume you have a user-provided date (userDate) and you want to use it for a calculation, but only if it is earlier than the current date, in which case, you want to use that date. Typically, this would be a bunch of nasty comparisons and assignments. With NSDate, you would create a date object with the current date in it (provided automatically by the init method):

myDate=[[NSDate alloc] init]

And then grab the earlier of the two dates using the earlierDate method:

[myDate earlierDate: userDate]

Obviously, you can perform many other operations, but you can avoid much of the ugliness of data and time manipulation using NSDate objects.

URLs (NSURL)

URLs are certainly a different type of data from what we’re accustomed to thinking about, but on an Internet-connected device like the iPhone, you’ll find that the ability to manipulate URLs comes in handy. The NSURL class will enable you to manage URLs with ease. For example, suppose you have the URL http://www.floraphotographs.com/index.html and want to get just the machine name out of the string? You could create an NSURL object:

MyURL=[[NSURL alloc] initWithString: @"http://www.floraphotographs.com/index.html"]

Then use the host method to automatically parse the URL and grab the text www.floraphotographs.com:
[MyURL host]

This will come in handy as you start to create Internet-enabled applications. Of course, many more data type objects are available, and as mentioned earlier, some objects store their own data, so you won’t, for example, need to maintain a separate string object to correspond to the text in labels that you have onscreen.

Speaking of labels, let’s round out our introduction to common classes with a quick look at some of the UI elements that you’ll be adding to your applications.

Interface Classes

Part of what makes the iPhone such a fun device to use are the onscreen touch interfaces that you can create. As we explore Interface Builder in the next hour, you’ll get your first hands-on experience with some of these interface classes. Something to keep in the back of your head as you read through this section is that many UI objects can take on very different visual appearance based on how they are configured—so there is quite a bit of flexibility in your presentation

Labels (UILabel)

You’ll be adding labels to your applications both to present static text onscreen (as a typical label) and as a controllable block of text that can be changed as needed by your program (see Figure 1).

Figure 1. Labels add text to your application views.


Buttons (UIButton)

Buttons are one of the simplest user input methods that you’ll be using. Buttons can respond to a variety of touch events and give your users an easy way to make onscreen choices (see Figure 2).

Figure 2. Buttons provide a simple form of user input/interaction.


Switches (UISwitch)

A switch object can be used to collect “on” and “off” responses from a user. It is displayed as a simple toggle and is frequently used to activate or deactivate application features (see Figure 3).

Figure 3. A switch moves between on and off states.


Segmented Control (UISegmentedControl)

A segmented control creates an elongated touchable bar with multiple named selections (Category 1, Category 2, and so on). Touching a selection will activate it and can trigger your application to perform an action, such as updating the screen to hide or show other controls (see Figure 4).

Figure 4. Segmented controls can be used to choose one item out of a set and react accordingly.


Sliders (UISlider)

A slider provides the user with a draggable bobble for the purpose of choosing a value from across a range. Sliders, for example, are used to control volume, screen brightness, and other inputs that should be presented in an “analog” fashion (see Figure 5).

Figure 5. Sliders offer a visual means of entering a value within a range.


Text Fields (UITextField/UITextView)

Text fields are used to collect user input through the iPhone’s onscreen keyboard. The UITextField is a single-line field, similar to what you’d see on a web page order form. The UITextView class, on the other hand, creates a larger multiline text entry block for more lengthy compositions (see Figure 6).

Figure 6. Collect user input through text fields.


Pickers (UIDatePicker/UIPicker)

A picker is an interesting interface element that resembles a slot machine display. By letting the user change each segment on the wheel, it can be used to enter a combination of several different values. Apple has implemented one complete picker for you: the UIDatePicker class. With this object, a user can quickly enter dates and times. You can also implement your own arbitrary pickers with the UIPicker class (see Figure 7).

Figure 7. Pickers enable users to choose a combination of several options.


These are only a sample of the classes that you can use in your applications. We explore these and many others in the hours to come.

Other  
  •  Tracing the iPhone Application Life Cycle
  •  Inside Cocoa Touch : Exploring the iOS Technology Layers
  •  The Language of Apple Platforms : Memory Management
  •  The Language of Apple Platforms : Objective-C Programming Basics
  •  The Language of Apple Platforms : Exploring the Objective-C File Structure
  •  The Language of Apple Platforms : Object-Oriented Programming and Objective-C
  •  Using the iPhone Simulator
  •  Introduction to Xcode Simulator
  •  Creating a Development Provisioning Profile on iPhone
  •  Preparing Your System and iPhone for Development
  •  Understanding Mobile Networking and Remote Access in Vista
  •  Creating Connections for Remote Access in Vista
  •  Configuring Mobile Connection Properties in Vista
  •  Establishing Mobile Connections in Vista
  •  Wireless Networking in Vista
  •  Configuring Power Management Settings in Vista
  •  Configuring Networking for Laptops
  •  Mobile Commerce Applications, Part 2
  •  Mobile Commerce Applications, Part 1
  •  J2ME: User Interface
  •  
    Most View
    Nook HD - A High-Definition Tablet With The Heart Of A Reader (Part 3)
    Windows Small Business Server 2011 : Installing the Second Server (part 5) - Customizing the Server
    Reusing T-SQL Code - Scalar UDFs and Performance
    Mobile Phones Buying Guide – April 2013 (Part 7) : Samsung Galaxy S Advance, Samsung Galaxy S Ill, Sony Xperia Go, Sony Xperia P
    How To Buy…A Media Streaming Device (Part 2)
    Kaser Net’sPC2 YF810-8G Android Nettop Review (Part 1)
    Sony KDL-26EX553 – LCD Television
    Galaxy Note 10.1 - The Pen Sets This Tablet Apart
    SQL Server 2012 : Exploring SQL CLR - Security
    External Drive Western Digital My Book Thunderbolt Duo
    Top 10
    Keep Your Laptop Safe And Secure While You Travel
    8 Tips To Protect Your Business’s Wireless Network
    Alternatives To Online Backups
    My Cloud EX4 Wins On Features, Not Speed
    Must-Know Privacy Tips For Facebook And More
    Windows Phone 7 : Applying Textures (part 2) - Preparing the Effect for Texture Mapping
    Windows Phone 7 : Applying Textures (part 1) - Applying the Texture to an Object
    Windows 7 : Programming WMI Support (part 5) - Techniques for Testing WMI Driver Support, WMI Event Tracing
    Windows 7 : Programming WMI Support (part 4) - Troubleshooting Specific WMI Problems
    Windows 7 : Programming WMI Support (part 3) - Firing WMI Events