Chapter 9. SDK programming for web developers

This chapter covers

We’ve spent the last six chapters talking about how to program great web pages and applications using familiar languages such as HTML, JavaScript, and PHP; brand-new libraries such as the WebKit, iUI, and Canvas; and helpful tools such as Dashcode, Firebug, and Safari. As we discussed in chapter 2, though, web development isn’t the be-all and end-all of iPhone programming. There are some programs that will just be better suited for native programming on the iPhone. Apple provides a development platform for doing this sort of programming called the SDK (software development kit). The SDK includes a set of tools, frameworks, and templates that we’ll meet fully in the next chapter. It also depends on a particular programming language: Objective-C.

If you’ve never worked with Objective-C, don’t panic. This chapter is intended to build on your experiences with web development (which we assume includes some sort of dynamic programming language, such as PHP, Ruby on Rails, Python, or Perl) so that you’ll be prepared to work with Objective-C when you encounter it in the next chapter.

We’ll do this by focusing on three major topics. First we’ll talk about C, which is a more complex and rigorous programming language than many of the somewhat freeform web-based languages. It’s also the core of Objective-C. Then we’ll talk about object-oriented programming, which is the style of programming used by Objective-C. Finally we’ll hit on MVC, an architectural model used by many different programming languages, including Objective-C. If you’re already familiar with some of these concepts, just skip the section where the concept is described.

Before we start this whirlwind tour, we’ll offer one caveat: none of these short overviews can possibly do justice to the topics. There are complete books on each of these topics, and if you feel like you need more information, you should pick one up. This chapter will prepare you so that you will not only understand the code in part 3 of this book, but will also be ready to dive right in yourself by tweaking and ultimately building on the copious examples that we’ll provide.

9.1. An introduction to C’s concepts

The syntax of C will look a lot like whatever language you’re familiar with. However, it may vary from your web language of choice in how it deals with some big-picture areas, such as declarations, memory management, file structure, and compilation. We’ve summarized all these ideas in table 9.1, but we’re going to talk about each of them in turn at more length.

Table 9.1. The rigorous style of C requires you to think about a few new programming topics.

C concept

Summary

Declaration and typing

You must declare variable types.

You must declare function argument types and return types.

You may need to repeat these declarations in a header file.

Memory management

You may sometimes need to explicitly manage the memory usage of your variables.

Pointers

Some variables are represented as pointers to spaces in memory.

File structure

Programs are divided between source (.c) and header (.h) files.

Directives

Precompiler commands are marked with the # sign. This includes the #include directive, which incorporates header files into source files.

Compiling

Your code is turned into a machine-readable format when you compile it, not at runtime.

Our goal here isn’t to teach you how to program in C. If you want more information on that, the definitive reference is The C Programming Language, Second Edition, by Brian W. Kernighan and Dennis M. Ritchie (Prentice Hall, 1988). Instead,our goal is to explain the programming concepts that you may not have encountered in your web-based programming language.

The reasoning behind this section is ultimately that Objective-C is built right on top of C. Therefore, we’ll show you how each of these concepts is used in C (though we’re going to save the guts of Objective-C for the next chapter).

9.1.1. Declarations and typing

C is generally a more rigorous programming language than some of the casual languages found on the web. That means there’s a bit more time spent saying what you’re going to do before you do it.

The purpose of this is not only to make it easier for a computer to understand and efficiently run your program (which was more important in the early 1970s, when C was first invented, than it is today), but also to make it easier to catch errors (which is still important today, alas). If you tell the computer what you’re going to do, then it can give you a warning if that isn’t quite what happens.

First, we see this rigor in the typing of variables. Before you’re allowed to use a variable in C, you must say how it’s going to be used. For example, the following says that the variable n will be used as an integer:

int n;

Second, we see it in functions, where you must declare not only what types of variables you’ll be passing a function, but also what type of variable you’re going to return. This is all done as part of the line of code that kicks off the function. For example, the following function takes two floating-point numbers as arguments and returns a floating-point number:

float divide(float numerator, float divisor) {

These variable and function declarations often get done a second time as part of a header file, which is a topic that we’ll return to momentarily.

A close relative to type declaration is the idea of type casting. This occurs when you take a variable and temporarily treat it (“cast it”) as a different type of variable. You do so by marking the cast in parentheses before the variable that’s being used. It usually looks something like this:

float a = 6.00;
int b;
b = (int) a;

Here, the float value of a is turned into an integer so that it can be saved to the integer variable b. Casting can sometimes lead to unexpected results, so you should be careful when using it and you shouldn’t do it often.

Objective-C Declarations and Typing

Declarations and typing work largely the same way in Objective-C. The only notable difference is that you’ll more frequently use special Objective-C classes as types than some of the fundamentals like int and float.

Casting comes up the most in Objective-C when you use some of the older frameworks, such as Core Foundation. Older frameworks tend to have classes for fundamental types that aren’t the ones you’d usually use but that are equivalent. For example, you can freely move between the CFStringRef type (from the Core Foundation framework) and the NSString * type (from Cocoa’s Foundation framework), but to avoid compiler warnings and improve clarity, you should cast when doing so.

9.1.2. Memory management and pointers

You didn’t have to worry at all about how memory was used to store your active data in most web-based languages. Conversely, in C if you’re dynamically changing your data during your program’s runtime, you often do. Memory management is usually done in C through the function’s malloc() and free() methods.

When you specifically allocate memory, you also have to de-allocate it when you’re done. If you don’t, your program will “leak,” which means that it will gradually increase its memory footprint over time due to memory that’s been “lost.”

When you allocate memory, you end up working with memory addresses that lead to your data, rather than the data itself. This is also by default the case with some sorts of data, such as strings. To address this, C introduces the concept of a pointer, wherein a variable refers to a memory address rather than to the data itself. When this is the case, you can dereference the memory address, and thus access your data, with the * character.

For example, the following would define a pointer to an integer:

int *bignumber;

Sometimes you need to do the opposite and get a memory address back from a regular variable. This is done with the & symbol:

int variable = 72;
int *variablepointer = &variable;

This symbol is often used to pass error messages back from a function.

Objective-C Memory Management and Pointers

On the iPhone, memory management is vitally important because of the device’s limited memory. If you’re sloppy with your memory usage, you’ll start receiving didReceivedMemoryWarning messages and eventually your program could get shut down. Objective-C uses the same general concepts of memory allocation and memory deallocation that we’ve already discussed, but it has some specific rules for when you have to worry about freeing up memory yourself. Because these rules are based on functionality of the iPhone OS, we cover them in the next chapter in section 10.4.2.

Although Objective-C objects are generally built using pointers to memory, you don’t have to worry about dereferencing them because the details are hidden by the SDK’s classes. However, when you initially declare objects, you’ll always do so with a *; you’ll constantly be creating pointers to objects.

In addition, you may occasionally run into a library that isn’t built around object-oriented classes. In that situation you’ll need to make full use of pointers. As you’ll see, this is the case with SQLite, which is discussed in chapter 16.

9.1.3. File structure and directives

When you look at the file structure of a complex C program, you’ll see that it includes a variety of files with .c and .h suffixes. The .c files include all the source code: the various functions that you’re accustomed to using in a program, split up in a (hopefully) rational way.

The .h (or header) files, meanwhile, are the tools that allow you to easily integrate the source code from one .c file into the rest of your program. They contain all the declarations for variables that you want to make available outside of specific functions. In addition, they contain function prototypes. These are declarations for your functions that effectively describe a protocol for using them:

float divide(float numerator, float divisor);

Just as header declarations make a variable available outside its own function, function prototypes make a function available outside its own file.

To use a header file, you need the capability to include one file inside another. For example, if you want to access some of the global variables or some of the functions of file2.c in file1.c, you do so by incorporating file2.c’s header file. You do this by inserting an include command into file1.c:

#include "file2.h"

The appropriate file is then inserted as part of the C preprocessor’s work. This is what’s known as a compiler directive, or just a macro.

Objective-C File Structures and Directives

Objective-C replaces .c files with .m or .mm files and replaces the #include directive with #import, but the overall ideas are the same.

9.1.4. Compiling

The final major difference between C and most web-based programming languages is that you must compile it. This means that the human-readable source code is turned into machine-readable object code. The same thing happens to your web programs, but whereas they compile at runtime, C instead compiles in advance, providing for more efficient program startup at the cost of portability. C compilation can be done by a command-line program (like “cc” or “gcc”) or by some fancy integrated development environment (IDE).

Because C programs tend to include many files, they need special instructions to tell the compiler how to put all the code together. This is most frequently done with a makefile, though integrated environments might have their own ways to list what should be used, possibly shielding the user entirely from worrying about this.

Objective-C Compiling

All of these details will be taken care of for you by Xcode, Apple’s development environment. You therefore don’t have to worry about makefiles or how the compiling works. The only catch is that you must remember to always add files (such as databases or images) to your project through Xcode so that they get added in correctly.

9.1.5. Other elements

C is full of other features that may or may not have turned up in your programming language of choice. Among them are symbolic constants (which are permanent declarations, typically used to increase readability), special sorts of loops (such as while and do-while), older-style branching statements (such as goto labels), and some more complex structures (such as unions).

We can’t cover all of these topics with any justice here, so we’ve held ourselves to the big-picture stuff. If you see something unfamiliar in Objective-C code that you’ve been handed, and it looks like it’s a foundational C structure of some sort, we again point you to Kernighan and Ritchie’s definitive book on the topic.

With C now covered in the depth that we can give it, we’re ready to move on to the next major element that will define your Objective-C programming experience: object-oriented programming.

9.2. An introduction to object-oriented programming

C is fundamentally a procedural language, as are early web-based languages like Perl and PHP (though that’s changing for both through current releases). You make calls to functions that do the work of your program. Object-oriented programming (OOP) moves away from this old paradigm. Specifically, there are no longer separate functions and variables; instead, data and commands are bound into a more cohesive whole.

As in our previous section, we’ve created a summary chart of the major elements of object-oriented programming, which you can find in table 9.2.

Table 9.2. Object-oriented programming introduces a number of new concepts.

OOP concept

Summary

Class

A collection of variables and functions that work together

Framework

A collection of class libraries

Inheritance

The way in which a subclass gets variables and functions from its parent

Message

A call sent to an object, telling it to execute a function

Method

A function inside a class, executed by a message

Object

A specific instance of a class

Subclass

A descendent of a class, with some features in common and some variance

If you need more information than what we’ve written here, Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional, 1994) by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides is an influential book that generally talks about OOP, then specifically covers some design patterns usable in it. But you should find all the basics here, starting with a look at the fundamentals of object-oriented programming.

9.2.1. Objects and classes

The central concept in OOP is (as you might guess) the object. Think of it as a super-variable, or (if you prefer) as a concrete, real-world thing—which is what’s actually being modeled in the OOP paradigm.

An object combines values (which Objective-C calls instance variables and properties) and functions (which Objective-C calls methods). These variables and methods are intrinsically tied together. The variables describe the object while the methods give ways to act on it (such as creating, modifying, or destroying the object).

Objects are specific instances of classes. The class is where the variable and method descriptions actually appear. An individual object then takes all of that information, and starts setting its own version of the variables as it sees fit.

Classes gain power because they support inheritance. That means that you can subclass an existing class. Your subclass starts off with all the default variables and methods for its parent class, but you can now supplement or even override them.

It’s frequent for a subclass to override a parent method by first calling the parent method, then doing a few things to vary how it works. For example, if you had a class that represented an eating utensil, it might include a simple method to transfer solid food from your plate to your mouth. If you created a subclass for a spoon, it could include a new method that worked on liquids.

Once you’ve created a hierarchy of classes and subclasses, you can store them away in a class library. When you put several of those together you have a software framework, and that’s what we’ll be working with in the SDK, as Apple has provided numerous frameworks to make your programming of the iPhone easier.

9.2.2. Messaging

If the object is the OOP equivalent of the variable, then the message is the OOP equivalent of the function. To get something done in an object-oriented program, you send a message to a specific object that asks it to execute a specific method. The object then does so internally, using its own variables and reporting its results out to the calling object.

One of the most frequent types of messages that you’ll see in OOP is a call to a method that looks at or changes an object’s variables. A getter is an accessor that looks at data, while a setter is a mutator that changes data (though Apple calls both accessors in some of its documentation).

It’s important to use accessors and mutators because they support the core OOP ideal of encapsulation. The actual variables in objects are hidden away from the rest of the world, freeing up that global namespace, which otherwise could become quite cluttered. If one object uses a foo variable, that no longer impacts the use of a foo variable by another object. Instead, each variable can only be accessed by the methods of its own class.

Some OOP languages support two different types of messages. You might see calls to class methods (where a special class object does general stuff like create an object) or to instance methods (where a specific instance object acts in some way). As you’ll see, this is the case with Objective-C.

Figure 9.1 combines many of the ideas that we’ve talked about so far into a single diagram using a vegetative example.

Figure 9.1. Inheritance and messaging combine to form an intricate network of objects in object-oriented programming.

When we look at the classes that are built into the iPhone OS, we’ll see that there are even more levels of inheritance and overall a much larger web of classes and messages.

That ends our brief overview of object-oriented programming, but there’s one more high-level abstraction that you should be familiar with before you dive into the iPhone SDK: the MVC architectural pattern.

9.3. The Model-View-Controller (MVC) pattern

Programming languages innately have their own philosophies and models that underlie how they work. Encapsulation and inheritance are two of the philosophies that are critical to OOP. A philosophy that’s critical to good Objective-C programming is the Model-View-Controller (MVC) architectural pattern.

This method of software design goes back to 1979, when Trygve Reenskaug—then working on Smalltalk at Xerox PARC—described it. It’s widely available today in OOP frameworks, including the iPhone’s Cocoa Touch, and as libraries for other programming languages.

The MVC pattern breaks a program into three parts. The model is the data at the heart of a program. Meanwhile, the view and the controller together comprise the presentation layer of your application. The view is essentially the user interface side of things, while the controller sits between the view and the model, accepting user input and modifying the other elements appropriately. Figure 9.2 shows what this model looks like.

Figure 9.2. The MVC model covers how user input and other changes affect your program’s design.

In figure 9.2 you can see the core ideal of the controller accepting input and making changes, but note that there will also be direct interaction between the model and the view.

Dynamic web design offers a simple example of an MVC pattern. The model represents your data, usually stored in a database or XML. The view is your HTML page itself. Finally, the controller is your JavaScript, PHP, Perl, or Ruby on Rails code, which accepts the input, kicking out HTML code on one side and modifying the database on the other.

Within Objective-C, you’ll see an even more explicit interpretation of MVC. There are objects specifically called views and view controllers. If you’re following good Objective-C programming practice, you’ll make sure your controllers are accepting input from your view and doing the work themselves.

9.4. Summary

We think it’s entirely possible for someone without object-oriented experience (and even without C experience) to make the transition from creating iPhone-based web pages to creating iPhone-based native apps. We’ve already seen it happen at iPhone development camps. We also think there are good reasons for doing so. As we said back in chapter 2, the SDK and web development can each do different things well, and it’s always best to use the right tool for the job at hand.

We won’t promise that it’ll be easy. The whole idea of objects replacing procedural calls is a pretty big switch in how you do things when programming. When you meet actual Objective-C code, you’ll also see that even with the simplest program you’re going to have several files to work with that each serve very different purposes.

Fortunately you’re going to have four terrific advantages on your side. First, of course, you’ll have this book to help guide you. Second, you’ll have access to the SDK’s programming tools: Xcode and Interface Builder. The first will constantly offer you whatever documentation you need for the objects, methods, and properties you’re using, while the second will provide you with a simple, graphical way to create objects. Third, you’re going to have Objective-C itself on your side. Although its code looks a bit different from most programming languages you’ve worked with, its code is simple, elegant, and overall quite easy to read. Fourth, you’re going to be able to use the iPhone OS’s enormous library of frameworks, making your code even shorter and simpler thanks to many years of development on Apple’s part, just as we already saw with Apple’s Dashcode and web development.

You’re going to be amazed at what you can do in just a few lines of code.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.186