Programming in Objective-C 2.0

The purpose of this book is as its name implies: to teach you how to program in Objective-C 2.0.


Stephen G. Kochan


588 Pages

60460 Reads

96 Downloads

English

PDF Format

5.98 MB

iOS App Development

Download PDF format


  • Stephen G. Kochan   
  • 588 Pages   
  • 21 Feb 2015
  • Page - 1

    Programming in Objective-C 2.0 Stephen G. Kochan Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Cape Town • Sydney • Tokyo • Singapore • Mexico City read more..

  • Page - 2

    Programming in Objective-C 2.0 Copyright © 2009 b y Pearson Education, Inc. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information read more..

  • Page - 3

    read more..

  • Page - 4

    read more..

  • Page - 5

    read more..

  • Page - 6

    ❖ To Roy and Ve, two people whom I dearly miss ❖ read more..

  • Page - 7

    informit.com/devlibrary Developer’s Library ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS Developer’s Library books are designed to provide practicing programmers with unique, high-quality references and tutorials on the programming languages and technologies they use in their daily work. All books in the Developer’s Library are written by expert technology practitioners who are especially read more..

  • Page - 8

    About the Author Stephen Kochan is the author and coauthor of several bestselling titles on the C lan- guage, including Programming in C (Sams, 2004), Programming in ANSI C (Sams, 1994), and Topics in C Programming (Wiley, 1991), and several Unix titles, including Exploring the Unix System (Sams, 1992) and Unix Shell Programming (Sams 2003). He has been pro- gramming on Macintosh read more..

  • Page - 9

    We Want to Hear from You! As the reader of this book, you are our most important critic and commentator.We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. You can email or write me directly to let me know what read more..

  • Page - 10

    read more..

  • Page - 11

    1 Introduction Dennis Ritchie at AT&T Bell Laboratories pioneered the C programming language in the early 1970s. However, this programming language did not begin to gain widespread popularity and support until the late 1970s.This was because, until that time, C compilers were not readily available for commercial use outside of Bell Laboratories. Initially, this growth in popularity was read more..

  • Page - 12

    2 Chapter 1 Introduction When the iPhone was released in 2007, developers clamored for the opportunity to develop applications for this revolutionary device. At first, Apple did not welcome third- party application development.The company’s way of placating wannabe iPhone devel- opers was to allow them to develop web-based applications. A web-based application runs under the iPhone’s read more..

  • Page - 13

    3 How This Book Is Organized depth instructions on how to develop interactive graphical applications with Cocoa.You can learn all that material in greater detail elsewhere, after you’ve learned how to write programs in Objective-C. In fact, mastering that material will be much easier when you have a solid foundation of how to program in Objective-C.This book does not assume read more..

  • Page - 14

    4 Chapter 1 Introduction Chapter 4,“Data Types and Expressions,” describes the basic Objective-C data types and how to use them in your programs. Chapter 5,“Program Looping,” introduces the three looping statements you can use in your programs: for , while , and do . Making decisions is fundamental to any computer programming language. Chapter 6, “Making Decisions,” covers the read more..

  • Page - 15

    5 Acknowledgments card and address book classes. Methods enable you to perform simple operations such as adding and removing address cards from the address book, looking up someone, listing the contents of the address book, and so on. After you’ve learned how to write Objective-C programs, you can go in several direc- tions.You might want to lean more about the underlying C read more..

  • Page - 16

    read more..

  • Page - 17

    Part I The Objective-C 2.0 Language 1 Introduction 2 Programming in Objective-C 3 Classes, Objects, and Methods 4 Data Types and Expressions 5 Program Looping 6 Making Decisions 7 More on Classes 8 Inheritance 9 Polymorphism, Dynamic Typing, and Dynamic Binding 10 More on Variables and Data Types 11 Categories and Protocols 12 The Preprocessor 13 Underlying C Language Features read more..

  • Page - 18

    read more..

  • Page - 19

    2 Programming in Objective-C In this chapter, we dive right in and show you how to write your first Objective-C pro- gram.You won’t work with objects just yet; that’s the topic of the next chapter.We want you to understand the steps involved in keying in a program and compiling and running it.We give special attention to this process both under Windows and on a read more..

  • Page - 20

    10 Chapter 2 Programming in Objective-C Note These tools should be preinstalled on all Macs that came with OS X. If you separately in- stalled OS X, make sure you install the Developer Tools as well. Using Xcode Xcode is a sophisticated application that enables you to easily type in, compile, debug, and execute programs. If you plan on doing serious application development on read more..

  • Page - 21

    11 Compiling and Running Programs Scroll down the left pane until you get to Command Line Utility. In the upper-right pane, highlight Foundation Tool.Your window should now appear as shown in Figure 2.4. Click Choose.This brings up a new window, shown in Figure 2.5. Figure 2.3 Starting a new project: selecting the application type Figure 2.4 Starting a new project: creating a read more..

  • Page - 22

    12 Chapter 2 Programming in Objective-C We’ll call the first program prog1 , so type that into the Save As field.You may want to create a separate folder to store all your projects in. On my system, I keep the projects for this book in a folder called ObjC Progs . Click the Save button to create your new project.This gives you a project window such as the one read more..

  • Page - 23

    13 Compiling and Running Programs Figure 2.6 Xcode prog1 project window Figure 2.7 File prog1.m and edit window read more..

  • Page - 24

    14 Chapter 2 Programming in Objective-C Returning to your Xcode project window, the bottom-right side of the window shows the file called prog1.m and contains the following lines: #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // insert code here... NSLog (@ ”Hello World! ”); [pool drain]; return read more..

  • Page - 25

    15 Compiling and Running Programs Under the Build menu, you can select either Build or Build and Run. Select the latter because that automatically runs the program if it builds without any errors.You can also click the Build and Go icon that appears in the toolbar. Note Build and Go means “Build and then do the last thing I asked you to do,” which might be Run, read more..

  • Page - 26

    16 Chapter 2 Programming in Objective-C 4. Select a name for your project, and optionally a directory to store your project files in. Click Save. 5. In the top-right pane, you will see the file prog1.m (or whatever name you assigned to your project, followed by .m . Highlight that file.Type your program into the edit window that appears directly below that pane. 6. Save the read more..

  • Page - 27

    17 Compiling and Running Programs Figure 2.10 Terminal window Note In the previous example and throughout the remainder of this text, commands that you, the user, enter are indicated in boldface. For Objective-C files, you can choose any name you want; just make sure the last two characters are .m .This indicates to the compiler that you have an Objective-C program. After you’ve read more..

  • Page - 28

    18 Chapter 2 Programming in Objective-C sh: prog1: command not found $ This is the result you’ll probably get unless you’ve used Terminal before.The UNIX shell (which is the application running your program) doesn’t know where prog1 is lo- cated (we don’t go into all the details of this here), so you have two options: One is to precede the name of the program with read more..

  • Page - 29

    19 Explanation of Your First Program A comment statement is used in a program to document a program and enhance its readability. Comments tell the reader of the program—whether it’s the programmer or someone else whose responsibility it is to maintain the program—just what the program- mer had in mind when writing a particular program or a particular sequence of statements. read more..

  • Page - 30

    20 Chapter 2 Programming in Objective-C In Program 2.1, this line specifies that the name of the program is main : int main (int argc, const char *argv[]) main is a special name that indicates precisely where the program is to begin execu- tion.The reserved word int that precedes main specifies the type of value main returns, which is an integer (more about that soon).We read more..

  • Page - 31

    21 Explanation of Your First Program You must terminate all program statements in Objective-C with a semicolon (;).This is why a semicolon appears immediately after the closed parenthesis of the NSLog call. Before you exit your program, you should release the allocated memory pool (and ob- jects that are associated with it) with a line such as the following: [pool drain]; Again, read more..

  • Page - 32

    22 Chapter 2 Programming in Objective-C If you type in Program 2.2 and then compile and execute it, you can expect the fol- lowing output (again, without showing the text that NSLog normally prepends to the out- put): Program 2.2 Output Programming is fun! Programming in Objective-C is even more fun! As you will see from the next program example, you don’t need to make a read more..

  • Page - 33

    23 Displaying the Values of Variables Program 2.4 #import <Foundation/Foundation.h> int main (int argc, const char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int sum; sum = 50 + 25; NSLog (@ ”The sum of 50 and 25 is %i ”, sum); [pool drain]; return 0; } Program 2.4 Output The sum of 50 and 25 is 75 The first program statement inside main after read more..

  • Page - 34

    24 Chapter 2 Programming in Objective-C The percent character inside the first argument is a special character recognized by the NSLog function.The character that immediately follows the percent sign specifies what type of value is to be displayed at that point. In the previous program, the NSLog routine recognizes the letter i as signifying that an integer value is to be read more..

  • Page - 35

    25 Exercises The call to the NSLog routine now contains four arguments. Once again, the first argu- ment, commonly called the format string, describes to the system how the remaining argu- ments are to be displayed.The value of value1 is to be displayed immediately following the phrase “The sum of.” Similarly, the values of value2 and sum are to be printed at the points read more..

  • Page - 36

    26 Chapter 2 Programming in Objective-C 4. Write a program that subtracts the value 15 from 87 and displays the result, together with an appropriate message. 5. Identify the syntactic errors in the following program.Then type in and run the corrected program to make sure you have identified all the mistakes: #import <Foundation/Foundation.h> int main (int argc, const char read more..

  • Page - 37

    3 Classes, Objects, and Methods In this chapter, you’ll learn about some key concepts in object-oriented programming and start working with classes in Objective-C.You’ll need to learn a little bit of terminol- ogy, but we keep it fairly informal.We also cover only some of the basic terms here be- cause you can easily get overwhelmed. Refer to Appendix A,“Glossary,” at read more..

  • Page - 38

    28 Chapter 3: Classes, Objects, and Methods Instances and Methods A unique occurrence of a class is an instance, and the actions that are performed on the in- stance are called methods. In some cases, a method can be applied to an instance of the class or to the class itself. For example, washing you car applies to an instance (in fact, all the methods listed in Table read more..

  • Page - 39

    29 Instances and Methods You send a message to the Car class (the receiver of the message) asking it to give you a new car.The resulting object (which represents your unique car) is then stored in the variable yourCar . From now on, yourCar can be used to refer to your instance of the car, which you got from the factory. Because you went to the factory to get the read more..

  • Page - 40

    30 Chapter 3: Classes, Objects, and Methods An Objective-C Class for Working with Fractions Now it’s time to define an actual class in Objective-C and learn how to work with in- stances of the class. Once again, you’ll learn procedure first. As a result, the actual program examples might not seem very practical.We get into more practical stuff later. Suppose you need to read more..

  • Page - 41

    31 An Objective-C Class for Working with Fractions It would be better if you could define a fraction as a single entity and collectively refer to its numerator and denominator with a single name, such as myFraction .You can do that in Objective-C, and it starts by defining a new class. Program 3.2 duplicates the functionality of Program 3.1 using a new class called Fraction read more..

  • Page - 42

    32 Chapter 3: Classes, Objects, and Methods @end //---- program section ---- int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *myFraction; // Create an instance of a Fraction myFraction = [Fraction alloc]; myFraction = [myFraction init]; // Set fraction to 1/3 [myFraction setNumerator: 1]; [myFraction setDenominator: 3]; // Display the read more..

  • Page - 43

    33 The @interface Section Each of these sections is a part of every Objective-C program, even though you might not need to write each section yourself. As you’ll see, each section is typically put in its own file. For now, however, we keep it all together in a single file. The @interface Section When you define a new class, you have to do a few things. First, you read more..

  • Page - 44

    34 Chapter 3: Classes, Objects, and Methods n i n myLocation n numberOfMoves n _sysFlag n ChessBoard On the other hand, the following names are not valid for the stated reasons: n sum$value $ —is not a valid character. n piece flag —Embedded spaces are not permitted. n 3Spencer —Names can’t start with a number. n int —This is a reserved word. int cannot be used as a variable read more..

  • Page - 45

    35 The @interface Section int denominator; } -(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d; @end The name of the new class (NewClassName) is Fraction , and its parent class is NSObject . (We talk in greater detail about parent classes in Chapter 8,“Inheritance.”) The NSObject class is defined in the file NSObject.h , which is automatically included in read more..

  • Page - 46

    36 Chapter 3: Classes, Objects, and Methods new instance of the class.This is similar to manufacturing a new car, in that the car is the class and you want to create a new one, which would be a class method. An instance method performs some operation on a particular instance of a class, such as setting its value, retrieving its value, displaying its value, and so on. read more..

  • Page - 47

    37 The @implementation Section will be returned.This is similar for setDenominator , except that the name of its argu- ment is d . Notice the syntax of the declaration for these methods. Each method name ends with a colon, which tells the Objective-C compiler that the method expects to see an argu- ment. Next, the type of the argument is specified, enclosed in a set of read more..

  • Page - 48

    38 Chapter 3: Classes, Objects, and Methods return type, and its arguments and their types. However, instead of the line ending with a semicolon, the code for the method follows, enclosed inside a set of curly braces. Consider the @implementation section from Program 3.2: //---- @implementation section ---- @implementation Fraction –(void) print { NSLog ( “%i/%i”, numerator, denominator); } read more..

  • Page - 49

    39 The @program Section Fraction *myFraction; // Create an instance of a Fraction myFraction = [Fraction alloc]; myFraction = [myFraction init]; // Set fraction to 1/3 [myFraction setNumerator: 1]; [myFraction setDenominator: 3]; // Display the fraction using the print method NSLog (@ ”The value of myFraction is: ”); [myFraction print]; [myFraction release]; [pool drain]; return 0; } Inside read more..

  • Page - 50

    40 Chapter 3: Classes, Objects, and Methods mean that the object has been properly initialized for use.You need to initialize an object after you allocate it. This is done with the next statement in Program 3.2, which reads as follows: myFraction = [myFraction init]; Again, you are using a method here that you didn’t write yourself.The init method initializes the instance of a read more..

  • Page - 51

    41 The program Section The first message statement sends the setNumerator: message to myFraction .The ar- gument that is supplied is the value 1 . Control is then sent to the setNumerator: method you defined for your Fraction class.The Objective-C system knows that it is the method from this class to use because it knows that myFraction is an object from the Fraction class. Inside read more..

  • Page - 52

    42 Chapter 3: Classes, Objects, and Methods rely on garbage collection when programming for certain platforms on which garbage collection is not supported, such as the iPhone. For that reason, we don’t talk about garbage collection until much later in this book. It seems as if you had to write a lot more code to duplicate in Program 3.2 what you did in Program read more..

  • Page - 53

    43 The @program Section denominator = d; } @end //---- program section ---- int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *frac1 = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // Set 1st fraction to 2/3 [frac1 setNumerator: 2]; [frac1 setDenominator: 3]; // Set 2nd fraction to 3/7 [frac2 setNumerator: 3]; read more..

  • Page - 54

    44 Chapter 3: Classes, Objects, and Methods Object Instance Variables frac1 numerator 2 denominator 3 frac2 numerator 3 denominator 7 Figure 3.2 Unique instance variables value 3 . Each time you create a new object, it gets its own distinct set of instance vari- ables. Figure 3.2 depicts this. Based on which object is getting sent the message, the correct instance variables are read more..

  • Page - 55

    45 Accessing Instance Variables and Data Encapsulation –(int) denominator { return denominator; } Note that the names of the methods and the instance variables they access are the same.There’s no problem doing this; in fact, it is common practice. Program 3.4 tests your two new methods. Program 3.4 // Program to access instance variables – cont’d #import <Foundation/Foundation.h> read more..

  • Page - 56

    46 Chapter 3: Classes, Objects, and Methods -(int) denominator { return denominator; } @end //---- program section ---- int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *myFraction = [[Fraction alloc] init]; // Set fraction to 1/3 [myFraction setNumerator: 1]; [myFraction setDenominator: 3]; // Display the fraction using our two new read more..

  • Page - 57

    47 Exercises We should also point out that there’s also a method called new that combines the ac- tions of an alloc and init . So this line could be used to allocate and initialize a new Fraction : Fraction *myFraction = [Fraction new]; It’s generally better to use the two-step allocation and initialization approach so you conceptually understand that two distinct events are read more..

  • Page - 58

    48 Chapter 3: Classes, Objects, and Methods 6. In a procedural language such as C, you think about actions and then write code to perform the action on various objects. Referring to the car example, you might write a procedure in C to wash a vehicle and then inside that procedure write code to handle washing a car, washing a boat, washing a motorcycle, and so on. If read more..

  • Page - 59

    4 Data Types and Expressions In this chapter, we take a look at the basic data types and describe some fundamental rules for forming arithmetic expressions in Objective-C. Data Types and Constants You have already been exposed to the Objective-C basic data type int . As you will recall, a variable declared to be of type int can be used to contain integral values only—that read more..

  • Page - 60

    50 Chapter 4 Data Types and Expressions the digits, and values larger than 999 cannot be expressed using commas. (So the value 12,000 is not a valid integer constant and must be written as 12000 .) Two special formats in Objective-C enable integer constants to be expressed in a base other than decimal (base 10). If the first digit of the integer value is 0 , the integer read more..

  • Page - 61

    51 Data Types and Constants Type float You can use a variable declared to be of type float to store values containing decimal places. A floating-point constant is distinguished by the presence of a decimal point.You can omit digits before the decimal point or digits after the decimal point, but, obviously, you can’t omit both.The values 3. , 125.8 , and -.0001 are all valid read more..

  • Page - 62

    52 Chapter 4 Data Types and Expressions ond is a semicolon, and the third is the character zero—which is not the same as the number zero. Do not confuse a character constant, which is a single character enclosed in single quotes, with a C-style character string, which is any number of characters enclosed in double quotes. As mentioned in the last chapter, a string of read more..

  • Page - 63

    53 Data Types and Constants doubleVar = 8.440000e+11 doubleVar = 8.44e+11 charVar = 'W' In the second line of the program’s output, notice that the value of 331.79 , which is as- signed to floatingVar , is actually displayed as 331.790009 .The reason for this inaccuracy is the particular way in which numbers are internally represented inside the computer.You have probably come read more..

  • Page - 64

    54 Chapter 4 Data Types and Expressions A long double constant is written as a floating constant with an l or L immediately following, like so: 1.234e+7L To display a long double , you use the L modifier. So %Lf would display a long dou- ble value in floating-point notation, %Le would display the same value in scientific nota- tion, and %Lg would tell NSLog to choose between read more..

  • Page - 65

    55 Data Types and Constants The signed qualifier can be used to explicitly tell the compiler that a particular vari- able is a signed quantity. Its use is primarily in front of the char declaration, and further discussion is beyond the scope of this book. Type id The id data type is used to store an object of any type. In a sense, it is a generic object type. For read more..

  • Page - 66

    56 Chapter 4 Data Types and Expressions Arithmetic Expressions In Objective-C, just as in virtually all programming languages, the plus sign (+) is used to add two values, the minus sign (-) is used to subtract two values, the asterisk (*)is used to multiply two values, and the slash (/) is used to divide two values.These opera- tors are known as binary arithmetic operators read more..

  • Page - 67

    57 Arithmetic Expressions result = a + b * c; //precedence NSLog (@ ”a + b * c = %i ”, result); NSLog (@ ”a * b + c * d = %i ”, a * b + c * d); [pool drain]; return 0; } Program 4.2 Output a - b = 98 b * c = 50 a / c = 4 a + b * c = 150 a * b + c * d = 300 After declaring the integer variables a , b , c , d , and read more..

  • Page - 68

    58 Chapter 4 Data Types and Expressions a + b * c as follows: a + (b * c) (This is the same way this expression would be evaluated if you applied the basic rules of algebra.) If you want to alter the order of evaluation of terms inside an expression, you can use parentheses. In fact, the expression listed previously is a perfectly valid Objective-C expres- sion.Thus, read more..

  • Page - 69

    59 Arithmetic Expressions NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int a = 25; int b = 2; int result; float c = 25.0; float d = 2.0; NSLog (@ ”6 + a / 5 * b = %i ”, 6 + a / 5 * b); NSLog (@ ”a / b * b = %i ”, a / b * b); NSLog (@ ”c / d * d = %f ”, c / d * d); NSLog (@ ”-a = %i ”, -a); [pool read more..

  • Page - 70

    60 Chapter 4 Data Types and Expressions If you glance back at the declarations for the variables a and b , you will recall that both were declared to be of type int .Whenever a term to be evaluated in an expression con- sists of two integers, the Objective-C system performs the operation using integer arith- metic. In such a case, all decimal portions of numbers are read more..

  • Page - 71

    61 Arithmetic Expressions int a = 25, b = 5, c = 10, d = 7; NSLog (@ ”a %% b = %i ”, a % b); NSLog (@ ”a %% c = %i ”, a % c); NSLog (@ ”a %% d = %i ”, a % d); NSLog (@ ”a / d * d + a %% d = %i ”, a / d * d + a % d); [pool drain]; return 0; } Program 4.4 Output a % b = 0 a % c = 5 a % d = 4 a / d * d + read more..

  • Page - 72

    62 Chapter 4 Data Types and Expressions Integer and Floating-Point Conversions To effectively develop Objective-C programs, you must understand the rules used for the implicit conversion of floating-point and integer values in Objective-C. Program 4.5 demonstrates some of the simple conversions between numeric data types. Program 4.5 // Basic conversions in Objective-C #import read more..

  • Page - 73

    63 Arithmetic Expressions ger portion, or 123 , is stored in i1 .The first line of the program’s output verifies that this is the case. Assigning an integer variable to a floating variable does not cause any change in the value of the number; the system simply converts the value and stores it in the floating variable.The second line of the program’s output verifies that read more..

  • Page - 74

    64 Chapter 4 Data Types and Expressions because the effect of casting a floating value to an integer is one of truncating the float- ing-point value.The expression (float) 6 / (float) 4 produces a result of 1.5 , as does the following expression: (float) 6 / 4 The type cast operator is often used to coerce an object that is a generic id type into an object of a read more..

  • Page - 75

    65 A Calculator Class erator has higher precedence than the assignment operator. In fact, all operators but the comma operator have higher precedence than the assignment operators, which all have the same precedence. In this case, this expression is identical to the following: a = a / (b + c) The motivation for using assignment operators is threefold. First, the program state- read more..

  • Page - 76

    66 Chapter 4 Data Types and Expressions accumulator = value; } -(void) clear { accumulator = 0; } -(double) accumulator { return accumulator; } -(void) add: (double) value { accumulator += value; } -(void) subtract: (double) value { accumulator -= value; } -(void) multiply: (double) value { accumulator *= value; } -(void) divide: (double) value { accumulator /= value; } @end int main (int argc, read more..

  • Page - 77

    67 Bit Operators Program 4.6 Output The result is 50 The Calculator class has only one instance variable, a double value that holds the value of the accumulator.The method definitions themselves are quite straightforward. Notice the message that invokes the multiply method: [deskCalc multiply: 5]; The argument to the method is an integer, yet the method expects a double . No prob- read more..

  • Page - 78

    68 Chapter 4 Data Types and Expressions All the operators listed in Table 4.2, with the exception of the ones complement opera- tor (~), are binary operators and, as such, take two operands. Bit operations can be per- formed on any type of integer value but cannot be performed on floating-point values. The Bitwise AND Operator When two values are ANDed, the binary read more..

  • Page - 79

    69 Bit Operators The Bitwise Inclusive-OR Operator When two values are bitwise Inclusive-ORed in Objective-C, the binary representation of the two values is once again compared bit by bit.This time, each bit that is a 1 in the first value or a 1 in the second value will produce a 1 in the corresponding bit of the re- sult.The truth table for the Inclusive-OR operator is read more..

  • Page - 80

    70 Chapter 4 Data Types and Expressions If w1 and w2 , were set equal to hexadecimal 5e and d6 , respectively, the result of w1 Ex- clusive-ORed with w2 would be hexadecimal e8 , as illustrated: w1 0000 0000 0101 1110 0x5e w2 0000 0000 1011 0110 ^ 0xd6 ———————————————————————————————————— 0000 read more..

  • Page - 81

    71 Bit Operators int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; unsigned int w1 = 0xA0A0A0A0, w2 = 0xFFFF0000, w3 = 0x00007777; NSLog (@ ”%x %x %x ”, w1 & w2, w1 | w2, w1 ^ w2); NSLog (@ ”%x %x %x ”, ~w1, ~w2, ~w3); NSLog (@ ”%x %x %x ”, w1 ^ w1, w1 & ~w2, w1 | w2 | w3); NSLog (@ ”%x %x ”, w1 | w2 read more..

  • Page - 82

    72 Chapter 4 Data Types and Expressions will result in 3 being shifted one place to the left, which will result in 6 being assigned to w1 : w1 ... 0000 0011 0x03 w1 << 1 ... 0000 0110 0x06 The operand on the left of the << operator is the value to be shifted, while the operand on the right is the number of bit positions the read more..

  • Page - 83

    73 Exercises integers in 32 bits, for example, shifting an integer to the left or right by 32 or more bits is not guaranteed to produce a defined result in your program.You should also note that if you shift a value by a negative amount, the result is similarly undefined. Types: _Bool , _Complex , and _Imaginary Before leaving this chapter, we should mention three read more..

  • Page - 84

    74 Chapter 4 Data Types and Expressions 4. Write a program to evaluate the polynomial shown here: 3x 3 - 5x 2 + 6 for x = 2.55 5. Write a program that evaluates the following expression and displays the results (re- member to use exponential format to display the result): (3.31 x 10 -8 x + 2.01 x 10 -7) / (7.16 x 10 -6 + 2.01 x 10 -8) 6. Complex numbers are numbers read more..

  • Page - 85

    75 Exercises 8. Modify the add: , subtract: , multiply: , and divide: methods from Program 4.6 to return the resulting value of the accumulator.Test the new methods. 9. After completing exercise 8, add the following methods to the Calculator class and test them: -(double) changeSign; // change sign of accumulator -(double) reciprocal; // 1/accumulator -(double) xSquared; // read more..

  • Page - 86

    read more..

  • Page - 87

    Figure 5.1 Triangle arrangement example 5 Program Looping In Objective-C, you can repeatedly execute a sequence of code in several ways.These looping capabilities are the subject of this chapter, and they consist of the following: n The for statement n The while statement n The do statement We start with a simple example: counting numbers. If you were to arrange 15 marbles into the read more..

  • Page - 88

    78 Chapter 5 Program Looping Program 5.1 #import <Foundation/Foundation.h> // Program to calculate the eighth triangular number int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int triangularNumber; triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8; NSLog (@ ”The eighth triangular number is %i ”, triangularNumber); [pool drain]; read more..

  • Page - 89

    79 The for Statement { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int n, triangularNumber; triangularNumber = 0; for ( n = 1; n <= 200; n = n + 1 ) triangularNumber += n; NSLog (@ ”The 200th triangular number is %i ”, triangularNumber); [pool drain]; return 0; } Program 5.2 Output The 200th triangular number is 20100 Some explanation is needed for Program 5.2.The method read more..

  • Page - 90

    80 Chapter 5 Program Looping Table 5.1 Relational Operators Operator Meaning Example == Equal to count == 10 != Not equal to flag != DONE < Less than a < b <= Less than or equal to low <= high > Greater than points > POINT_MAX >= Greater than or equal to j >= 0 This expression can be read as “n less than or equal to 200.” The “less than or equal to” read more..

  • Page - 91

    81 The for Statement Returning to the previous example, the program statement that forms the body of the for loop—triangularNumber += n; —is repetitively executed as long as the result of the relational test is TRUE , or, in this case, as long as the value of n is less than or equal to 200 . This program statement has the effect of adding the value of n to the read more..

  • Page - 92

    82 Chapter 5 Program Looping int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int n, triangularNumber; NSLog (@ ”TABLE OF TRIANGULAR NUMBERS ””); NSLog (@ ” n Sum from 1 to n ”); NSLog (@ ”-- -------- ””); triangularNumber = 0; for ( n = 1; n <= 10; ++n ) { triangularNumber += n; NSLog (@ ” %i %i read more..

  • Page - 93

    83 The for Statement execute not just a single program statement, but a group of program statements? This can be accomplished by enclosing all such program statements within a pair of braces.The system then treats this group, or block, of statements as a single entity. In general, any place in a Objective-C program that a single statement is permitted, a block of statements read more..

  • Page - 94

    84 Chapter 5 Program Looping can be equivalently expressed using the decrement operator, like so: --bean_counter Some programmers prefer to put the ++ or -- after the variable name, as in n++ or bean_counter-- .This is acceptable and is a matter of personal preference. You might have noticed that the last line of output from Program 5.3 doesn’t line up. You can correct this read more..

  • Page - 95

    85 The for Statement the correct number of times.You would also have to change the NSLog statement to dis- play the correct message. An easier solution might be to somehow have the program ask you which triangular number you want to calculate.Then, after you had given your answer, the program could calculate the desired triangular number.You can effect such a solution by read more..

  • Page - 96

    86 Chapter 5 Program Looping could have just as easily typed in the number 10 or 30 , for example, if he or she wanted to calculate those particular triangular numbers. The first NSLog statement in Program 5.4 is used to prompt the user to type in a num- ber. Of course, it is always nice to remind the user of what you want entered. After the message is printed, the read more..

  • Page - 97

    87 The for Statement int n, number, triangularNumber, counter; for ( counter = 1; counter <= 5; ++counter ) { NSLog (@ ”What triangular number do you want? ”); scanf ( “%i”, &number); triangularNumber = 0; for ( n = 1; n <= number; ++n ) triangularNumber += n; NSLog (@ ”Triangular number %i is %i ”, number, triangularNumber); } [pool drain]; return 0; } Program 5.5 read more..

  • Page - 98

    88 Chapter 5 Program Looping This specifies that the program loop is to be executed precisely five times.The value of counter is initially set to 1 and is incremented by 1 until it is no longer less than or equal to 5 (in other words, until it reaches 6 ). Unlike the previous program examples, the variable counter is not used anywhere else within the program. Its read more..

  • Page - 99

    89 The while Statement sets up two index variables: i and j , which initialize to 0 and 100 , respectively, before the loop begins. Each time after the body of the loop is executed, the value of i is incre- mented by 1 and the value of j is decremented by 10. Just as you might need to include more than one expression in a particular field of the for statement, read more..

  • Page - 100

    90 Chapter 5 Program Looping is again evaluated. If the result of the evaluation is TRUE , the program statement is again executed.This process continues until expression finally evaluates FALSE , at which point the loop is terminated. Execution of the program then continues with the statement that follows program statement . As an example of its use, the following program sets up a read more..

  • Page - 101

    91 The while Statement for ( init_expression; loop_condition; loop_expression ) program statement can be equivalently expressed in the form of a while statement, like so: init_expression; while ( loop_condition ) { program statement loop_expression; } When you become familiar with the use of the while statement, you will gain a bet- ter feel for when it seems more logical to use a while read more..

  • Page - 102

    92 Chapter 5 Program Looping { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; unsigned int u, v, temp; NSLog (@ ”Please type in two nonnegative integers. ”); scanf ( “%u%u”, &u, &v); while ( v != 0 ) { temp = u % v; u = v; v = temp; } NSLog (@ ”Their greatest common divisor is %u ”, u); [pool drain]; return 0; } Program 5.7 Output Please type in read more..

  • Page - 103

    93 The while Statement To write such a program, you first must come up with an algorithm that accomplishes the stated task. Frequently, analyzing your own method for solving the problem leads to an algorithm. For the task of reversing the digits of a number, the solution can be simply stated as “successively read the digits of the number from right to left.” You can read more..

  • Page - 104

    94 Chapter 5 Program Looping Program 5.8 Output Enter your number. 13579 9 7 5 3 1 The do Statement The two looping constructs discussed thus far in this chapter both test the conditions be- fore the loop is executed.Therefore, the body of the loop might never be executed if the conditions are not satisfied.When developing programs, you sometimes want to have the test made at read more..

  • Page - 105

    95 The break Statement NSLog (@ ”Enter your number. ”); scanf ( “%i”, &number); do { right_digit = number % 10; NSLog (@ ”%i”, right_digit); number /= 10; } while ( number != 0 ); [pool drain]; return 0; } Program 5.9 Output Enter your number. 135 5 3 1 Program 5.9 Output (Rerun) Enter your number. 0 0 As you can see from the program’s output, when 0 is keyed into the read more..

  • Page - 106

    96 Chapter 5 Program Looping The format of the break statement is simply the keyword break followed by a semi- colon, like so: break; The continue Statement The continue statement is similar to the break statement, except that it doesn’t cause the loop to terminate. At the point that the continue statement is executed, any statements that appear after the continue statement up to read more..

  • Page - 107

    97 Exercises 4. A minus sign placed in front of a field width specification causes the field to be dis- played left-justified. Substitute the following NSLog statement for the correspon- ding statement in Program 5.2, run the program, and compare the outputs produced by both programs: NSLog (@ ”%-2i %i ”, n, triangularNumber); 5. Program 5.5 allows the user to type in only five read more..

  • Page - 108

    read more..

  • Page - 109

    6 Making Decisions A fundamental feature of any programming language is its capability to make decisions. Decisions were made when executing the looping statements to determine when to ter- minate a loop.The Objective-C programming language also provides several other deci- sion-making constructs, which are covered in this chapter: n The if statement n The switch statement n The conditional read more..

  • Page - 110

    100 Chapter 6: Making Decisions An actual program example will help drive the point home. Suppose you want to write a program that accepts an integer entered from the keyboard and then displays the absolute value of that integer. A straightforward way to calculate the absolute value of an integer is to simply negate the number if it is less than zero.The phrase “if it read more..

  • Page - 111

    101 The if Statement dence so that you know it is indeed working correctly, but at least you know that you have checked both possible outcomes of the program’s decision. After a message is displayed to the user and the integer value that is entered is stored in number , the program tests the value of number to see whether it is less than zero. If it is, the read more..

  • Page - 112

    102 Chapter 6: Making Decisions We arbitrarily decided to return 0.0 if the denominator of the fraction is zero. Other options are available (such as printing an error message, throwing an exception, and so on), but we won’t go into them here. Let’s put this new method to use in Program 6.2. Program 6.2 #import <Foundation/Foundation.h> @interface Fraction: NSObject { int read more..

  • Page - 113

    103 The if Statement return denominator; } -(double) convertToNum { if (denominator != 0) return (double) numerator / denominator; else return 0.0; } @end int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *aFraction = [[Fraction alloc] init]; Fraction *bFraction = [[Fraction alloc] init]; [aFraction setNumerator: 1]; // 1st fraction is 1/4 read more..

  • Page - 114

    104 Chapter 6: Making Decisions After setting aFraction to 1/4 , the program uses the convertToNum method to con- vert the fraction to a decimal value.This value is then displayed as 0.25 . In the second case, the value of bFraction is not explicitly set, so its numerator and denominator are initialized to zero, which is the default for instance variables.This ex- plains the read more..

  • Page - 115

    105 The if Statement if ( remainder != 0 ) NSLog (@ ”The number is odd. ”); [pool drain]; return 0; } Program 6.3 Output Enter your number to be tested: 2455 The number is odd. Program 6.3 Output (Rerun) Enter your number to be tested: 1210 The number is even. After the number is typed in, the remainder after division by 2 is calculated.The first if statement tests the read more..

  • Page - 116

    106 Chapter 6: Making Decisions Program 6.4 // Determine if a number is even or odd (Ver. 2) #import <Foundation/Foundation.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int number_to_test, remainder; NSLog (@ ”Enter your number to be tested: ”); scanf ( “%i”, &number_to_test); remainder = number_to_test % 2; if ( remainder == read more..

  • Page - 117

    107 The if Statement such a case, you would want to compare the value of a grade not merely against one limit, but against the two limits 70 and 79 to ensure that it fell within the specified range. The Objective-C language provides the mechanisms necessary to perform these types of compound relational tests. A compound relational test is simply one or more simple rela- read more..

  • Page - 118

    108 Chapter 6: Making Decisions terms, it becomes a relatively straightforward task to translate it into a program statement, as follows: if ( (rem_4 == 0 && rem_100 != 0) || rem_400 == 0 ) NSLog (@ ”It’s a leap year. ”); The parentheses around the following subexpression are not required: rem_4 == 0 && rem_100 != 0 This is because the expression will be read more..

  • Page - 119

    109 The if Statement Program 6.5 Output (Rerun) Enter the year to be tested: 2000 It ’s a leap year. Program 6.5 Output (Rerun) Enter the year to be tested: 1800 Nope, it ’s not a leap year. The previous examples use a year that is not a leap year because it isn’t evenly divisible by 4 (1955), a year that is a leap year because it is evenly divisible by 400 read more..

  • Page - 120

    110 Chapter 6: Making Decisions message is sent only if both the game is not done and it’s your turn. In fact, this statement could have been equivalently formulated using compound relationals, like so: if ( [chessGame isOver] == NO && [chessGame whoseTurn] == YOU ) [chessGame yourMove]; A more practical example of nested if statements might involve adding an else clause to the read more..

  • Page - 121

    111 The if Statement if ( [chessGame whoseTurn] == YOU ) [chessGame yourMove]; else [chessGame finish]; This is because the else clause is associated with the last un-elsed if .You can use braces to force a different association when an innermost if does not contain an else but an outer if does.The braces have the effect of closing off the if statement.Thus, the fol- lowing read more..

  • Page - 122

    112 Chapter 6: Making Decisions The preceding construct is so frequently used that it is generally referred to as an else if construct and is usually formatted differently from that shown previously: if ( expression 1 ) program statement 1 else if ( expression 2 ) program statement 2 else program statement 3 This latter method of formatting improves the readability of the statement read more..

  • Page - 123

    113 The if Statement Program 6.6 Output (Rerun) Please type in a number: -158 Sign = -1 Program 6.6 Output (Rerun) Please type in a number: 0 Sign = 0 If the number that is entered is less than zero, sign is assigned the value -1 ; if the number is equal to zero, sign is assigned the value 0 ; otherwise, the number must be greater than zero, so sign is assigned the read more..

  • Page - 124

    114 Chapter 6: Making Decisions Program 6.7 Output Enter a single character: & It ’s a special character. Program 6.7 Output (Rerun) Enter a single character: 8 It ’s a digit. Program 6.7 Output (Rerun) Enter a single character: B It ’s an alphabetic character. The first test that is made after the character is read in determines whether the char variable c is an alphabetic read more..

  • Page - 125

    115 The if Statement Let’s suppose for the next example that you want to write a program that allows the user to type in simple expressions of the following form:[[STYLE_FIRST]] number operator number The program will evaluate the expression and display the results at the terminal.The operators you want to have recognized are the normal operators for addition, subtraction, read more..

  • Page - 126

    116 Chapter 6: Making Decisions -(void) clear { accumulator = 0; } -(double) accumulator { return accumulator; } -(void) add: (double) value { accumulator += value; } -(void) subtract: (double) value { accumulator -= value; } -(void) multiply: (double) value { accumulator *= value; } -(void) divide: (double) value { accumulator /= value; } @end int main (int argc, char *argv[]) { NSAutoreleasePool * read more..

  • Page - 127

    117 The if Statement [deskCalc subtract: value2]; else if ( operator == ‘*’ ) [deskCalc multiply: value2]; else if ( operator == ‘/’ ) [deskCalc divide: value2]; NSLog (@ ”%.2f”, [deskCalc accumulator]); [deskCalc release]; [pool drain]; return 0; } Program 6.8 Output Type in your expression. 123.5 + 59.3 182.80 Program 6.8 Output (Rerun) Type in your expression. 198.7 / 26 7.64 read more..

  • Page - 128

    118 Chapter 6: Making Decisions the calculator to perform the operation. In the last NSLog , the value of the accumulator is retrieved for display. Execution of the program is then complete. A few words about program thoroughness are in order at this point. Although the pre- ceding program does accomplish the task that we set out to perform, the program is not really read more..

  • Page - 129

    119 The if Statement [deskCalc subtract: value2]; else if ( operator == ‘*’ ) [deskCalc multiply: value2]; else if ( operator == ‘/’ ) if ( value2 == 0 ) NSLog (@ ”Division by zero. ”); else [deskCalc divide: value2]; else NSLog (@ ”Unknown operator. ”); NSLog (@ ”%.2f”, [deskCalc accumulator]); [deskCalc release]; [pool drain]; return 0; } Program 6.8A Output Type in your read more..

  • Page - 130

    120 Chapter 6: Making Decisions A better way to handle the division-by-zero problem is to perform the test inside the method that handles division.You can modify your divide: method as shown here: -(void) divide: (double) value { if (value != 0.0) accumulator /= value; else { NSLog (@ ”Division by zero. ”); accumulator = 99999999.; } } If value is nonzero, you perform the read more..

  • Page - 131

    121 The switch Statement break; } The expression enclosed within parentheses is successively compared against the val- ues value1 , value2 , ... , valuen , which must be simple constants or constant expressions. If a case is found whose value is equal to the value of expression , the program statements that follow the case are executed. Note that when more than one such program read more..

  • Page - 132

    122 Chapter 6: Making Decisions Program 6.9 // Program to evaluate simple expressions of the form // value operator value #import <Foundation/Foundation.h> // Insert interface and implementation sections for // Calculator class here int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; double value1, value2; char operator; read more..

  • Page - 133

    123 Boolean Variables Program 6.9 Output Type in your expression. 178.99 - 326.8 -147.81 After the expression has been read in, the value of operator is successively compared against the values specified by each case.When a match is found, the statements contained inside the case are executed.The break statement then sends execution out of the switch statement, where execution of the read more..

  • Page - 134

    124 Chapter 6: Making Decisions Program 6.10 // Program to generate a table of prime numbers #import <Foundation/Foundation.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int p, d, isPrime; for ( p = 2; p <= 50; ++p ) { isPrime = 1; for ( d = 2; d < p; ++d ) if ( p % d == 0 ) isPrime = 0; if ( isPrime != read more..

  • Page - 135

    125 Boolean Variables are currently testing to see whether it is prime.The first statement in the loop assigns the value 1 to the variable isPrime .The use of this variable will become apparent shortly. A second loop is set up to divide p by the integers 2 through p-1 . Inside the loop, a test is performed to see whether the remainder of p divided by d is 0 . If read more..

  • Page - 136

    126 Chapter 6: Making Decisions actually proceeds as follows:The relational expression number < 0 is evaluated. If the condition is satisfied—that is, if number is less than 0 —the value of the expression is 1 ; otherwise, its value is 0 . The if statement tests the result of the expression evaluation. If the result is nonzero, the statement that immediately follows is executed; read more..

  • Page - 137

    127 Boolean Variables A couple of built-in features in Objective-C make working with Boolean variables a little easier. One is the special type BOOL , which can be used to declare variables that will contain either a true or a false value.The other is the built-in values YES and NO . Using these predefined values in your programs can make them easier to write and read.Take read more..

  • Page - 138

    128 Chapter 6: Making Decisions 19 23 29 31 37 41 43 47 The Conditional Operator Perhaps the most unusual operator in the Objective-C language is one called the condi- tional operator. Unlike all other operators in Objective-C—which are either unary or bi- nary operators—the conditional operator is a ternary operator; that is, it takes three operands.The two symbols used to denote read more..

  • Page - 139

    129 The Conditional Operator If the value of x is not less than zero, the expression immediately following the : is evaluated and assigned to s . So if x is greater than or equal to zero, the value of x * x ,or x2 , is assigned to s . As another example of the conditional operator, the following statement assigns to the variable max_value the maximum of a and b : read more..

  • Page - 140

    130 Chapter 6: Making Decisions 4. Write a program that acts as a simple printing calculator.The program should allow the user to type in expressions of the following form: number operator The program should recognize the following operators: + - * / S E The S operator tells the program to set the accumulator to the typed-in number, and the E operator read more..

  • Page - 141

    131 Exercises (Remember to display zero if the user types in just 0.) Note:This exercise is a hard one! 7. Program 6.10 has several inefficiencies. One inefficiency results from checking even numbers. Because any even number greater than 2 obviously cannot be prime, the program could simply skip all even numbers as possible primes and as possible divi- sors.The inner for loop is read more..

  • Page - 142

    read more..

  • Page - 143

    7 More on Classes In this chapter, you’ll continue learning how to work with classes and write methods. You’ll also apply some of the concept you learned in the previous chapter, such as com- pleting program looping, making deci ions, and working with expr s ions. First we talk about splitting your program into multiple files to make working with larger programs easier. read more..

  • Page - 144

    134 Chapter 7 More on Classes Figure 7.1 Xcode New File menu. Note that this file does not include the definition of the Fraction class. However, it does import a file called Fraction.h . Typically, a class declaration (that is, the @interface section) is placed in its own file, called class.h .The definition (that is, the @implementation section) is normally placed in a file of read more..

  • Page - 145

    135 Separate Interface and Implementation Files Figure 7.2 Adding a new class to your project. Figure 7.3 Xcode creates files for the new class. In that same file (Fraction.h), you will now enter your interface section for the Fraction class, as shown in Program 7.1: read more..

  • Page - 146

    136 Chapter 7 More on Classes Program 7.2 Interface File Fraction.h // // Fraction.h // FractionTest // // Created by Steve Kochan on 7/5/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> // The Fraction class @interface Fraction : NSObject { int numerator; int denominator; } -(void) print; -(void) setNumerator: (int) read more..

  • Page - 147

    137 Separate Interface and Implementation Files @implementation Fraction -(void) print { NSLog (@ ”%i/%i”, numerator, denominator); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(int) numerator { return numerator; } -(int) denominator { return denominator; } -(double) convertToNum { if (denominator != 0) return (double) numerator / denominator; read more..

  • Page - 148

    138 Chapter 7 More on Classes they tell the compiler where to look for the specified file.When you use double quotes, the compiler typically looks for the specified file first inside your current directory and then in a list of other places. If necessary, you can specify the actual places for the com- piler to search. Here is the test program for our example, which we read more..

  • Page - 149

    139 Synthesized Accessor Methods This builds an executable file called FractionTest . Here’s the output after running the program: Program 7.1 FractionTest Output The value of myFraction is: 1/3 Synthesized Accessor Methods As of Objective-C 2.0, you can have your setter and getter methods (collectively known as accessor methods) automatically generated for you.We haven’t shown you how read more..

  • Page - 150

    140 Chapter 7 More on Classes { NSLog (@ ”%i/%i”, numerator, denominator); } -(double) convertToNum { if (denominator != 0) return (double) numerator / denominator; else return 1.0; } @end The following line tells the Objective-C compiler to generate a pair of getter and set- ter methods for each of the two listed instance variables, numerator and denominator : @synthesize numerator, read more..

  • Page - 151

    141 Multiple Arguments to Methods You can use a similar syntax to assign values as well: instance.property = value This is equivalent to writing the following expression:[instance setProperty: value] In Program 7.1 you set the numerator and denominator of your fraction to 1/3 using the following two lines of code: [myFraction setNumerator: 1]; [myFraction setDenominator: 3]; Here’s an read more..

  • Page - 152

    142 Chapter 7 More on Classes Program 7.2 Interface File: Fraction.h #import <Foundation/Foundation.h> // Define the Fraction class @interface Fraction : NSObject { int numerator; int denominator; } @property int numerator, denominator; -(void) print; -(void) setTo: (int) n over: (int) d; -(double) convertToNum; @end Next, add the definition for the new method to the read more..

  • Page - 153

    143 Multiple Arguments to Methods The new setTo:over: method simply assigns its two integer arguments, n and d ,to the corresponding instance variables for the fraction, numerator , and denominator . Here’s a test program to try your new method. Program 7.2 Test File: FractionTest.m #import “Fraction.h” int main (int argc, char *argv[]) { Fraction *aFraction = [[Fraction alloc] init]; read more..

  • Page - 154

    144 Chapter 7 More on Classes It’s generally not good programming style to omit argument names when writing new methods because it makes the program harder to follow and makes the purpose of the method’s actual parameters less intuitive. Operations on Fractions Let’s continue to work with the Fraction class. First, you’ll write a method that will en- able you to add one read more..

  • Page - 155

    145 Multiple Arguments to Methods Don’t forget that you can refer to the Fraction that is the receiver of the message by its fields: numerator and denominator . On the other hand, you can’t directly refer to the instance variables of the argument f that way. Instead, you have to obtain them by apply- ing the dot operator to f (or by sending an appropriate message read more..

  • Page - 156

    146 Chapter 7 More on Classes The test program is straightforward enough.Two Fraction s, called aFraction and bFraction , are allocated and initialized.Then they are set to the values 1/4 and 1/2 ,re- spectively. Next, the Fraction bFraction is added to the Fraction aFraction ; the re- sult of the addition is then displayed. Note again that the add: method adds the argument to the read more..

  • Page - 157

    147 Local Variables been declaring inside your main routine; those variables were also local to main and could be accessed directly only from within the main routine. None of the methods you devel- oped could directly access those variables defined in main . Local variables have no default initial value, so you must set them to some value before using them.The three local read more..

  • Page - 158

    148 Chapter 7 More on Classes The following code sequence might appear inside a showPage method that wanted to keep track of the number of times it was invoked (or, in this case, perhaps the number of pages that have been printed, for example): -(void) showPage { static int pageCount = 0; ... ++pageCount; ... } The local static variable would be set to 0 only once when the read more..

  • Page - 159

    149 The self Keyword NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *aFraction = [[Fraction alloc] init]; Fraction *bFraction = [[Fraction alloc] init]; [aFraction setTo: 1 over: 4]; // set 1st fraction to 1/4 [bFraction setTo: 1 over: 2]; // set 2nd fraction to 1/2 [aFraction print]; NSLog (@ ”+”); [bFraction print]; NSLog (@ ”=”); [aFraction add: read more..

  • Page - 160

    150 Chapter 7 More on Classes know how to identify instance variables inside a method directly by name, but we don’t know how to directly identify the receiver of the message. You can use the keyword self to refer to the object that is the receiver of the current method. If inside your add: method you wrote [self reduce]; the reduce method would be applied to the read more..

  • Page - 161

    151 Allocating and Returning Objects from Methods [result setTo: resultNum over: resultDenom]; [result reduce]; return result; } The first line of your method definition is this: -(Fraction *) add: (Fraction *) f; It says that your add: method will return a Fraction object and that it will take one as its argument as well.The argument will be added to the receiver of the message, read more..

  • Page - 162

    152 Chapter 7 More on Classes [aFraction setTo: 1 over: 4]; // set 1st fraction to 1/4 [bFraction setTo: 1 over: 2]; // set 2nd fraction to 1/2 [aFraction print]; NSLog (@ ”+”); [bFraction print]; NSLog (@ ”=”); resultFaction = [aFraction add: bFraction]; [resultFraction print]; // This time give the result directly to print // memory leakage here! [[aFraction add: read more..

  • Page - 163

    153 Allocating and Returning Objects from Methods main .The add: method allocated it, but it’s still your responsibility to clean it up.The fol- lowing message expression might look nice, but it actually creates a problem: [[aFraction add: bFraction] print]; Because you take the Fraction that add: returns and send it a message to print ,you have no way of subsequently releasing read more..

  • Page - 164

    154 Chapter 7 More on Classes Fraction *aFraction = [[Fraction alloc] init]; Fraction *sum = [[Fraction alloc] init], *sum2; int i, n, pow2; [sum setTo: 0 over: 1]; // set 1st fraction to 0 NSLog (@ ”Enter your value for n: ”); scanf ( “%i”, &n); pow2 = 2; for (i = 1; i <= n; ++i) { [aFraction setTo: 1 over: pow2]; sum2 = [sum add: aFraction]; [sum release]; read more..

  • Page - 165

    155 Allocating and Returning Objects from Methods 0 ?).The program then prompts the user to enter a value for n and reads it using scanf . You then enter a for loop to calculate the sum of the series. First, you initialize the vari- able pow2 to 2 .This variable is used to store the value of 2i . Each time through the loop, its value is multiplied by 2. The for read more..

  • Page - 166

    156 Chapter 7 More on Classes You might not need to work with fractions, but these examples have shown how you can continually refine and extend a class by adding new methods.You could hand this in- terface file to someone else working with fractions, and it would be sufficient for that person to be able to write programs to deal with fractions. If that person needed read more..

  • Page - 167

    root class subclass NSObject Fraction Figure 8.1 Root and subclass 8 Inheritance In this chapter, you’ll learn about one of the key principles that makes object-oriented programming so powerful.Through the concept of inheritance, you will build on existing class definitions and customize them for your own applications. It All Begins at the Root You learned about the idea of a parent read more..

  • Page - 168

    158 Chapter 8 Inheritance From a terminology point of view, we can speak of classes, child classes, and parent classes. Analogously, we can talk about classes, subclasses, and superclasses.You should be- come familiar with both types of terminology. Whenever a new class (other than a new root class) is defined, the class inherits certain properties. For example, all the instance read more..

  • Page - 169

    159 It All Begins at the Root superclass superclass subclass subclass NSObject ClassA ClassB Figure 8.2 Subclasses and superclasses Class Instance Variables Methods NSObject ClassA ClassB x x initVar initVar printVar Figure 8.3 Inheriting instance variables and methods. -(void) printVar; @end @implementation ClassB -(void) printVar { NSLog (@ ”x = %i ”, read more..

  • Page - 170

    160 Chapter 8 Inheritance Program 8.1 // Simple example to illustrate inheritance #import <Foundation/Foundation.h> // ClassA declaration and definition @interface ClassA: NSObject { int x; } -(void) initVar; @end @implementation ClassA -(void) initVar { x = 100; } @end // Class B declaration and definition @interface ClassB : ClassA -(void) printVar; @end @implementation ClassB -(void) printVar { read more..

  • Page - 171

    161 It All Begins at the Root Program 8.1 Output x = 100 You begin by defining b to be a ClassB object. After allocating and initializing b ,you send a message to apply the initVar method to it. But looking back at the definition of ClassB , you’ll notice that you never defined such a method. initVar was defined in ClassA , and because ClassA is the parent of ClassB read more..

  • Page - 172

    162 Chapter 8 Inheritance how to respond to such a method. Again, this was determined after checking ClassB ’s methods and its parents’ methods back to the root class (which, in this case, is NSObject ). In some cases, a message is not generated if the method is not found.This involves us- ing something known as forwarding, which is briefly discussed in Chapter read more..

  • Page - 173

    163 Extension Through Inheritance: Adding New Methods -(int) area { return width * height; } -(int) perimeter { return (width + height) * 2; } @end Each method definition is straightforward enough. Program 8.2 shows a main routine to test it. Program 8.2 #import “Rectangle h ” #import <stdio.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] read more..

  • Page - 174

    164 Chapter 8 Inheritance Suppose that you now need to work with squares.You could define a new class called Square and define similar methods in it as in your Rectangle class. Alternately, you could recognize the fact that a square is just a special case of a rectangle whose width and height just happen to be the same. Thus, an easy way to handle this is to make a read more..

  • Page - 175

    165 Extension Through Inheritance: Adding New Methods So setSide: calls the setWidth:andHeight: method from the Rectangle class, passing the parameter s as the value for both the width and the height.You don’t really have to do anything else. Someone working with a Square object can now set the dimensions of the square by using setSide: and can take advantage of the methods read more..

  • Page - 176

    166 Chapter 8 Inheritance myRect (x 1, y 1) (x,y) (0,0) Figure 8.4 A rectangle drawn in a window A Point Class and Memory Allocation The Rectangle class stores only the rectangle’s dimensions. In a real-world graphical ap- plication, you might need to keep track of all sorts of additional information, such as the rectangle’s fill color, line color, location (origin) inside a read more..

  • Page - 177

    167 Extension Through Inheritance: Adding New Methods int width; int height; XYPoint *origin; } ... It seems reasonable to add a method to set the rectangle’s origin and to retrieve it.To illustrate an important point, we’re won’t synthesize the accessor methods for the origin now. Instead, we’ll write them ourselves. The @class Directive Now you can work with rectangles read more..

  • Page - 178

    168 Chapter 8 Inheritance Using the @class directive is more efficient because the compiler doesn’t need to process the entire XYPoint.h file (even though it is quite small); it just needs to know that XYPoint is the name of a class. If you need to reference one of the XYPoint classes meth- ods, the @class directive does not suffice because the compiler would need more read more..

  • Page - 179

    169 Extension Through Inheritance: Adding New Methods Program 8.4 XYPoint.m Implementation File #import “XYPoint.h” @implementation XYPoint @synthesize x, y; -(void) setX: (int) xVal andY: (int) yVal { x = xVal; y = yVal; } @end Program 8.4 Rectangle.h Interface File #import <Foundation/Foundation.h> @class XYPoint; @interface Rectangle: NSObject { int width; int height; XYPoint *origin; } read more..

  • Page - 180

    170 Chapter 8 Inheritance { width = w; height = h; } –(void) setOrigin: (Point *) pt { origin = pt; } –(int) area { return width * height; } –(int) perimeter { return (width + height) * 2; } –(Point *) origin { return origin; } @end Program 8.4 Test Program #import “Rectangle.h” #import “XYPoint.h” int main (int argc, char *argv[]) { NSAutoreleasePool * pool = read more..

  • Page - 181

    171 Extension Through Inheritance: Adding New Methods NSLog (@ ”Origin at (%i, %i) ”, myRect.origin.x, myRect.origin.y); NSLog (@ ”Area = %i, Perimeter = %i ”, [myRect area], [myRect perimeter]); [myRect release]; [myPoint release]; [pool drain]; return 0; } Program 8.4 Output Rectangle w = 5, h = 8 Origin at (100, 200) Area = 40, Perimeter = 26 Inside the main routine, you read more..

  • Page - 182

    172 Chapter 8 Inheritance 100 200 x y myPoint Figure 8.5 The XYPoint myPoint in memor y [myPoint setX: 100 andY: 200]; [myRect setWidth: 5 andHeight: 8]; myRect.origin = myPoint; NSLog (@ ”Origin at (%i, %i) ”, myRect.origin.x, myRect.origin.y); [myPoint setX: 50 andY: 50]; NSLog (@ ”Origin at (%i, %i) ”, myRect.origin.x, myRect.origin.y); [myRect release]; [myPoint release]; [pool drain]; read more..

  • Page - 183

    173 Extension Through Inheritance: Adding New Methods 100 200 x y myPoint pt Figure 8.6 Passing the rectangle’s origin to the method That value stored inside myPoint , which is a pointer into memory, is copied into the local variable pt as defined inside the method. Now both pt and myPoint reference the same data stored in memory. Figure 8.6 illustrates this. When the origin read more..

  • Page - 184

    174 Chapter 8 Inheritance Figure 8.8 Compiler error messages [origin setX: pt.x andY: pt.y]; sets the newly allocated XYPoint to the x, y coordinate of the argument to the method. Study this message expression until you fully understand how it works. The change to the setOrigin: method means that each Rectangle instance now owns its origin XYPoint instance. Even though it is now read more..

  • Page - 185

    175 Overriding Methods That’s better.This time, changing the value of myPoint to (50, 50) inside main had no effect on the rectangle’s origin because a copy of the point was created inside the Rectangle ’s setOrigin: method. Incidentally, we didn’t synthesize the origin methods here because the synthesized set- ter setOrigin: method would have behaved just like the one you read more..

  • Page - 186

    176 Chapter 8 Inheritance @end // ClassB declaration and definition @interface ClassB: ClassA -(void) initVar; -(void) printVar; @end @implementation ClassB -(void) initVar // added method { x = 200; } -(void) printVar { NSLog (@ ”x = %i ”, x); } @end int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; ClassB *b = [[ClassB alloc] init]; read more..

  • Page - 187

    177 Overriding Methods Class Instance Variables Methods Object ClassA ClassB x x initVar initVar printVar Figure 8.9 Overriding the initVar method Which Method Is Selected? We covered how the system searches up the hierarchy for a method to apply to an object. If you have methods in different classes with the same name, the correct method read more..

  • Page - 188

    178 Chapter 8 Inheritance @interface ClassA: NSObject { int x; } -(void) initVar; @end Notice that no printVar method is declared.That method is declared and defined in ClassB .Therefore, even though ClassB objects and their descendants can use this method through inheritance, ClassA objects cannot because the method is defined farther down in the hierarchy. Note You can coerce the use of read more..

  • Page - 189

    179 Overriding Methods Program 8.7 Output x = 100 x = 200 Now we can talk about the actual example. First, a and b are defined to be ClassA and ClassB objects, respectively. After allocation and initialization, a message is sent to a asking it to apply the initVar method.This method is defined in the definition of ClassA ,so this method is selected.The method simply sets the read more..

  • Page - 190

    180 Chapter 8 Inheritance when used inside a method invokes the release method that is defined in (or inherited by) the parent class.The method is invoked on the receiver of the message—in other words, on self . Therefore, the strategy for overriding the dealloc method for your Rectangle class is to first release the memory taken up by your origin and then invoke the read more..

  • Page - 191

    181 Extension Through Inheritance: Adding New Instance Variables myRect.origin = endPoint; ... [startPoint release]; [endPoint release]; [myRect release]; The copy of the XYPoint startPoint stored in the origin member of myRect will not be released because it is overwritten by the second origin (endPoint) that is stored there.That origin is released properly when the rectangle itself is read more..

  • Page - 192

    182 Chapter 8 Inheritance Note Of course, it also has instance variables that it inherits from the NSObject class, but we choose to ignore this detail for now. Let’s put this together in a simple example to illustrate this concept (see Program 8.8). Program 8.8 // Extension of instance variables #import <Foundation/Foundation.h> // Class A declaration and definition @interface read more..

  • Page - 193

    183 Abstract Classes NSLog (@ ”x = %i ”, x); NSLog (@ ”y = %i ”, y); } @end int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; ClassB *b = [[ClassB alloc] init]; [b initVar ; // uses overriding method in ClassB [b printVar]; // reveal values of x and y; [b release]; [pool drain]; return 0; } Program 8.8 Output x = 200 y read more..

  • Page - 194

    184 Chapter 8 Inheritance floating-point numbers typically have different storage requirements. Separate subclasses of NSNumber exist for each numeric type. Because these subclasses, unlike their abstract superclasses, actually exist, they are known as concrete subclasses. Each concrete subclass falls under the NSNumber class umbrella and is collectively referred to as a cluster.When you send a read more..

  • Page - 195

    185 Exercises Write methods to set and retrieve the variables defined previously. Make the Rectangle class a subclass of GraphicObject . Define new classes, Circle and Triangle , which are also subclasses of GraphicObject . Write methods to set and retrieve the various parameters for these objects and also to calculate the circle’s circumference and area, and the triangle’s read more..

  • Page - 196

    read more..

  • Page - 197

    9 Polymorphism, Dynamic Typing, and Dynamic Binding In this chapter, you’ll learn about the features of the Objective-C language that make it such a powerful programming language and that distinguish it from some other object- oriented programming languages such as C++.This chapter describes three key concepts: polymorphism, dynamic typing, and dynamic binding. Polymorphism enables programs read more..

  • Page - 198

    188 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding You should have completed the implementation section for this class in Exercise 6 from Chapter 4,“Data Types and Expressions.”We added an additional setReal:andImaginary: method to enable you to set both the real and imaginary parts of your number with a single message and also synthesized accessor methods.This is shown read more..

  • Page - 199

    189 Polymorphism: Same Name, Different Class NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *f1 = [[Fraction alloc] init]; Fraction *f2 = [[Fraction alloc] init]; Fraction *fracResult; Complex *c1 = [[Complex alloc] init]; Complex *c2 = [[Complex alloc] init]; Complex *compResult; [f1 setTo: 1 over: 10]; [f2 setTo: 2 over: 15]; [c1 setReal: 18.0 andImaginary: 2.5]; [c2 read more..

  • Page - 200

    190 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding Program 9.1 Output 18 + 2.5i + -5 + 3.2i --------- 13 + 5.7i 1/10 + 2/15 ---- 7/30 Note that both the Fraction and Complex classes contain add: and print methods. So when executing the message expressions compResult = [c1 add: c2]; [compResult print]; how does the system know which methods to execute? It’s simple:The read more..

  • Page - 201

    191 Dynamic Binding and the id Type Note Before leaving this section, note that both the Fraction and Complex classes should be re- sponsible for releasing the results that are produced by their add: methods, and not the test program. In fact, these objects should be autoreleased. We’ll talk about that more in Chapter 18, “Copying Objects.” Dynamic Binding and the id Type read more..

  • Page - 202

    192 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding Program 9.2 Output 2/5 10 + 2.5i The variable dataValue is declared as an id object type.Therefore, dataValue can be used to hold any type of object in the program. Note that no asterisk is used in the decla- ration line: id dataValue; The Fraction f1 is set to 2/5 , and the Complex number c2 is set to (10 + read more..

  • Page - 203

    193 Compile Time Versus Runtime Checking drawn is stored inside an id variable called currentObject , for example, you could paint it on the screen simply by sending it the draw message: [currentObject draw]; You could even test it first to ensure that the object stored in currentObject actually responds to a draw method.You’ll see how to do that later in this chapter, in the read more..

  • Page - 204

    194 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding method setReal:andImaginary: is one of the methods defined for the class Fraction . Because it’s not, the error message shown previously is issued and the program is termi- nated. The id Data Type and Static Typing If an id data type can be used to store any object, why don’t you just declare all your ob- jects read more..

  • Page - 205

    195 Asking Questions About Classes Argument and Return Types with Dynamic Typing If you use dynamic typing to invoke a method, note the following rule: If a method with the same name is implemented in more than one of your classes, each method must agree on the type of each argument and the type of value it returns so that the compiler can generate the correct code read more..

  • Page - 206

    196 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding Table 9.1 Methods for Working with Dynamic Types Method Question or Action -(BOOL) isKindOfClass: class-object Is the object a member of class-object or a descendant? -(BOOL) isMemberOfClass: class-object Is the object a member of class-object? -(BOOL) respondsToSelector: selector Can the object respond to the method speci- fied by read more..

  • Page - 207

    197 Asking Questions About Classes To see if my Fraction class, you test the result from the expression, like this: [myFract isMemberOfClass: [Fraction class]] To generate one of the so-called selectors listed in Table 9.1, you apply the @selector directive to a method name. For example, the following produces a value of type SEL for the method named alloc , which you know read more..

  • Page - 208

    198 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding Note You can also catch an error by overriding the doesNotRecognize: method. This method is invoked whenever an unrecognized message is sent to a class and is passed the unrecog- nized selector as its argument. You can employ other strategies as well:You can forward the message to someone else to handle using the read more..

  • Page - 209

    199 Asking Questions About Classes NSLog (@ ”mySquare is a kind of NSObject ”); // respondsTo: if ( [mySquare respondsToSelector: @selector (setSide:)] == YES ) NSLog (@ ”mySquare responds to setSide: method ”); if ( [mySquare respondsToSelector: @selector (setWidth:andHeight:)] == YES ) NSLog (@ ”mySquare responds to setWidth:andHeight: method ”); if ( [Square respondsToSelector: @selector read more..

  • Page - 210

    200 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding the inheritance hierarchy.Thus, mySquare is a member of the Square class—but it’s also “kind of ” a Square , Rectangle , and NSObject because it exists in that class hierarchy (obviously, all objects should return YES for the isKindOf: test on the NSObject class, unless you’ve defined a new root object). The read more..

  • Page - 211

    201 Exception Handling Using @try You can go ahead and run the program despite the warning messages you receive. If you do, you can expect to see your program terminate abnormally with errors similar to these: Program 9.4 Output -[Fraction noSuchMethod]: unrecognized selector sent to instance 0x103280 *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: read more..

  • Page - 212

    202 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *f = [[Fraction alloc] init]; @try { [f noSuchMethod]; } @catch (NSException *exception) { NSLog(@ ”Caught %@%@ ”, [exception name], [exception reason]); } NSLog (@ ”Execution continues! ”); [f release]; [pool drain]; return 0; } Program 9.5 Output *** -[Fraction read more..

  • Page - 213

    203 Exercises Exercises 1. What will happen if you insert the message expression [compResult reduce]; into Program 9.1 after the addition is performed (but before compResult is re- leased)? Try it and see. 2. Can the id variable dataValue , as defined in Program 9.2, be assigned a Rectangle object as you defined it in Chapter 8? That is, is the statement dataValue = [[Rectangle read more..

  • Page - 214

    6. Modify the Calculator class you developed in the exercise from Chapter 4 so that division is done in an @try block. If the division throws an exception, log an error message and continue program execution. 204 Chapter 9 Polymorphism, Dynamic Typing, and Dynamic Binding read more..

  • Page - 215

    10 More on Variables and Data Types In this chapter, we go into more detail about variable scope, initialization methods for objects, and data types. The initialization of an object deserves some special attention, which we give it here. We talked briefly about the scope of instance variables as well as static and local vari- ables in Chapter 7,“More on Classes.”We talk read more..

  • Page - 216

    206 Chapter 10 More on Variables and Data Types A class that contains many methods and instance variables in it commonly has several initialization methods as well. For example, the Foundation framework’s NSArray class contains the following six initialization methods: initWithArray: initWithArray:copyItems: initWithContentsOfFile: initWithContentsOfURL: initWithObjects: initWithObjects:count: An array might read more..

  • Page - 217

    207 Scope Revisited Program 10.1 tests your new initWith:: initialization method. Program 10.1 #import “Fraction.h” int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *a, *b; a = [[Fraction alloc] initWith: 1: 3]; b = [[Fraction alloc] initWith: 3: 7]; [a print]; [b print]; [a release]; [b release]; [pool drain]; return 0; } Program 10.1 read more..

  • Page - 218

    208 Chapter 10 More on Variables and Data Types Directives for Controlling Instance Variable Scope You know by now that instance variables have scope that is limited to the instance meth- ods defined for the class. So any instance method can access its instance variables directly by name, without having to do anything special. You also know that instance variables are read more..

  • Page - 219

    209 Scope Revisited good programming practice because it defeats the concept of data encapsulation (that is, a class hiding its instance variables). External Variables If you write the statement int gMoveNumber = 0; at the beginning of your program—outside any method, class definition, or function—its value can be referenced from anywhere in that module. In such a case, we say read more..

  • Page - 220

    210 Chapter 10 More on Variables and Data Types When dealing with external variables, you can declare a variable as extern in many places, but you can define it only once. Consider a small program example to illustrate the use of external variables. Suppose we have defined a class called Foo , and we type the following code into a file called main.m : #import “Foo.h” read more..

  • Page - 221

    211 Scope Revisited ing the code that accesses the variable, the individual extern declarations are not re- quired. Static Variables The example just shown goes against the notion of data encapsulation and good object- oriented programming techniques. However, you might need to work with variables whose values are shared across different method invocations. Even though it might not make read more..

  • Page - 222

    212 Chapter 10 More on Variables and Data Types +(int) count; Notice that the inherited alloc method wasn’t overridden here; instead, you defined your own allocator method.Your method will take advantage of the inherited alloc method. Place this code in your Fraction.m implementation file: static int gCounter; @implementation Fraction +(Fraction *) allocF { extern int gCounter; ++gCounter; read more..

  • Page - 223

    213 Storage Class Specifiers Program 10.2 #import “Fraction.h” int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Fraction *a, *b, *c; NSLog (@ ”Fractions allocated: %i ”, [Fraction count]); a = [[Fraction allocF] init] b = [[Fract on allocF] init] c = [[Fraction allocF] init]; NSLog (@ ”Fractions allocated: %i ”, [Fraction count]); [a read more..

  • Page - 224

    214 Chapter 10 More on Variables and Data Types This declares index to be an automatic local variable, meaning that it automatically is allocated when the block (which can be a curly-braced sequence of statements, a method, or a function) is entered and is automatically deallocated when the block is exited. Be- cause this is the default inside a block, the statement int index; read more..

  • Page - 225

    215 Enumerated Data Types being modified in between, simply remove the first assignment from the program.To pre- vent this from happening, you declare outPort to be a volatile variable, like this: volatile char *outPort; Enumerated Data Types The Objective-C language enables you to specify a range of values that can be assigned to a variable. An enumerated data type definition is read more..

  • Page - 226

    216 Chapter 10 More on Variables and Data Types enum boolean { no = 0, false = 0, yes = 1, true = 1 }; assigning either the value no or false to an enum boolean variable assigns it the value 0 ; assigning either yes or true assigns it the value 1 . As another example of an enumerated data type definition, the following defines the type enum month , with permissible read more..

  • Page - 227

    217 Enumerated Data Types switch (amonth) { case january: case march: case may: case july: case august: case october: case december: days = 31; break; case april: case june: case september: case november: days = 30; break; case february: days = 28; break; default: NSLog (@ ”bad month number ”); days = 0; break; } if ( days != 0 ) NSLog (@ ”Number of days is %i ”, days); if ( read more..

  • Page - 228

    218 Chapter 10 More on Variables and Data Types You can explicitly assign an integer value to an enumerated data type variable; you should do this using the type cast operator.Therefore, if monthValue were an integer vari- able that had the value 6 , for example, this expression would be permissible: lastMonth = (enum month) (monthValue - 1); If you don’t use the type cast read more..

  • Page - 229

    219 The typedef Statement them to be of type int in the traditional fashion would not have made the intended use of these variables clear. The following typedef defines a type named NumberObject to be a Number object: typedef Number *NumberObject; Variables subsequently declared to be of type NumberObject , as in NumberObject myValue1, myValue2, myResult; are treated as if they were read more..

  • Page - 230

    220 Chapter 10 More on Variables and Data Types ... } This actually tests whether the result from the compare: method is zero. Data Type Conversions Chapter 4,“Data Types and Expressions,” briefly addressed the fact that sometimes the system implicitly makes conversions when expressions are evaluated.You examined a case with the data types float and int .You saw how an operation read more..

  • Page - 231

    221 Data Type Conversions 7. If this step is reached, both operands are of type int , and that is the type of the result. This is actually a simplified version of the steps involved in converting operands in an expression.The rules get more complicated when unsigned operands are involved. For the complete set of rules, see Appendix B,“Objective-C Language Summary.” Realize from read more..

  • Page - 232

    222 Chapter 10 More on Variables and Data Types to a long int .Whenever an unsigned integer is converted to an integer of a larger size, no sign extension occurs, as you would expect. On some machines (such as on on the Intel processors used in the current Macintosh line of computers as well as on the ARM processors currenly used in the iPhone and iTouch), characters are read more..

  • Page - 233

    223 Exercises 5. Using typedef , define a type called FractionObj that enables you to write state- ments such as the following: FractionObj f1 = [[Fraction alloc] init], f2 = [[Fraction alloc] init]; 6. Based on the following definitions float f = 1.00; short int i = 100; long int l = 500L; double d = 15.00; and the seven teps outlined in his chapter for read more..

  • Page - 234

    read more..

  • Page - 235

    11 Categories and Protocols In this chapter, you’ll learn about how to add methods to a class in a modular fashion through the use of categories and how to create a standardized list of methods for others to implement. Categories Sometimes you might be working with a class definition and want to add some new methods to it. For example, you might decide for your Fraction read more..

  • Page - 236

    226 Chapter 11 Categories and Protocols #import <stdio.h> // Define the Fraction class @interface Fraction : NSObject @property int numerator, denominator; -(void) setTo: (int) n over: (int) d; -(Fraction *) add: (Fraction *) f; -(void) reduce; -(double) convertToNum; -(void) print; @end Next, let’s remove the add: method from this interface section and add it to a new read more..

  • Page - 237

    227 Categories you could define your category’s methods in a separate implementation section. In such a case, the implementation section for these methods must also identify the category to which the methods belong. As with the interface section, you do this by enclosing the category name inside parentheses after the class name, like this: @implementation Fraction (MathOps) // code read more..

  • Page - 238

    228 Chapter 11 Categories and Protocols // To sub two fractions: // a/b - c/d = ((a*d) - (b*c)) / (b * d) Fraction *result = [[Fraction alloc] init]; int resultNum, resultDenom; resultNum = (numerator * f.denominator) - (denominator * f.numerator); resultDenom = denominator * f.denominator; [result setTo: resultNum over: resultDenom]; [result reduce]; return result; } -(Fraction read more..

  • Page - 239

    229 Categories [result print]; NSLog (@ ”\n”); [result release]; [a print]; NSLog (@ ” - ”); [b print]; NSLog (@ ”-----”); result = [a sub: b]; [result print]; NSLog (@ ”\n”); [result release]; [a print]; NSLog (@ ” * ”); [b print]; NSLog (@ ”-----”); result = [a mul: b]; [result print]; NSLog (@ ”\n”); [result release]; [a print]; NSLog (@ ” / ”); [b print]; read more..

  • Page - 240

    230 Chapter 11 Categories and Protocols Realize once again that it is certainly legal in Objective-C to write a statement such as this: [[a div: b] print]; This line directly prints the result of dividing Fraction a by b and thereby avoids the intermediate assignment to the variable result , as was done in Program 11.1. However, you need to perform this intermediate assignment read more..

  • Page - 241

    231 Protocols The new methods you add to an existing class through a category can serve your pur- poses just fine, but they might be inconsistent with the original design or intentions of the class.Turning a Square into a Circle (admittedly, an exaggeration), for example, by adding a new category and some methods muddies the definition of the class and is not good programming read more..

  • Page - 242

    232 Chapter 11 Categories and Protocols If you adopt the NSCopying protocol in your class, you must implement a method called copyWithZone: .You tell the compiler that you are adopting a protocol by listing the protocol name inside a pair of angular brackets (<...>) on the @interface line.The protocol name comes after the name of the class and its parent class, as in the read more..

  • Page - 243

    233 Protocols Note Note the use of the @optional directive here. Any methods that are listed following that di- rective are optional. That is, an adopter of the Drawing protocol does not have to implement the outline method to conform to the protocol. (And you can subsequently switch back to listing required methods by using the @required directive inside the protocol definition.) So read more..

  • Page - 244

    234 Chapter 11 Categories and Protocols This is a compiler check here, so assigning an id variable to currentObject would not generate this message because the compiler has no way of knowing whether the object stored inside an id variable conforms to the Drawing protocol. You can list more than one protocol if the variable will hold an object conforming to more than one read more..

  • Page - 245

    235 Composite Objects under a name.This can help somewhat from the point of documentation and modulariza- tion of methods. The class that declares the informal protocol doesn’t implement the methods in the class itself, and a subclass that chooses to implement the methods needs to redeclare them in its interface section, as well as implement one or more of them. Unlike formal read more..

  • Page - 246

    236 Chapter 11 Categories and Protocols -(int) perimeter; @end The Square class is defined here with four methods. Unlike the subclass version, which gives you direct access to the Rectangle ’s methods (setWidth:, setHeight: , setWidth:andHeight: , width , and height ), those methods are not in this definition for a Square .That makes sense here because those methods really don’t read more..

  • Page - 247

    237 Exercises 3. Extend the Fraction class by adding methods that conform to the informal proto- col NSComparisonMethods , as listed earlier in this chapter. Implement the first six methods from that protocol (isEqualTo:, isLessThanOrEqualTo:, is- LessThan:, isGreaterThanOrEqualTo:, isGreaterThan:, isNotEqualTo:) and test them. 4. The functions sin () , cos () , and tan () are part of the read more..

  • Page - 248

    read more..

  • Page - 249

    12 The Preprocessor The preprocessor provides the tools that enable you to develop programs that are easier to develop, read, modify, and port to different systems.You can also use the preprocessor to literally customize the Objective-C language to suit a particular programming application or your own programming style. The preprocessor is a part of the Objective-C compilation process read more..

  • Page - 250

    240 Chapter 12 The Preprocessor defines the name FALSE and makes its subsequent use in the program equivalent to speci- fying the value 0 .Therefore, the statement gameOver = FALSE; assigns the value of FALSE to gameOver , and the statement if ( gameOver == FALSE ) ... compares the value of gameOver against the defined value of FALSE . A defined name is not a variable.Therefore, read more..

  • Page - 251

    241 The #define Statement Assigning a constant to a symbolic name frees you from having to remember the par- ticular constant value every time you want to use it in a program. Furthermore, if you ever need to change the value of the constant (if perhaps you found out that you were us- ing the wrong value, for example), you would have to change the value in only read more..

  • Page - 252

    242 Chapter 12 The Preprocessor literally substitutes 2.0 * 3.141592654 whenever the defined name TWO_PI occurs in the program. The fact that the preprocessor performs a literal text substitution whenever the defined name occurs explains why you don’t usually want to end your #define statement with a semicolon. If you did, the semicolon would also be substituted into the program read more..

  • Page - 253

    243 The #define Statement To make things even more interesting, a defined value can itself reference another de- fined value. So these two #define lines are perfectly valid: #define PI 3.141592654 #define TWO_PI 2.0 * PI The name TWO_PI is defined in terms of the previously defined name PI , thus obviat- ing the need to spell out the value 3.141592654 again. Reversing read more..

  • Page - 254

    244 Chapter 12 The Preprocessor tion. Note that when defining a name with arguments, no spaces are permitted between the defined name and the left parenthesis of the argument list. With the previous definition, you can write a statement such as the following: if ( IS_LEAP_YEAR (year) ) ... This tests whether the value of year is a leap year. Or you could write this to test read more..

  • Page - 255

    245 The #define Statement y = ( (v + 1) * (v + 1) ); The following macro lets you easily create new fractions from your Fraction class on the fly: #define MakeFract(x,y) ([[Fraction alloc] initWith: x over: y]]) Then you can write expressions such as myFract = MakeFract (1, 3); // Make the fraction 1/3 or even sum = [MakeFract (n1, d1) add: MakeFract (n2, d2)]; to add read more..

  • Page - 256

    246 Chapter 12 The Preprocessor The # Operator If you place a # in front of a parameter in a macro definition, the preprocessor creates a constant C-style string out of the macro argument when the macro is invoked. For exam- ple, the definition #define str(x) # x causes the subsequent invocation str (testing) to be expanded into ”testing” by the preprocessor.The printf call read more..

  • Page - 257

    247 The #import Statement The ## Operator The ## operator is used in macro definitions to join two tokens. It is preceded (or fol- lowed) by the name of a parameter to the macro.The preprocessor takes the actual argu- ment to the macro that is supplied when the macro is invoked and creates a single token out of that argument and whatever token follows (or precedes) the read more..

  • Page - 258

    248 Chapter 12 The Preprocessor ously encountered but haven’t written yourself—normally end with the characters .h and are referred to as header or include files. Suppose you were writing a series of programs for performing various metric conver- sions.You might want to set up some #define statements for the various constants you would need for performing your conversions: #define read more..

  • Page - 259

    249 The #import Statement To see how include files are used in an actual program example, type the six #define statements given previously into a file called metric.h .Then type and run Program 12.1 in the normal manner. Program 12.1 /* Illustrate the use of the #import statement Note: This program assumes that definitions are set up in a file called metric.h */ read more..

  • Page - 260

    250 Chapter 12 The Preprocessor Other system include files contain declarations for various functions stored inside the underlying C system library. For example, the file limits.h contains system-dependent values that specify the sizes of various characters and integer data types. For instance, the maximum size of an int is defined by the name INT_MAX inside this file.The maximum size read more..

  • Page - 261

    251 Conditional Compilation As you can see here, you are allowed to put one or more spaces after the # that begins a preprocessor statement. The #ifdef , #else , and #endif statements behave as you would expect. If the symbol specified on the #ifdef line has been already defined—through a #define statement or through the command line when the program is compiled—the compiler read more..

  • Page - 262

    252 Chapter 12 The Preprocessor The #if and #elif Preprocessor Statements The #if preprocessor statement offers a more general way of controlling conditional compilation.The #if statement can be used to test whether a constant expression evalu- ates to nonzero. If the result of the expression is nonzero, subsequent lines up to a #else , #elif , or #endif are processed; otherwise, they read more..

  • Page - 263

    253 Exercises Another common use of #if is in code sequences that look like this: #if defined (DEBUG) && DEBUG ... #endif This causes the statements after the #if and up to the #endif to be processed only if DEBUG is defined and has a nonzero value. The #undef Statement Sometimes you need to cau e a defined name to become undefined.You do this with the #undef statement.To read more..

  • Page - 264

    254 Chapter 12 The Preprocessor 7. Write a macro called ABSOLUTE_VALUE that computes the absolute value of its argu- ment. Make sure that the macro properly evaluates an expression such as this: ABSOLUTE_VALUE (x + delta) 8. Consider the definition of the printint macro from this chapter: #define printx(n) printf ( “%i\n”, x ## n) Could the following be used to display the read more..

  • Page - 265

    13 Underlying C Language Features This chapter describes features of the Objective-C language that you don’t necessarily need to know to write Objective-C programs. In fact, most of these come from the un- derlying C programming language. Features such as functions, structures, pointers, unions, and arrays are best learned on a need-to-know basis. Because C is a procedural language, read more..

  • Page - 266

    256 Chapter 13 Underlying C Language Features Arrays The Objective-C language enables the user to define a set of ordered data items known as an array.This section describes how to define and manipulate arrays. Later sections il- lustrate how arrays work together with functions, structures, character strings, and point- ers. Suppose you wanted to read a set of grades into the read more..

  • Page - 267

    257 Arrays sequences through the first 100 elements of the array grades (elements 0 –99) and adds the value of each grade into sum .When the for loop is finished, the variable sum contains the total of the first 100 values of the grades array (assuming that sum was set to 0 before the loop was entered). As with other types of variables, you must declare arrays before you read more..

  • Page - 268

    258 Chapter 13 Underlying C Language Features Program 13.1 Output 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 The first two Fibonacci numbers, which we call F0 and F1, are defined to be 0 and 1, respectively.Thereafter, each successive Fibonacci number Fi is defined to be the sum of the two preceding Fibonacci numbers Fi-2 and Fi-1. So F2 is calculated by adding the read more..

  • Page - 269

    259 Arrays initializes the first three values of sample_data to 100.0 , 300.0 , and 500.5 and sets the remaining 497 elements to 0 . By enclosing an element number in a pair of brackets, you can initialize specific array elements in any order. For example, int x = 1233; int a[] = { [9] = x + 1, [2] = 3, [1] = 2, [0] = 1 }; defines a 10-element array called a read more..

  • Page - 270

    260 Chapter 13 Underlying C Language Features 10 5 –3 17 82 9 0 0 8 –7 32 20 1 0 14 0 0 8 7 6 initialization elements. Because Program 13.2 has six initial values listed for the array word , the Objective-C language implicitly dimensions the array to six elements. This approach works fine as long as you initialize every element in the array at the point that the array is read more..

  • Page - 271

    261 Arrays Row (i) Column (j) 0 1 2 3 4 0 10 5 –3 17 82 1 9 0 0 8 –7 2 32 20 1 0 14 3 0 0 8 7 6 Whereas in mathematics the notation Mi,j is used, in Objective-C the equivalent nota- tion is as follows: M[i][j] Remember, the first index number refers to the row number, whereas the second in- dex number references the column.Therefore, the statement sum = M[0][2] + M[2][4]; read more..

  • Page - 272

    262 Chapter 13 Underlying C Language Features As with one-dimensional arrays, the entire array need not be initialized. A statement such as the following initializes only the first three elements of each row of the matrix to the indicated values: int M[4][5] = { { 10, 5, -3 }, { 9, 0, 0 }, { 32, 20, 1 }, { 0, 0, 8 } }; The remaining values are set to 0 . Note read more..

  • Page - 273

    263 Functions The first line of the printMessage function definition tells the compiler that printMessage is the name of the function and that it returns no value (the first use of the keyword void ). Unlike methods, you don’t put the function’s return type inside a set of parentheses. In fact, you get a compiler error message if you do. After telling the compiler that read more..

  • Page - 274

    264 Chapter 13 Underlying C Language Features Program 13.4 #import <Foundation/Foundation.h> // Function to calculate the nth triangular number void calculateTriangularNumber (int n) { int i, triangularNumber = 0; for ( i = 1; i <= n; ++i ) triangularNumber += i; NSLog (@ ”Triangular number %i is %i ”, n, triangularNumber); } int main (int argc, char *argv[]) { NSAutoreleasePool read more..

  • Page - 275

    265 Functions Local variables in functions behave the same way they do in methods: If an initial value is given to a variable inside a function, that initial value is assigned to the variable each time the function is called. Variables defined inside a function (as in methods) are known as automatic local variables because they are automatically “created” each time the read more..

  • Page - 276

    266 Chapter 13 Underlying C Language Features int gcd (int u, int v) { int temp; while ( v != 0 ) { temp = u % v; u = v; v = temp; } return u; } main () { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int result; result = gcd (150, 35); NSLog (@ ”The gcd of 150 and 35 is %i ”, result); result = gcd (1026, 405); NSLog (@ ”The gcd of 1026 and read more..

  • Page - 277

    267 Functions If the return type declaration for a function is omitted, the compiler assumes that the function will return an integer—if it returns a value at all. Many programmers take ad- vantage of this fact and omit the return type declaration for functions that return integers. However, this is a bad programming habit that you should avoid.The compiler will warn you that read more..

  • Page - 278

    268 Chapter 13 Underlying C Language Features the special file Foundation/Foundation.h 1, which is why you have been placing the fol- lowing line at the start of each of your programs: #import <Foundation/Foundation.h> Without this line, the compiler can assume that NSLog takes a fixed number of argu- ments, which can result in incorrect code being generated. The compiler read more..

  • Page - 279

    269 Functions Passing an entire array to a function or method is an entirely new ballgame.To pass an array, you need to list only the name of the array, without any subscripts, inside the call to the function or method invocation. As an example, if you assume that grade_scores has been declared as an array containing 100 elements, the expression minimum (grade_scores) passes the read more..

  • Page - 280

    270 Chapter 13 Underlying C Language Features the original array, not to a copy of the array.Therefore, when the function or method re- turns, these changes remain in effect. Multidimensional Arrays You can pass a multidimensional array element to a function or method just as any ordi- nary variable or single-dimensional array element can.The statement result = squareRoot (matrix[i][j]); read more..

  • Page - 281

    271 Structures Structures The Objective-C language provides another tool besides arrays for grouping elements. You also can use structures, which form the basis for the discussions in this section. Suppose you wanted to store a date—say, 7/18/09—inside a program, perhaps to be used for the heading of some program output or even for computational purposes. A nat- ural method for read more..

  • Page - 282

    272 Chapter 13 Underlying C Language Features Now, wait a second! Wasn’t this the same operator we used to invoke an property on an object? Recall that we could write the statement myRect.width = 12; to invoke the Rectangle object’s setter method (called setWidth ), passing it the argu- ment value of 12 . No confusion arises here:The compiler determines whether it’s a read more..

  • Page - 283

    273 Structures Program 13.6 Output Today ’s date is 9/25/09. The first statement inside main defines the structure called date to consist of three integer members, called month , day , and year . In the second statement, the variable today is declared to be of type struct date . So the first statement simply defines what a date structure looks like to the Objective-C compiler read more..

  • Page - 284

    274 Chapter 13 Underlying C Language Features int month; int day; int year; }; // Function to calculate tomorrow ’s date struct date dateUpdate (struct date today) { struct date tomorrow; int numberOfDays (struct date d); if ( today.day != numberOfDays (today) ) { tomorrow.day = today.day + 1; tomorrow.month = today.month; tomorrow.year = today.year; } else if ( today.month == 12 ) read more..

  • Page - 285

    275 Structures return (answer); } // Function to determine if it ’s a leap year BOOL isLeapYear (struct date d) { if ( (d.year % 4 == 0 && d.year % 100 != 0) || d.year % 400 == 0 ) return YES; else return NO; } int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; struct date dateUpdate (struct date today); struct date thisDay, read more..

  • Page - 286

    276 Chapter 13 Underlying C Language Features Program 13.7 Output (Rerun) Enter today ’s date (mm dd yyyy): 12 31 2010 Tomorrow ’s date is 1/1/10. Even though you’re not working with any classes in this program, the file Foundation.h was imported because you wanted to use the BOOL type and the defines YES and NO .They’re defined in that file. Notice that the definition read more..

  • Page - 287

    277 Structures specifies that the structure today is to be passed as an argument to the numberOfDays function. Inside that function, the appropriate declaration must be made to inform the system that a structure is expected as an argument, like so: int numberOfDays (struct date d) The numberOfDays function begins by determining whether it is a leap year and whether the month is read more..

  • Page - 288

    278 Chapter 13 Underlying C Language Features Arrays of Structures Working with arrays of structures is pretty straightforward.The definition struct date birthdays[15]; defines the array birthdays to contain 15 elements of type struct date . Referencing a particular structure element inside the array is quite natural.To set the second birthday in- side the birthdays array to February 22, read more..

  • Page - 289

    279 Structures event.sdate Therefore, you could call your dateUpdate function with this date as the argument and assign the result back to the same place by a statement, like so: event.sdate = dateUpdate (event.sdate); You can do the same with the time structure contained within your date_and_time structure: event.stime = timeUpdate (event.stime); To reference a particular member inside read more..

  • Page - 290

    280 Chapter 13 Underlying C Language Features Additional Details About Structures We should mention that you have some flexibility in defining a structure. First, you can declare a variable to be of a particular structure type at the same time that the structure is defined.You do this simply by including the variable name(s) before the terminating semicolon of the structure read more..

  • Page - 291

    281 Structures To define bit field assignments, you can define a structure called packedStruct , for example, as follows: struct packedStruct { unsigned int f1:1; unsigned int f2:1; unsigned int f3:1; unsigned int type:4; unsigned int index:9; }; The structure packedStruct is defined to contain five members.The first member, called f1 , is an unsigned int .The :1 that immediately follows read more..

  • Page - 292

    282 Chapter 13 Underlying C Language Features right to left. So if bit fields are assigned from right to left, f1 would be in the low-order bit position, f2 in the bit position immediately to the left of f1 , and so on.This should not present a problem unless you are dealing with data that a different program or a dif- ferent machine created. You can also include normal read more..

  • Page - 293

    283 Pointers Pointers Pointers enable you to effectively represent complex data structures, change values passed as arguments to functions and methods, and more concisely and efficiently deal with ar- rays. At the end of this chapter, we also clue you in about how important they are to the implementation of objects in the Objective-C language. We introduced the concept of a read more..

  • Page - 294

    284 Chapter 13 Underlying C Language Features 10 intPtr count Figure 13.1 Pointer to an integer to set up the indirect reference between intPtr and count .The address operator assigns to the variable intPtr not the value of count , but a pointer to the variable count . Figure 13.1 illustrates the link made between intPtr and count .The directed line illustrates the idea that intPtr read more..

  • Page - 295

    285 Pointers The variables count and x are declared to be integer variables in the normal fashion. On the next line, the variable intPtr is declared to be of type “pointer to int .” Note that the two lines of declarations could have been combined into a single line: int count = 10, x, *intPtr; Next, the address operator is applied to the variable count , which has read more..

  • Page - 296

    286 Chapter 13 Underlying C Language Features The character variable c is defined and initialized to the character ‘Q’. In the next line of the program, the variable charPtr is defined to be of type “pointer to char ,” meaning that whatever value is stored inside this variable should be treated as an indirect reference (pointer) to a character. Notice that you can assign read more..

  • Page - 297

    287 Pointers Pointers and Structures You have seen how to define a pointer to point to a basic data type such as an int or a char . But you can also define a pointer to point to a structure. Earlier in this chapter, you defined your date structure as follows: struct date { int month; int day; int year; }; Just as you defined variables to be of type struct date , as read more..

  • Page - 298

    288 Chapter 13 Underlying C Language Features We rewrote Program 13.6, the first program to illustrate structures, using the concept of structure pointers. Program 13.10 presents this program. Program 13.10 // Program to illustrate structure pointers #import <Foundation/Foundation.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; struct date read more..

  • Page - 299

    289 Pointers { int temp; temp = *pint1; *pint1 = *pint2; *pint2 = temp; } int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; void exchange (int *pint1, int *pint2); int i1 = -5, i2 = 66, *p1 = &i1, *p2 = &i2; NSLog (@ ”i1 = %i, i2 = %i ”, i1, i2); exchange (p1, p2); NSLog (@ ”i1 = %i, i2 = %i ”, i1, i2); read more..

  • Page - 300

    290 Chapter 13 Underlying C Language Features The second call to exchange is a bit more interesting.This time, the arguments passed to the function are pointers to i1 and i2 that are manufactured on the spot by applying the address operator to these two variables. Because the expression &i1 produces a pointer to the integer variable i1 , this is in line with the type of read more..

  • Page - 301

    291 Pointers The real power of using pointers to arrays comes into play when you want to se- quence through the elements of an array. If valuesPtr is defined as mentioned previously and is set pointing to the first element of values , you can use the expression *valuesPtr to access the first integer of the values array—that is, values[0] .To reference values[3] through the read more..

  • Page - 302

    292 Chapter 13 Underlying C Language Features and assign the result to the Fraction object result .You could do this by writing the following: result = [fractsPtr add: fractsPtr + 1]; The increment and decrement operators (++ and -- ) are particularly handy when dealing with pointers. Applying the increment operator to a pointer has the same effect as adding 1 to the pointer, read more..

  • Page - 303

    293 Pointers return (sum); } int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int arraySum (int array[], int n); int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 }; NSLog (@ ”The sum is %i ”, arraySum (values, 10)); [pool drain]; return 0; } Program 13.12 Output The sum is 21 Inside the arraySum function, the integer pointer read more..

  • Page - 304

    294 Chapter 13 Underlying C Language Features ginning of values .What follows from this is that you can also use the expression *(values + i) to reference the i th element of the array values —and, in general, if x is an array of any type, the expression x[i] can always be equivalently expressed in Objec- tive-C as *(x + i) . As you can see, pointers and arrays are read more..

  • Page - 305

    295 Pointers int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; void copyString (char *to, char *from); char string1[] = “A string to be copied. ”2; char string2[50]; copyString (string2, string1); NSLog (@ ”%s”, string2); copyString (string2, “So is this. ”); NSLog (@ ”%s”, string2); [pool drain]; return 0; } Program 13.13 Output A string read more..

  • Page - 306

    296 Chapter 13 Underlying C Language Features Constant Character Strings and Pointers The fact that the call copyString (string2, “So is this. ”); works in the previous program implies that when a constant character string is passed as an argument to a function, that character string is actually passed to a pointer. Not only is this true in this case, but it can also be read more..

  • Page - 307

    297 Pointers know that this adds 1 to the value of the variable x . And as you have just seen, if x is a pointer to an array, this sets x to point to the next element of the array. You can use the increment and decrement operators in expressions where other oper- ators also appear. In such cases, it becomes important to know more precisely how these operators read more..

  • Page - 308

    298 Chapter 13 Underlying C Language Features i is incremented after its value has been assigned to j . So if i were 0 before the previous statement were executed, 0 would be assigned to j and then i would be incremented by 1, as if these statements were used instead: j = i; ++i; As another example, if i is equal to 1 , the statement x = a[--i]; has the effect of read more..

  • Page - 309

    299 Pointers Execution of the assignment statement inside the loop would proceed as follows.The character that from points to would be retrieved, and then from would be incremented to point to the next character in the source string.The referenced character would be stored inside the location that to points to; then to would be incremented to point to the next location in the read more..

  • Page - 310

    300 Chapter 13 Underlying C Language Features Operations on Pointers As you have seen in this chapter, you can add or subtract integer values from pointers. Furthermore, you can compare two pointers to see whether they are equal or whether one pointer is less than or greater than another pointer.The only other operation permit- ted on pointers is the subtraction of two read more..

  • Page - 311

    301 Pointers If the lookup function has not been previously defined in the program, you must de- clare the function before the previous assignment can be made. A statement such as int lookup (void); would be needed before a pointer to this function could be assigned to the variable fnPtr . You can call the function indirectly referenced through a pointer variable by applying read more..

  • Page - 312

    302 Chapter 13 Underlying C Language Features the value of count while the program is executing. For example, this location might be at address 1000FF16 inside the computer’s memory. Luckily, you don’t need to concern yourself with the particular memory addresses as- signed to variables—the system automatically handles them. However, the knowledge that each variable is associated read more..

  • Page - 313

    303 Unions does not define x to contain three distinct members called c , f , and i ; instead, it defines x to contain a single member that is called either c , f , or i . In this way, you can use the variable x to store either a char ,a float , or an int , but not all three (and not even two of the three).You can store a character in the variable x with read more..

  • Page - 314

    304 Chapter 13 Underlying C Language Features ber type to keep track of the type of value stored in the member data . For example, you could assign it the value INTEGER (defined appropriately, we assume) if it contained an int , FLOATING if it contained a float , and CHARACTER if it contained a char .This infor- mation would enable you to know how to reference the read more..

  • Page - 315

    305 Miscellaneous Language Features They’re Not Objects! Now you know how to define arrays, structures, character strings, and unions, and how to manipulate them in your program. Remember one fundamental thing: They’re not objects. Thus, you can’t send messages to them.You also can’t use them to take maximum advan- tage of nice things such as the memory-allocation strategy that read more..

  • Page - 316

    306 Chapter 13 Underlying C Language Features The goto Statement Executing a goto statement causes a direct branch to be made to a specified point in the program.To identify where in the program the branch is to be made, a label is needed. A label is a name formed with the same rules as variable names; it must be immediately fol- lowed by a colon.The label is read more..

  • Page - 317

    307 Miscellaneous Language Features for ( i = 0, j = 100; i != 10; ++i, j -= 10 ) ... initializes the value of i to 0 and j to 100 before the loop begins, and it increments the value of i and subtracts 10 from the value of j after the body of the loop is executed. Because all operators in Objective-C produce a value, the value of the comma opera- tor is that read more..

  • Page - 318

    308 Chapter 13 Underlying C Language Features gives the number of elements contained in data (data must be a previously defined array, not a formal parameter or externally referenced array).The expression sizeof (data) / sizeof (data[0]) produces the same result. Use the sizeof operator wherever possible, to avoid having to calculate and hard-code sizes into your programs. Command-Line read more..

  • Page - 319

    309 Miscellaneous Language Features can use command-line arguments so that the word whose meaning you want to find can be specified at the same time that the program is executed, as in the following command: lookup aerie This eliminates the need for the program to prompt the user to enter a word because it is typed on the command line. If the previous command were read more..

  • Page - 320

    310 Chapter 13 Underlying C Language Features return (0); } The main routine tests to ensure that a word was typed after the program name when the program was executed. If it wasn’t, or if more than one word was typed, the value of argc is not equal to 2 . In that case, the program writes an error message to standard error and terminates, returning an exit status read more..

  • Page - 321

    311 How Things Work did that with the numerator and denominator members of your Fraction class, for ex- ample, you could write expressions such as myFract->numerator in your program to directly access the numerator member of the Fraction object myFract . But we strongly advise against doing that. As we mentioned in Chapter 10, it goes against the grain of data encapsulation. Fact read more..

  • Page - 322

    312 Chapter 13 Underlying C Language Features Exercises 1. Write a function that calculates the average of an array of 10 floating-point values and returns the result. 2. The reduce method from your Fraction class finds the greatest common divisor of the numerator and denominator to reduce the fraction. Modify that method so that it uses the gcd function from Program 13.5 read more..

  • Page - 323

    313 Exercises 7. Given the following definitions char *message = “Programming in Objective-C is fun ”; char message2[] = “You said it ”; NSString *format = “x = %i ”; int x = 100; determine whether each NSLog call from the following sets is valid and produces the same output as other calls from the set. /*** set 1 ***/ NSLog (@ ”Programming in Objective-C is fun read more..

  • Page - 324

    read more..

  • Page - 325

    Part II The Foundation Framework 14 Introduction to the Foundation Framework 15 Numbers, Strings, and Collections 16 Working with Files 17 Memory Management 18 Copying Objects 19 Archiving read more..

  • Page - 326

    read more..

  • Page - 327

    14 Introduction to the Foundation Framework A framework is a collection of classes, methods, functions, and documentation logically grouped together to make developing programs easier. On Mac OS X, more than 80 frameworks are available for developing applications so that you can easily work with the Mac’s Address Book structure, burn CDs, play back DVDs, play movies with QuickTime, read more..

  • Page - 328

    318 Chapter 14 Introduction to the Foundation Framework Note The header files are actually linked to another directory where they are stored, but that really makes no difference to you. Navigate to this directory on your system and familiarize yourself with its contents. You should also take advantage of the Foundation framework documentation that is stored on your system (buried read more..

  • Page - 329

    319 Foundation Documentation in your editor window and right-click it. From the menu that appears, you can either se- lect Find Selected Text in Documentation or select Find Selected Text in API Reference, as appropriate. Xcode will search the documentation library and display the results that match your query. Let’s see how this works.The NSString class is a Foundation class that read more..

  • Page - 330

    320 Chapter 14 Introduction to the Foundation Framework find a wide assortment of documents covering specific programming issues, such as mem- ory management, strings, and file management. Unless you subscribe to a particular document set with Xcode, the online documenta- tion might be more current than that stored on your disk. This concludes our brief introduction to the Foundation read more..

  • Page - 331

    15 Numbers, Strings, and Collections This chapter describes how to work with some of the basic objects provided in the Foundation framework.These include numbers, strings, and collections, which refers to the capability to work with groups of objects in the form of arrays, dictionaries, and sets. The Foundation framework contains a plethora of classes, methods, and functions for you to read more..

  • Page - 332

    322 Chapter 15 Numbers, Strings, and Collections Number Objects All the numeric data types we’ve dealt with up to now, such as integers, floats, and longs, are basic data types in the Objective-C language—that is, they are not objects. For exam- ple, you can’t send messages to them. Sometimes, though, you need to work with these values as objects. For example, the read more..

  • Page - 333

    323 Number Objects // double myNumber = [NSNumber numberWithDouble: 12345e+15]; NSLog (@ ”%lg”, [myNumber doubleValue]); // Wrong access here NSLog (@ ”%i”, [myNumber integerValue]); // Test two Numbers for equality if ([intNumber isEqualToNumber: floatNumber] == YES) NSLog (@ ”Numbers are equal ”); else NSLog (@ ”Numbers are not equal ”); // Test if one Number is <, ==, or > second read more..

  • Page - 334

    324 Chapter 15 Numbers, Strings, and Collections The autorelease pool provides for the automatic release of memory used by objects that are added to this pool. An object is added to the pool when it is sent an autorelease message.When the pool is released, so are all the objects that were added to it.Therefore, all such objects are destroyed unless they have been read more..

  • Page - 335

    325 Number Objects Table 15.1 NSNumber Creation and Retrieval Methods Creation and Initialization Class Method Initialization Instance Method Retrieval Instance Method numberWithChar: initWithChar: charValue numberWithUnsignedChar: initWithUnsignedChar: unsignedCharValue numberWithShort: initWithShort: shortValue numberWithUnsignedShort: initWithUnsignedShort: unsignedShortValue numberWithInteger: initWithInteger: integerValue read more..

  • Page - 336

    326 Chapter 15 Numbers, Strings, and Collections returns the value NSOrderedAscending if the numeric value stored in intNumber is less than the numeric value contained in myNumber , returns the value NSOrderedSame if the two numbers are equal, and returns the value NSOrderedDescending if the first number is greater than the second.The values returned are defined in the header file read more..

  • Page - 337

    327 String Objects As you know, you create a constant character string object in Objective-C by putting the @ character in front of the string of double-quoted characters. So the expression @ ”Programming is fun ” creates a constant character string object. In particular, it is a constant character string that belongs to the class NSConstantString . NSConstantString is a subclass read more..

  • Page - 338

    328 Chapter 15 Numbers, Strings, and Collections produces the following output: 100 You can even use the %@ format characters to display the entire contents of arrays, dic- tionaries, and sets. In fact, they can display your own class objects as well, as long as you override the description method inherited by your class. If you don’t override the method, NSLog simply displays read more..

  • Page - 339

    329 String Objects // Copy one string to the end of another str2 = [str1 stringByAppendingString: str2]; NSLog (@ ”Concatentation: %@ ”, str2); // Test if 2 strings are equal if ([str1 isEqualToString: res] == YES) NSLog (@ ”str1 == res ”); else NSLog (@ ”str1 != res ”); // Test if one string is <, == or > than another compareResult = [str1 compare: str2]; if read more..

  • Page - 340

    330 Chapter 15 Numbers, Strings, and Collections Program 15.3 first declares three immutable NSString objects: str1 , str2 , and res . The first two are initialized to constant character string objects.The declaration NSComparisonResult compareResult; declares compareResult to hold the result of the string comparison that will be per- formed later in the program. You can use the length read more..

  • Page - 341

    331 String Objects Program 15.4 illustrates additional methods for dealing with strings.These methods en- able you to extract substrings from a string, as well as search one string for the occurrence of another. Some methods require that you identify a substring by specifying a range. A range con- sists of a starting index number plus a character count. Index numbers begin read more..

  • Page - 342

    332 Chapter 15 Numbers, Strings, and Collections NSLog (@ ”Chars from index 8 through 13: %@ ”, res); // Locate one string inside another subRange = [str1 rangeOfString: @ ”string A ”]; NSLog (@ ”String is at index %lu, length is %lu ”, subRange.location, subRange.length); subRange = [str1 rangeOfString: @ ”string B ”]; if (subRange.location == NSNotFound) NSLog (@ ”String not read more..

  • Page - 343

    333 String Objects The substringWithRange: method does in one step what we just did in two: It takes a range and returns a character in the specified range.The special function NSMakeRange (8, 6) creates a range from its argument and returns the result.This is given as the argument to the substringWithRange: method. To locate one string inside another, you can use the read more..

  • Page - 344

    334 Chapter 15 Numbers, Strings, and Collections Program 15.5 // Basic String Operations - Mutable Strings #import <Foundation/NSObject.h> #import <Foundation/NSString.h> #import <Foundation/NSAutoreleasePool.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *str1 = @ ”This is string A ”; NSString *search, *replace; read more..

  • Page - 345

    335 String Objects if (substr.location != NSNotFound) { [mstr deleteCharactersInRange: substr]; NSLog (@ ”%@”, mstr); } // Set the mutable string directly [mstr setString: @ ”This is string A ”]; NSLog (@ ”%@”, mstr); // Now let ’s replace a range of chars with another [mstr replaceCharactersInRange: NSMakeRange(8, 8) withString: @ ”a mutable string ”]; NSLog (@ ”%@”, mstr); // read more..

  • Page - 346

    336 Chapter 15 Numbers, Strings, and Collections 0 Index # 16 13 chars 28 This is mutable string A and string B and string C Figure 15.1 Indexing into a string Program 15.5 Output This is string A This is mutable string A This is mutable string A and string B This is mutable string A and string B and string C This is mutable string B and string C This is mutable read more..

  • Page - 347

    337 String Objects The rangeOfString: method is used in the lines that follow in Program 15.5 to show how a string can first be located and then deleted. After first verifying that the string @ ”string B and ” does exist in mstr , the deleteCharactersInRange: method is used to delete the characters, using the range returned from the rangeOfString: method as its argument. You read more..

  • Page - 348

    338 Chapter 15 Numbers, Strings, and Collections Table 15.2 Common NSString Methods Method Description +(id) stringWithContentsOfFile: path encoding: enc error: err Creates a new string and sets it to the path con- tents of a file specified by path using character encoding enc , returning error in err if non-nil +(id) stringWithContentsOfURL: url encoding: enc error: err Creates a new string and read more..

  • Page - 349

    339 String Objects Table 15.2 Common NSString Methods Method Description -(id) initWithContentsOfURL: url encoding enc error: err Sets a string to the contents of url (NSURL *) url using character encoding enc , returning er- ror in err if non-nil -(NSUInteger) length Returns the number of characters in the string -(unichar) characterAtIndex: i Returns the Unicode character at index i -(NSString read more..

  • Page - 350

    340 Chapter 15 Numbers, Strings, and Collections Table 15.3 Common NSMutableString Methods Method Description +(id) stringWithCapacity: size Creates a string initially containing size char- acters. -(id) initWithCapacity: size Initializes a string with an initial capacity of size characters. -(void) setString: nsstring Sets a string to nsstring. -(void) appendString: nsstring Appends nsstring to the end of read more..

  • Page - 351

    341 Array Objects Array Objects A Foundation array is an ordered collection of objects. Most often, elements in an array are of one particular type, but that’s not required. Just as there are mutable and immutable strings, are there mutable and immutable arrays. Immutable arrays are handled by the NSArray class, whereas mutable ones are handled by NSMutableArray .The latter is read more..

  • Page - 352

    342 Chapter 15 Numbers, Strings, and Collections Program 15.6 Output Month Name ===== ==== 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December You can use the class method arrayWithObjects: can be to create an array with a list of objects as its elements. In such a case, the objects are listed in order and are read more..

  • Page - 353

    343 Array Objects int main (int argc, char *argv[]) { int i, p, prevPrime; BOOL isPrime; NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Create an array to store the prime numbers NSMutableArray *primes = [NSMutableArray arrayWithCapacity: 20]; // Store the first two primes (2 and 3) into the array [primes addObject: [NSNumber numberWithInteger: 2]] read more..

  • Page - 354

    344 Chapter 15 Numbers, Strings, and Collections Program 15.7 Output 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 You define kMaxPrime to the maximum prime number you want the program to cal- culate, which, in this case, is 50 . After allocating your primes array, you set the first two elements of the array using these statements: [primes addObject: [NSNumber numberWithInteger: 2]]; read more..

  • Page - 355

    345 Array Objects lower-level array constructs provided by the language might be more efficient, in terms of both memory usage and execution speed. Refer to the section titled “Arrays” in Chapter 13 for more information. Making an Address Book Let’s take a look at an example that starts to combine a lot of what you’ve learned to this point by creating an address read more..

  • Page - 356

    346 Chapter 15 Numbers, Strings, and Collections This is straightforward, as is the implementation file in Program 15.8. Program 15.8 Implementation File AddressCard.m #import “AddressCard.h” @implementation AddressCard -(void) setName: (NSString *) theName { name = [[NSString alloc] initWithString: theName]; } -(void) setEmail: (NSString *) theEmail { email = [[NSString alloc] initWithString: read more..

  • Page - 357

    347 Array Objects -(void) setEmail: (NSString *) theEmail { email = theEmail; } But the AddressCard object would not own its member objects.We talked about the motivation for an object to take ownership with respect to the Rectangle class owning its origin object in Chapter 8,“Inheritance.” Defining the two methods in the following way would also be an incorrect approach because read more..

  • Page - 358

    348 Chapter 15 Numbers, Strings, and Collections [card1 setName: aName]; [card1 setEmail: aEmail]; [card1 print]; [card1 release]; [pool drain]; return 0; } Program 15.8 Output ===================================== | | | Julia Kochan | | jewls337@axlc.com read more..

  • Page - 359

    349 Synthesized AddressCard Methods for the email address, you must release the memory it uses before you replace it with the new one. These are the new setName: and setEmail: methods that ensure that we have a class that handles memory management properly: -(void) setName: (NSString *) theName { [name release]; name = [[NSString alloc] initWithString: theName]; } -(void) setEmail: read more..

  • Page - 360

    350 Chapter 15 Numbers, Strings, and Collections lists the attributes copy and nonatomic for the properties.The copy attribute says to make a copy of the instance variable in its setter method, as you did in the version you wrote. The default action is not to make a copy, but to instead perform a simple assignment (that’s the default attribute assign ), an incorrect approach read more..

  • Page - 361

    351 Synthesized AddressCard Methods By relying on the synthesized setter methods to set the appropriate instance variables (instead of setting them directly inside the method yourself), you add a level of abstraction and, therefore, make the program slightly more independent of its internal data structures. You also take advantage of the synthesized method’s properties, which in this read more..

  • Page - 362

    352 Chapter 15 Numbers, Strings, and Collections ==================================== | | | Tony Iannino | | tony.iannino@techfitness.com | | | | read more..

  • Page - 363

    353 Synthesized AddressCard Methods Program 15.10 Addressbook.m Implementation File #import “AddressBook.h” @implementation AddressBook; // set up the AddressBook ’s name and an empty book -(id) initWithName: (NSString *) name { self = [super init]; if (self) { bookName = [ NSString alloc] initWithString: name]; book = [[NSMutableArray alloc] init]; } return self; } -(void) addCard: (AddressCard read more..

  • Page - 364

    354 Chapter 15 Numbers, Strings, and Collections The initWithName: method first calls the init method for the superclass to perform its initialization. Next, it creates a string object (using alloc so it owns it) and sets it to the name of the address book passed in as name .This is followed by the allocation and ini- tialization of an empty mutable array that is stored in read more..

  • Page - 365

    355 Synthesized AddressCard Methods Program 15.10 is a test program for your new AddressBook class. Program 15.10 Test Program #import “AddressBook.h” #import <Foundation/NSAutoreleasePool.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *aName = @ ”Julia Kochan ”; NSString *aEmail = @ ”jewls337@axlc.com”; NSString *bName = read more..

  • Page - 366

    356 Chapter 15 Numbers, Strings, and Collections NSLog (@ ”Entries in address book after adding cards: %i ”, [myBook entries]); // List all the entries in the book now [myBook list]; [card1 release]; [card2 release]; [card3 release]; [card4 release]; [myBook release]; [pool drain]; return 0; } Program 15.10 Output Entries in address book after creation: 0 Entries in address book after read more..

  • Page - 367

    357 Synthesized AddressCard Methods for ( AddressCard *nextCard in book ) if ( [[nextCard name] caseInsensitiveCompare: theName] == NSOrderedSame ) return nextCard; return nil; } If you put the declaration for this method in your interface file and the definition in the implementation file, you can write a test program to try your new method. Program 15.11 shows such a program, read more..

  • Page - 368

    358 Chapter 15 Numbers, Strings, and Collections [myBook addCard: card3]; [myBook addCard: card4]; // Look up a person by name NSLog (@ ”Stephen Kochan ”); myCard = [myBook lookup: @ ”stephen kochan ”]; if (myCard != nil) [myCard print]; else NSLog (@ ”Not found! ”); // Try another lookup NSLog (@ ”Lookup:Haibo Zhang ”); myCard = [myBook lookup: @ ”Haibo Zhang ”]; if (myCard read more..

  • Page - 369

    359 Synthesized AddressCard Methods When the lookup: method located Stephen Kochan in the address book (taking ad- vantage of the fact that a non-case-sensitive match was made), the method gave the re- sulting address card to the AddressCard ’s print method for display. In the case of the second lookup, the name Haibo Zhang was not found. This lookup message is very read more..

  • Page - 370

    360 Chapter 15 Numbers, Strings, and Collections Here’s the new removeCard method: -(void) removeCard: (AddressCard *) theCard { [book removeObjectIdenticalTo: theCard]; } For purposes of what’s considered an identical object, we are using the idea of the same location in memory. So the removeObjectIdenticalTo: method does not consider two address cards that contain the same information read more..

  • Page - 371

    361 Synthesized AddressCard Methods Program 15.12 Test Program #import “AddressBook.h” #import <Foundation/NSAutoreleasePool.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *aName = @ ”Julia Kochan ”; NSString *aEmail = @ ”jewls337@axlc.com”; NSString *bName = @ ”Tony Iannino ”; NSString *bEmail = @ read more..

  • Page - 372

    362 Chapter 15 Numbers, Strings, and Collections // Now remove the entry from the phone book [myBook removeCard: myCard]; [myBook list]; // verify it ’s gone [card1 release]; [card2 release]; [card3 release]; [card4 release]; [myBook release]; [pool drain]; return 0; } Program 15.12 Output Lookup: Stephen Kochan ==================================== | read more..

  • Page - 373

    363 Synthesized AddressCard Methods generic sorting method is to have you decide whether elements in the array are in order. To do this, you must add a method to compare two elements in the array. 4 The result re- turned from that method is to be of type NSComparisonResult . It should return NSOrderedAscending if you want the sorting method to place the first element read more..

  • Page - 374

    364 Chapter 15 Numbers, Strings, and Collections If you add the sort method to the AddressBook class and the compareNames: method to the AddressCard class, you can write a test program to test it (see Program 15.13). Program 15.13 Test Program #import “AddressBook.h” #import <Foundation/NSAutoreleasePool.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool read more..

  • Page - 375

    365 Synthesized AddressCard Methods [myBook sort]; [myBook list]; [card1 release]; [card2 release]; [card3 release]; [card4 release]; [myBook release]; [pool drain]; return 0; } Program 15.13 Output ======== Contents of: Linda ’s Address Book ========= Julia Kochan jewls337@axlc.com Tony Iannino tony.iannino@techfitness.com Stephen Kochan steve@kochan-wood.com Jamie Baker read more..

  • Page - 376

    366 Chapter 15 Numbers, Strings, and Collections In Tables 15.4 and 15.5, obj , obj1 , and obj2 are any objects; i is an NSUInteger inte- ger representing a valid index number into the array; selector is a selector object of type SEL ; and size is an NSUInteger integer. Table 15.4 Common NSArray Methods Method Description +(id) arrayWithObjects: obj1, obj2, ... nil Creates a new array read more..

  • Page - 377

    367 Dictionary Objects Dictionary Objects A dictionary is a collection of data consisting of key-object pairs. Just as you would look up the definition of a word in a dictionary, you obtain the value (object) from an Objective- C dictionary by its key.The keys in a dictionary must be unique, and they can be of any object type, although they are typically strings.The value read more..

  • Page - 378

    368 Chapter 15 Numbers, Strings, and Collections [pool drain]; return 0; } Program 15.14 Output abstract class: A class defined so other classes can inherit from it adopt: To implement all the methods defined in a protocol archiving: Storing an object for later use The expression [NSMutableDictionary dictionary] creates an empty mutable dictionary.You can add key-value pairs to the read more..

  • Page - 379

    369 Dictionary Objects // Print all key-value pairs from the dictionary for ( NSString *key in glossary ) NSLog (@ ”%@%@”, key, [glossary objectForKey: key]); [pool drain]; return 0; } Program 15.15 Output abstract class: A class defined so other classes can inherit from it adopt: To implement all the methods defined in a protocol archiving: Storing an object for later use The read more..

  • Page - 380

    370 Chapter 15 Numbers, Strings, and Collections Table 15.6 Common NSDictionary Methods Method Description -(NSEnumerator *) keyEnumerator Returns an NSEnumerator object for all the keys in the dictionary -(NSArray *) keysSortedByValueUsingSelector: (SEL) selector Returns an array of keys in the dictionary sorted according to the comparison method selector specifies -(NSEnumerator *) objectEnumerator Returns read more..

  • Page - 381

    371 Set Objects Program 15.16 shows some basic operations on sets. Say you wanted to display the contents of your sets several times during execution of the program.You therefore have decided to create a new method called print .You add the print method to the NSSet class by creating a new category called Printing . NSMutableSet is a subclass of NSSet ,so mutable sets can use read more..

  • Page - 382

    372 Chapter 15 Numbers, Strings, and Collections NSLog (@ ”set1: “); [set1 print]; NSLog (@ ”set2: “); [set2 print]; // Equality test if ([set1 isEqualToSet: set2] == NO) NSLog (@ ”set1 equals set2 ”); else NSLog (@ ”set1 is not equal to set2 ”); // Membership test if ([set1 containsObject: INTOBJ(10)] == YES) NSLog (@ ”set1 contains 10 ”); else NSLog (@ ”set1 does not read more..

  • Page - 383

    373 Set Objects Program 15.16 Output set1: { 3 10 1 5 } set2: { 100 3 -5 5 } set1 is not equal to set2 set1 contains 10 set2 does not contain 10 set1 after adding 4 and removing 10: { 3 1 5 4 } set1 intersect set2: { 3 5 } set1 union set : { 12 3 5 200 } The print method uses the fast enumeration technique previously described to re- trieve each element read more..

  • Page - 384

    374 Chapter 15 Numbers, Strings, and Collections the set increments the count, whereas removing the object from the set decrements the count. If it reaches zero, the actual object itself is removed from the set.The countForObject: retrieves the count for a specified object in a set. One application for a counted set might be a word counter application. Each time a word is read more..

  • Page - 385

    375 Exercises Exercises 1. Look up the NSCalendarDate class in your documentation.Then add a new cate- gory to NSCalendarDate called ElapsedDays . In that new category, add a method based on the following method declaration: -(unsigned long) numberOfElapsedDays: (NSCalendarDate *) theDate; Have the new method return the number of elapsed days between the receiver and the argument to the read more..

  • Page - 386

    376 Chapter 15 Numbers, Strings, and Collections 7. Using the Fraction class defined in Part I, set up an array of fractions with some arbitrary values.Then write some code that finds the sum of all the fractions stored in the array. 8. Using the Fraction class defined in Part I, set up a mutable array of fractions with arbitrary values.Then sort the array using the read more..

  • Page - 387

    16 Working with Files The Foundation framework enables you to get access to the file system to perform basic operations on files and directories.This is provided by NSFileManager , whose methods include the capability to n Create a new file n Read from an existing file n Write data to a file n Rename a file n Remove (delete) a file n Test for the existence of a file n read more..

  • Page - 388

    378 Chapter 16: Working with Files Table 16.1 Common NSFileManager File Methods Method Description -(NSData *) contentsAtPath: path Reads data from a file -(NSData *) createFileAtPath: path contents: (NSData *) data attributes: attr Writes data to a file Managing Files and Directories: NSFileManager A file or directory is uniquely identified to NSFileManager using a pathname to the file. A pathname read more..

  • Page - 389

    379 Managing Files and Directories: NSFileManager Table 16.1 Common NSFileManager File Methods Method Description -(BOOL) removeFileAtPath: path handler: handler Removes a file -(BOOL) movePath: from toPath: to handler: handler Renames or moves a file (to cannot already exist) -(BOOL) copyPath: from toPath: to handler: handler Copies a file (to cannot already exist) -(BOOL) contentsEqualAtPath: path1 andPath: read more..

  • Page - 390

    380 Chapter 16: Working with Files the specified file’s attributes.The traverseLink: parameter is YES or NO for symbolic links. If the file is a symbolic link and YES is specified, the attributes of the linked-to file are returned; if NO is specified, the attributes of the link itself are returned. For preexisting files, the attributes dictionary includes information such as the read more..

  • Page - 391

    381 Managing Files and Directories: NSFileManager if ([fm copyPath: fName toPath: @ ”newfile” handler: nil] == NO) { NSLog (@ ”File copy failed! ”); return 2; } // Let ’s test to see if the two files are identical if ([fm contentsEqualAtPath: fName andPath: @ ”newfile”] == NO) { NSLog (@ ”Files are not equal! ”); return 3; } // Now let ’s rename the copy if ([fm read more..

  • Page - 392

    382 Chapter 16: Working with Files Program 16.1 Output File size is 84 bytes All operations were successful! This is a test file with some data in it. Here ’s another line of data. And a third. The program first tests whether testfile exists. If it does, it makes a copy of it and then tests the two files for equality. Experienced UNIX users should note that you can’t read more..

  • Page - 393

    383 Managing Files and Directories: NSFileManager Working with the NSData Class When working with files, you frequently need to read data into a temporary storage area, often called a buffer.When collecting data for subsequent output to a file, a storage area is also often used. Foundation’s NSData class provides an easy way to set up a buffer, read the contents of the file read more..

  • Page - 394

    384 Chapter 16: Working with Files Table 16.2 Common NSFileManager Directory Methods Method Description -(NSString *) currentDirectoryPath Gets the current directory -(BOOL) changeCurrentDirectoryPath: path Changes the current directory -(BOOL) copyPath: from toPath: to handler: handler Copies a directory structure; to cannot previously exist -(BOOL) createDirectoryAtPath: path attributes: attr Creates a new read more..

  • Page - 395

    385 Managing Files and Directories: NSFileManager Table 16.2 Common NSFileManager Directory Methods Method Description -(BOOL) fileExistsAtPath: path isDirectory: (BOOL *) flag Tests whether the file is a directory (YES/NO result is stored in flag) -(NSArray *) directoryContentsAtPath: path Lists the contents of the directory -(NSDirectoryEnumerator *) enumeratorAtPath: path Enumerates the contents of the read more..

  • Page - 396

    386 Chapter 16: Working with Files if ([fm createDirectoryAtPath: dirName attributes: nil] == NO) { NSLog (@ ”Couldn’t create directory!”); return 1; } // Rename the new directory if ([fm movePath: dirName toPath: @ ”newdir” handler: nil] == NO) { NSLog (@ ”Directory rename failed! ”); return 2; } // Change directory into the new directory if ([fm changeCurrentDirectoryPath: @ read more..

  • Page - 397

    387 Managing Files and Directories: NSFileManager Enumerating the Contents of a Directory Sometimes you need to get a list of the contents of a directory.This enumeration process can be accomplished using either the enumeratorAtPath: or the directoryContentsAtPath: method. In the former case, each file in the specified direc- tory is enumerated one at a time and, by default, if one read more..

  • Page - 398

    388 Chapter 16: Working with Files while ((path = [dirEnum nextObject]) != nil) NSLog (@ ”%@”, path); // Another way to enumerate a directory dirArray = [fm directoryContentsAtPath: [fm currentDirectoryPath]]; NSLog (@ ”Contents using directoryContentsAtPath: ”); for ( path in dirArray ) NSLog (@ ”%@”, path); [pool drain]; return 0; } Program 16.4 Output Contents of read more..

  • Page - 399

    389 Working with Paths: NSPathUtilities.h You begin enumeration of a directory by sending an enumerationAtPath: message to a file manager object, in this case fm . An NSDirectortyEnumerator object gets returned by the enumeratorAtPath: method, which is stored inside dirNum . Now, each time you send a nextObject message to this object, you get returned a path to the next file in read more..

  • Page - 400

    390 Chapter 16: Working with Files int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *fName = @ ”path.m”; NSFileManager *fm; NSString *path, *tempdir, *extension, *homedir, *fullpath; NSString *upath = @ ”~stevekochan/progs/../ch16/./path.m”; NSArray read more..

  • Page - 401

    391 Working with Paths: NSPathUtilities.h NSLog (@ ”%@”, path); // “Standardize” a path NSLog (@ ”%@ => %@ ”, upath , [upath stringByStandardizingPath] ); [pool drain]; return 0; } Program 16.5 Output Temporary Directory is /var/folders/HT/HTyGLvSNHTuNb6NrMuo7QE+++TI/-Tmp-/ Base dir is examples fullpath to path.m is /Users/stevekochan/progs/examples/path.m extension for read more..

  • Page - 402

    392 Chapter 16: Working with Files Table 16.3 Common Path Utility Methods Method Description +(NSString *) pathWithComponents: components Constructs a valid path from elements in components -(NSArray *) pathComponents Deconstructs a path into its constituent components -(NSString *) lastPathComponent Extracts the last component in a path -(NSString *) pathExtension Extracts the extension from the last read more..

  • Page - 403

    393 Working with Paths: NSPathUtilities.h Table 16.4 Common Path Util ty Functions Function Description NSString *NSUserName (void) Returns the current user’s login name NSString *NSFullUserName (void) Returns the current user’s full username NSString *NSHomeDirectory (void) Returns the path to the current user’s home directory NSString *NSHomeDirectoryForUser (NSString * user) Returns the home read more..

  • Page - 404

    394 Chapter 16: Working with Files Table 16.5 NSProcessInfo Methods Method Description +(NSProcessInfo *) processInfo Returns information about the current process –(NSArray *) arguments Returns the arguments to the current process as an array of NSString objects –(NSDictionary *) environment Returns a dictionary of variable/value pairs repre- senting the current environment variables (such as PATH read more..

  • Page - 405

    395 Working with Paths: NSPathUtilities.h Program 16.6 // Implement a basic copy utility #import <Foundation/NSString.h> #import <Foundation/NSArray.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSPathUtilities.h> #import <Foundation/NSProcessInfo.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] read more..

  • Page - 406

    396 Chapter 16: Working with Files if ([fm copyPath: source toPath: dest handler: nil] == NO) { NSLog (@ ”Copy failed! ”); return 3; } NSLog (@ ”Copy of %@ to %@ succeeded! ”, source, dest); [pool drain]; return 0; } Program 16.6 Output $ ls –l see what files we have total 96 -rwxr-xr-x 1 stevekoc staff 19956 Jul 24 14:33 copy -rw-r--r-- 1 stevekoc staff 1484 Jul 24 read more..

  • Page - 407

    397 Basic File Operations: NSFileHandle checks the file specified by dest to see whether it is a directory. As you’ve seen previ- ously, the answer—YES or NO —is stored in the variable isDir . If dest is a directory, you want to append the last path component of the source file- name to the end of the directory’s name.You use the path utility method read more..

  • Page - 408

    398 Chapter 16: Working with Files Table 16.6 Common NSFileHandle Methods Method Description -(NSData *) readDataToEndOfFile Reads the remaining data up to the end of the file (UINT_MAX) bytes max -(NSData *) readDataOfLength: (NSUInteger) bytes Reads a specified number of bytes from the file -(void) writeData: data Writes data to the file -(unsigned long long) offsetInFile Obtains the current file read more..

  • Page - 409

    399 Basic File Operations: NSFileHandle #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSData.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSFileHandle *inFile, *outFile; NSData *buffer; // Open the file testfile for reading inFile = [NSFileHandle fileHandleForReadingAtPath: @ ”testfile”]; if read more..

  • Page - 410

    400 Chapter 16: Working with Files Program 16.7 Output This is a test file with some data in it. Here ’s another line of data. And a third. The method readDataToEndOfFile: reads up to UINT_MAX bytes of data at a time, which is defined in <limits.h> and equal to FFFFFFFF16.This will be large enough for any application you’ll have to write.You can also break up the read more..

  • Page - 411

    401 Basic File Operations: NSFileHandle #import <Foundation/NSFileHandle.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSData.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSFileHandle *inFile, *outFile; NSData *buffer; read more..

  • Page - 412

    402 Chapter 16: Working with Files Contents of FileB before running Program 16.8 This is line 1 in the second file. This is line 2 in the second file. Program 16.8 Output Contents of fileB This is line 1 in the second file. This is line 2 in the second file. This is line 1 in the first file. This is line 2 in the first file. You can see from the output that read more..

  • Page - 413

    403 Exercises 3. Write your own version of the standard UNIX tools basename and dirname . 4. Using NSProcessInfo , write a program to display all the information returned by each of its getter methods. 5. Given the NSPathUtilities.h function NSTemporaryDirectory and the NSProcessInfo method globallyUniqueString described in this chapter, add a category called TempFiles to NSString , and in it read more..

  • Page - 414

    read more..

  • Page - 415

    17 Memory Management We have focused on the topic of memory management throughout this book.You should understand by now when you are responsible for releasing objects and when you are not. Even though the examples in this book have all been small, we have emphasized the importance of paying attention to memory management, to teach good programming practice and to develop read more..

  • Page - 416

    406 Chapter 17 Memory Management When the pool is set up, Foundation automatically adds certain arrays, strings, diction- aries, and other objects to this pool.When you’re done using the pool, you can release the memory it uses by sending it a drain message: [pool drain]; The autorelease pool gets its name from the fact that any objects that have been marked as autorelease read more..

  • Page - 417

    407 Reference Counting [myFraction retain]; Some of the methods in the Foundation framework also increment this reference count, such as when an object is added to an array. When you no longer need an object, you decrement its reference count by 1 by send- ing it a release message, like this: [myFraction release]; When the reference count of an object reaches 0 , the system read more..

  • Page - 418

    408 Chapter 17 Memory Management NSLog (@ ”myInt2 after retain = %lx ”, (unsigned long) [myInt2 retainCount]); [myInt release]; NSLog (@ ”after release = %lx ”, (unsigned long) [myInt retainCount]); [myArr removeObjectAtIndex: 0]; NSLog (@ ”after removal from array = %lx ”, (unsigned long) [myInt retainCount]); [pool drain]; return 0; } Program 17.1 Output myInt retain count = 1 after read more..

  • Page - 419

    409 Reference Counting the reference count, assigning it to another variable does not, so you must do that your- self. Notice from the output that both myInt and myInt2 have a reference count of 3 ; that’s because they both reference the same object in memory. Let’s assume that you’re finished using the myInt object in your program.You can tell the system that by read more..

  • Page - 420

    410 Chapter 17 Memory Management [myArr addObject: myStr2]; [myArr addObject: myStr3]; NSLog (@ ”Retain count: myStr1: %lx, myStr2: %lx, myStr3: %lx ”, (unsigned long) [myStr1 retainCount], (unsigned long) [myStr2retainCount], (unsigned long) [myStr3 retainCount]); [myArr addObject: myStr1]; [myArr addObject: myStr2]; [myArr addObject: myStr3]; NSLog (@ ”Retain count: myStr1: %lx, myStr2: %lx, myStr3: read more..

  • Page - 421

    411 Reference Counting Note Here the system is clever and determines that the immutable string object is being initial- ized by a constant string object. Before the release of Leopard, this optimization was not done, and mystr2 would have had a retain count. In the statement NSMutableString *myStr3 = [NSMutableString stringWithString: @ ”string 3 ”]; the variable myStr3 is set to read more..

  • Page - 422

    412 Chapter 17 Memory Management Suppose we had defined setName: this way instead and did not have it take ownership of its name object: -(void) setName: (NSString *) theName { name = theName; } This version of the method takes a string representing the person’s name and stores it in the name instance variable. It seems straightforward enough, but consider the following method read more..

  • Page - 423

    413 Reference Counting } -(NSString *) str { return str; } @end int main (int argc, char *argv[]) { NSAutorelea ePool * pool = [[NSAutoreleasePool alloc] init]; NSMutableString *myStr = [NSMutableSt ing stringWithString: @ ”A string ”]; ClassA *myA = [[ClassA alloc] init]; NSLog (@ ”myStr retain count: %x ”, [myStr retainCount]); [myA setStr: myStr]; NSLog (@ ”myStr retain count: read more..

  • Page - 424

    414 Chapter 17 Memory Management Program 17.4 // Retaining objects #import <Foundation/NSObject.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSString.h> #import <Foundation/NSArray.h> @interface ClassA: NSObject { NSString *str; } -(void) setStr: (NSString *) s; -(NSString *) str; @end @implementation ClassA -(void) setStr: (NSString *) s { str = s; [str retain]; } -(NSString read more..

  • Page - 425

    415 Reference Counting Program 17.4 Output myStr retain count: 1 myStr retain count: 2 myStr retain count: 1 You can see that the reference count for myStr is bumped to 2 after the setStr: method is invoked, so this particular problem has been solved. Subsequently releasing myStr in the program makes its reference through the instance variable still valid because its reference count read more..

  • Page - 426

    416 Chapter 17 Memory Management // free up old object since we ’re done with it [str autorelease]; // retain argument in case someone else releases it str = [s retain]; } -(NSString *) str { return str; } -(void) dealloc { NSLog (@ ”ClassA dealloc ”); [str release]; [super dealloc]; } @end int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] read more..

  • Page - 427

    417 Reference Counting marked for release. After the old value is released, the new one is retained and stored in the str field.The message expression str = [s retain]; takes advantage of the fact that the retain method returns its receiver. Note If the str variable is nil, that’s not a problem. The Objective-C runtime initializes all instance variables to nil, and it’s okay read more..

  • Page - 428

    418 Chapter 17 Memory Management An Autorelease Example Let’s take a look at one last program example in this chapter to ensure that you really un- derstand how reference counting, retaining, and releasing/autoreleasing objects work. Ex- amine Program 17.6, which defines a dummy class called Foo with one instance variable and only inherited methods. Program 17.6 #import read more..

  • Page - 429

    419 Summary of Memory-Management Rules after poolrelease = 1 after autorelease = 1 after retain = 2 after second pool drain = 1 The program allocates a new Foo object and assigns it to the variable myFoo . Its initial retain count is 1 , as you’ve already seen.This object is not a part of the autorelease pool yet, so releasing the pool does not invalidate the object. read more..

  • Page - 430

    420 Chapter 17 Memory Management n When you develop more sophisticated applications (such as Cocoa applications), au- torelease pools can be created and destroyed during execution of the program (for Cocoa applications, that happens each time an event occurs). In such cases, if you want to ensure that your object survives automatic deallocation when the autore- lease pool itself is read more..

  • Page - 431

    421 Garbage Collection Figure 17.1 Enabling garbage collection. need to write your code using the memory management techniques described through- out this book. It also means you have to test your code with garbage-collection disabled and enabled. If you decide to use garbage collection, you must turn it on when building programs with Xcode.You can do this through the Project, Edit read more..

  • Page - 432

    422 Chapter 17 Memory Management Exercises 1. Write a program to test the effects of adding and removing entries in a dictionary on the reference count of the objects you add and remove. 2. What effect do you think the NSArray ’s replaceObjectAtIndex:withObject: method will have on the reference count of the object that is replaced in the array? What effect will it have on read more..

  • Page - 433

    18 Copying Objects This chapter discusses some of the subtleties involved in copying objects.We introduce the concept of shallow versus deep copying nd discuss how to make copies under the Foundation framework. Chapter 8,“Inheritance,” discussed what happens when you assign one object to an- other with a simple assignment statement, such as here: origin = pt; In this example, read more..

  • Page - 434

    424 Chapter 18 Copying Objects The copy and mutableCopy Methods The Foundation classes implement methods known as copy and mutableCopy that you can use to create a copy of an object.This is done by implementing a method in confor- mance with the <NSCopying> protocol for making copies. If your class needs to distin- guish between making mutable and immutable copies of an read more..

  • Page - 435

    425 The copy and mutableCopy Methods dataArray2 = [dataArray mutableCopy]; [dataArray2 removeObjectAtIndex: 0]; NSLog (@ ”dataArray: “); for ( NSString *elem in dataArray ) NSLog (@ ” %@ ”, elem); NSLog (@ ”dataArray2: “); for ( NSString *elem in dataArray2 ) NSLog (@ ” %@ ”, elem); [dataArray2 release]; [pool drain]; return 0; } Program 18.1 Output dataArray: two three four dataArray2: read more..

  • Page - 436

    426 Chapter 18 Copying Objects elements. Now when you remove the first element from dataArray2 , it has no effect on the contents of dataArray , as verified by the last two lines of the program’s output. Note that making a mutable copy of an object does not require that the object being copied be mutable.The same applies to immutable copies:You can make an immutable read more..

  • Page - 437

    427 Shallow Versus Deep Copying // make a copy, then change one of the strings dataArray2 = [dataArray mutableCopy]; mStr = [dataArray objectAtIndex: 0]; [mStr appendString: @ ”ONE”]; NSLog (@ ”dataArray: “); for ( NSString *elem in dataArray ) NSLog (@ ” %@ ”, elem); NSLog (@ ”dataArray2: “); for ( NSString *elem in dataArray2 ) NSLog (@ ” %@ ”, elem); [dataArray2 read more..

  • Page - 438

    428 Chapter 18 Copying Objects but not why its copy was as well.When you get an element from a collection, you get a new reference to that element, but not a new copy. So when the objectAtIndex: method is invoked on dataArray , the returned object points to the same object in mem- ory as the first element in dataArray . Subsequently modifying the string object mStr has read more..

  • Page - 439

    429 Implementing the <NSCopying> Protocol Implementing the <NSCopying> Protocol If you try to use the copy method on one of your own classes—for example, on your address book, as follows NewBook = [myBook mutableCopy]; you’ll get an error message that looks something like this: *** -[AddressBook copyWithZone:]: selector not recognized *** Uncaught exception: *** -[AddressBook read more..

  • Page - 440

    430 Chapter 18 Copying Objects In the implementation file Fraction.m , add the following definition for your new method: -(id) copyWithZone: (NSZone *) zone { Fraction *newFract = [[Fraction allocWithZone: zone] init]; [newFract setTo: numerator over: denominator]; return newFract; } The zone argument has to do with different memory zones that you can allocate and work with in your read more..

  • Page - 441

    431 Implementing the <NSCopying> Protocol Program 18.3 Output 2/5 1/3 The program creates a Fraction object called f1 and sets it to 2/5 . It then invokes the copy method to make a copy, which sends the copyWithZone: message to your object. That method makes a new Fraction , copies the values from f1 into it, and returns the result. Back in main , you assign that result read more..

  • Page - 442

    432 Chapter 18 Copying Objects Copying Objects in Setter and Getter Methods Whenever you implement a setter or getter method, you should think about what you’re storing in the instance variables, what you’re retrieving, and whether you need to protect these values. For example, consider this when you set the name of one of your AddressCard objects using the setName: method: read more..

  • Page - 443

    433 Copying Objects in Setter and Getter Methods will generate a synthesized method that behaves like this: -(void) setName: (NSString *) theName { if (theName != name) { [name release] name = [theName copy]; } } Use of nonatomic here tells the system not to protect the property accessors with a mutex (mutually exclusive) lock People writing threadsafe code use mutex locks to pre- read more..

  • Page - 444

    434 Chapter 18 Copying Objects -(void) retainName: (NSString *) theName andEmail: (NSString *) theEmail { name = [theName retain]; email = [theEmail retain]; } The setName:andEmail: method isn’t used here to copy the instance variables over because that method makes new copies of its arguments, which would defeat the whole purpose of this exercise. Instead, you just retained the two read more..

  • Page - 445

    19 Archiving In Objective-C terms, archiving is the process of saving one or more objects in a format so that they can later be restored. Often this involves writing the object(s) to a file so it can subsequently be read back in.We discuss two methods for archiving data in this chap- ter: property lists and key-valued coding. Archiving with XML Property Lists Mac OS X read more..

  • Page - 446

    436 Chapter 19 Archiving { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSDictionary *glossary = [NSDictionary dictionaryWithObjectsAndKeys: @ ”A class defined so other classes can inherit from it. ”, @ ”abstract class ”, @ ”To implement all the methods defined in a protocol ”, @ ”adopt”, @ ”Storing an object for later use. “, @ ”archiving”, nil read more..

  • Page - 447

    437 Archiving with NSKeyedArchiver back data, use the dataWithContentsOfFile: method; to read back string objects, use the stringWithContentsOfFile: method. Program 19.2 reads back the glossary written in Program 19.1 and then displays its contents. Program 19.2 #import <Foundation/NSObject.h> #import <Foundation/NSString.h> #import <Foundation/NSDictionary.h> #import <Foundation/NSEnumerator.h> read more..

  • Page - 448

    438 Chapter 19 Archiving trieved in any order. Furthermore, if new instance variables are added or removed to a class, your program can account for it. Note that NSArchiver is not available in the iPhone SDK. If you want to use archiv- ing on the iPhone, you must use NSKeyedArchiver To work with keyed archives you need to import <Foundation/NSKeyedArchiver.h> . Program 19.3 read more..

  • Page - 449

    439 Archiving with NSKeyedArchiver writes the dictionary glossary to the file glossary.archive . Any pathname can be specified for the file. In this case, the file is written to the current directory. The archive file created can later be read into your program by using NSKeyedUnarchiver ’s unArchiveObjectWithFile: method, as is done in Program 19.4. Program 19.4 #import read more..

  • Page - 450

    440 Chapter 19 Archiving Table 19.1 Encoding and Decoding Basic Data Types in Keyed Archives Encoder Decoder encodeBool:forKey: decodeBool:forKey: encodeInt:forKey: decodeInt:forKey: encodeInt32:forKey: decodeInt32:forKey: encodeInt64: forKey: decodeInt64:forKey: Writing Encoding and Decoding Methods Basic Objective-C class objects such as NSString , NSArray , NSDictionary , NSSet , NSDate , NSNumber , and NSData can read more..

  • Page - 451

    441 Writing Encoding and Decoding Methods Table 19.1 Encoding and Decoding Basic Data Types in Keyed Archives Encoder Decoder encodeFloat:forKey: decodeFloat:forKey: encodeDouble:forKey: decodeDouble:forKey: Program 19.5 adds the two encoding and decoding methods to both the AddressCard and AddressBook classes. Program 19.5 Addresscard.h Interface File #import <Foundation/NSObject.h> #import read more..

  • Page - 452

    442 Chapter 19 Archiving The encoding method encodeWithCoder: is passed an NSCoder object as its argu- ment. Since your AddressCard class inherits directly from NSObject, you don’t need to worry about encoding inherited instance variables. If you did, and if you knew the super- class of your class conformed to the NSCoding protocol, you should start your encoding method with a read more..

  • Page - 453

    443 Writing Encoding and Decoding Methods [encoder encodeObject: bookName forKey: “AddressBookBookName”]; [encoder encodeObject: book forKey: @ ”AddressBookBook”]; } -(id) initWithCoder: (NSCoder *) decoder { bookName = [[decoder decodeObjectForKey: @ ”AddressBookBookName”] retain]; book = [[decoder decodeObjectForKey: @ ”AddressBookBook”] retain]; return self; } The test program is shown next as read more..

  • Page - 454

    444 Chapter 19 Archiving // Add some cards to the address book [myBook addCard: card1]; [myBook addCard: card2]; [myBook addCard: card3]; [myBook addCard: card4]; [myBook sort]; if ([NSKeyedArchiver archiveRootObject: myBook toFile: @ ”addrbook.arch”] == NO) NSLog (@ ”archiving failed ”); [card1 release]; [card2 release]; [card3 release]; [card4 release]; [myBook release]; [pool drain]; return 0; } This read more..

  • Page - 455

    445 Writing Encoding and Decoding Methods Program 19.7 Output ======== Contents of: Steve’s Address Book ========= Jamie Baker jbaker@hitmail.com Julia Kochan jewls337@axlc.com Stephen Kochan steve@steve_kochan.com Tony Iannino tony.iannino@techfitness.com ==================================================== In the process of unarchiving the address book, the decoding read more..

  • Page - 456

    446 Chapter 19 Archiving { strVal = [[decoder decodeObjectForKey: @ ”FoostrVal”] retain]; intVal = [decoder decodeIntForKey: @ ”FoointVal”]; floatVal = [decoder decodeFloatForKey: @ ”FoofloatVal”]; return self; } @end The encoding routine first encodes the string value strVal using the encodeObject:forKey: method, as was shown previously. In Program 19.8, a Foo object is created, archived to a read more..

  • Page - 457

    447 Using NSData to Create Custom Archives Some of the basic data types, such as char , short , long , and long long , are not listed in Table 19.1; you must determine the size of your data object and use the appropriate routine. For example, a short int is normally 16 bits, an int and long can be 32 or 64 bits, and a long long is 64 bits. (You can use the read more..

  • Page - 458

    448 Chapter 19 Archiving int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Foo *myFoo1 = [[Foo alloc] init]; Foo *myFoo2; NSMutableData *dataArea; NSKeyedArchiver *archiver; AddressBook *myBook; // Insert code from Program 19.7 to create an Address Book // read more..

  • Page - 459

    449 Using NSData to Create Custom Archives When you are finished archiving your two objects, you send the archiver object the finishEncoding message. No more objects can be encoded after that point, and you need to send this message to complete the archiving process. The area you set aside and named dataArea now contains your archived objects in a form that you can write to a read more..

  • Page - 460

    450 Chapter 19 Archiving if (! dataArea) { NSLog (@ “Can’t read back archive file!”); Return (1); } unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: dataArea]; // Decode the objects we previously stored in the archive myBook = [unarchiver decodeObjectForKey: @ ”myaddrbook”]; myFoo1 = [unarchiver decodeObjectForKey: @ ”myfoo1”]; [unarchiver finishDecoding]; [unarchiver release]; // Verify read more..

  • Page - 461

    451 Using the Archiver to Copy Objects You can use the Foundation’s archiving capabilities to create a deep copy of an ob- ject. For example, Program 19.11 copies dataArray to dataArray2 by archiving dataArray into a buffer and then unarchiving it, assigning the result to dataArray2 .You don’t need to use a file for this process; the archiving and unarchiving process can all read more..

  • Page - 462

    452 Chapter 19 Archiving Program 19.11 Output dataArray: one two three dataArray2: oneONE two three The output verifies that changing the first element of dataArray2 had no effect on the first element of dataArray .That’s because a new copy of the string was made through the archiving/unarchiving process. The copy operation in Program 19.11 is performed with the following two lines: data read more..

  • Page - 463

    Part III Cocoa and the iPhone SDK 20 Introduction to Cocoa 21 Writing iPhone Applications read more..

  • Page - 464

    read more..

  • Page - 465

    20 Introduction to Cocoa Throughout this book you developed programs that had a simple user interface.You re- lied on the NSLog routine to display messages on the console. However, as useful as this routine is, it is very limited in its capabilities. Certainly, other programs you use on the Mac aren’t as unfriendly. In fact, the Mac’s reputation is based on its read more..

  • Page - 466

    456 Chapter 20 Introduction to Cocoa Cocoa (Foundation and AppKit Frameworks) Application Application Services Core Services Mac OS X kernel User Computer Resources (memory, disk, display, etc.) Figure 20.1 The application hierarchy Directly below your application sits the Cocoa layer. As noted, Cocoa includes the Foundation and AppKit frameworks. Foundation offers classes for working with read more..

  • Page - 467

    457 Cocoa Touch Whereas the Cocoa frameworks are designed for application development for Mac OS X desktop and notebook computers, the Cocoa Touch frameworks are for applications targeted for the iPhone and iTouch. Both Cocoa and Cocoa Touch have the Foundation framework in common. However, the UIKit replaces the AppKit framework under Cocoa Touch, providing support for many of the read more..

  • Page - 468

    read more..

  • Page - 469

    21 Writing iPhone Applications In this chapter, you’ll develop two simple iPhone applications.The first illustrates some fundamental concepts to familiarize you with using Interface Builder, making connec- tions, and understanding delegates, outlets, and actions. For the second iPhone application, you’ll build a fraction calculator. It combines what you learned while developing the first read more..

  • Page - 470

    460 Chapter 21 Writing iPhone Applications Figure 21.1 First iPhone application. Let’s dive right into the first program.The pedagogy used in this chapter is not to cover all the details; as noted, there’s simply not enough space to do that here. Instead, we walk you through the steps to give you the necessary foundation (no pun intended!) for you to explore and learn read more..

  • Page - 471

    461 Your First iPhone Application Figure 21.2 iPhone application results. Contacts application, and so on.The simulator makes it much easier to debug your appli- cations; you don’t have to download each iteration of your application to an actual iPhone device and then debug it there.This can save you a lot of time and effort. To run applications on the iPhone device, you read more..

  • Page - 472

    462 Chapter 21 Writing iPhone Applications Figure 21.3 Starting a new iPhone project. Table 21.1 iPhone Application Templates Application Type Description Navigation-Based For an application that uses a navigation controller. Contacts is a sample application of this type. OpenGL ES For OpenGL graphics-based applications such as games. Tab Bar For applications that use a tab bar. An example would read more..

  • Page - 473

    463 Your First iPhone Application Figure 21.4 New iPhone project iPhone_1 is created. Returning to your New Project window, select Window-Based Application in the top rightmost pane and then click on the Choose button.When next prompted to enter the project name (in the Save As box), enter the text iPhone_1 and click Save.This also be- comes your application’s name by default. read more..

  • Page - 474

    464 Chapter 21 Writing iPhone Applications Figure 21.5 iPhone_1 project with SDK and Configuration options set. ods to respond to actions that occur in the iPhone’s window, such as the pressing of a but- ton or the movement of a slider. As you’ll see, it’s in the Interface Builder application that you make the actual connection between these controls and the corresponding read more..

  • Page - 475

    465 Your First iPhone Application UILabel *display; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UILabel *display; - (IBAction) click1: (id) sender; @end Notice that iPhone applications import the header file <UIKit/UIKit.h> .This header file, in turn, imports other UIKit header files, in a similar way that the Foundation.h header file read more..

  • Page - 476

    466 Chapter 21 Writing iPhone Applications identifier when it examines your header file to identify methods that can be used as ac- tions. Now it’s time to modify the corresponding iPhone_1AppDelegate.m implementation file for your class. Here you synthesize the accessor methods for your display variable (the window access methods are already synthesized for you) and add the definition read more..

  • Page - 477

    467 Your First iPhone Application Designing the Interface In Figure 21.4, and in your Xcode main window, notice a file called MainWindow.xib .An xib file contains all the information about the user interface for your program, including information about its windows, buttons, labels, tab bars, text fields, and so on. Of course you don’t have a user interface yet! That’s the read more..

  • Page - 478

    468 Chapter 21 Writing iPhone Applications Figure 21.7 Interface Builder MainWindow.xib. The window simply labeled Window shows the layout of the iPhone’s main window. Because you haven’t designed anything for your iPhone’s window yet, it starts out empty, as shown in Figure 21.8. The first thing we’ll do is set the iPhone’s window to black.To do this, first click inside read more..

  • Page - 479

    469 Your First iPhone Application Figure 21.8 Interface Builder iPhone window. Figure 21.9 Interface Builder Inspector window. read more..

  • Page - 480

    470 Chapter 21 Writing iPhone Applications Figure 21.10 Changing the window’s background color. Figure 21.11 Interface window changes to black. read more..

  • Page - 481

    471 Your First iPhone Application You can always reposition the label in the window at any time in the future by click- dragging it to another spot inside the window. Let’s now set some attributes for this label. In your window, if it’s not currently se- lected, click the label you just created to select it. Notice that the Inspector window auto- matically changes to read more..

  • Page - 482

    472 Chapter 21 Writing iPhone Applications two ways: by double-clicking on the button and then typing your text, or by setting the Title field in the Inspector window. Either way you choose, make you window match the one shown in Figure 21.15. Now we have a label that we want to connect to our display instance variable in our program so that when we set the read more..

  • Page - 483

    473 Your First iPhone Application Figure 21.14 Sizing and positioning a label. Figure 21.15 Adding a button to the interface. read more..

  • Page - 484

    474 Chapter 21 Writing iPhone Applications Figure 21.16 Adding an action for a button. For this sequence to work, we just need to make the two connections. Let’s discuss how to do it. First, let’s connect the button to the IBAction method click1: .You do this by hold- ing down the Control key while you click on the button and drag the blue line that ap- pears on read more..

  • Page - 485

    475 Your First iPhone Application Figure 21.17 Connecting the event to the method. Figure 21.18 Connecting an outlet variable. read more..

  • Page - 486

    476 Chapter 21 Writing iPhone Applications When you release the mouse, you get a list of IBOutlet variables of the corresponding class as the control (UILabel) to choose from.We have one such variable in our program, and it’s called display . Choose this variable (as shown in Figure 21.19) and make the connection. That’s it; you’re done! Select File->Save from read more..

  • Page - 487

    477 An iPhone Fraction Calculator a summary of the steps and an overview of the design methodology. Of course, we’ll also show all the code. First, let’s see how the application works. Figure 21.20 shows what the application looks like in the simulator just after launching. The calculator application allows you to enter fractions by first keying in the numera- tor, pressing read more..

  • Page - 488

    478 Chapter 21 Writing iPhone Applications Figure 21.21 Keying in an operation. The display is continuously updated as keys are pressed. Figure 21.21 shows the display after the fraction 4/6 has been entered and the multiplication key has been pressed. Figure 21.22 shows the result of multiplying the fractions 4/6 and 2/8 together.You’ll note that the result of 1/6 indicates that read more..

  • Page - 489

    479 An iPhone Fraction Calculator When your project is created, this time you’ll notice you get two class templates de- fined for you. Fraction_CalculatorAppDelegate.h and Fraction_CalculatorAppDelegate.m define the application’s controller class for your project, while Fraction_CalculatorViewController.h and Fraction_CalculatorViewController.m define the view controller class for your proj- ect. As noted, read more..

  • Page - 490

    480 Chapter 21 Writing iPhone Applications @property (nonatomic, retain) UIWindow *window; @property (nonatomic, retain) Fraction_CalculatorViewController *viewController; @end The UIWindow instance variable window serves the same purpose as in the first pro- gram example: it represents the iPhone’s window.The Fraction_CalculatorViewController instance variable represents the view controller that will manage read more..

  • Page - 491

    481 An iPhone Fraction Calculator int currentNumber; NSMutableString *displayString; BOOL firstOperand, isNumerator; Calculator *myCalculator; } @property (nonatomic, retain) IBOutlet UILabel *display; @property (nonatomic, retain) NSMutableString *displayString; -(void) processDigit: (int) digit; -(void) processOp: (char) op; -(void) read more..

  • Page - 492

    482 Chapter 21 Writing iPhone Applications // Override point for customization after application launch firstOperand = YES; isNumerator = YES; self.displayString = [NSMutableString stringWithCapacity: 40]; myCalculator = [[Calculator alloc] init]; [window makeKeyAndVisible]; } -(void) processDigit: (int) digit { currentNumber = currentNumber * 10 + digit; [displayString appendString: [NSString stringWithFormat: read more..

  • Page - 493

    483 An iPhone Fraction Calculator if (firstOperand) { if (isNumerator) { myCalculator.operand1.numerator = currentNumber; myCalculator.operand1.denominator = 1; // e.g. 3 * 4/5 = } else myCalculator.operand1.denominator = currentNumber; } else if (isNumerator) { myCalculator.operand2.numerator = currentNumber; myCalculator.operand2.denominator = 1; // e.g. 3/2 * 4 = } else { myCalculator.operand2.denominator = read more..

  • Page - 494

    484 Chapter 21 Writing iPhone Applications [displayString appendString: @ ” = “]; [displayString appendString: [myCalculator.accumulator convertToString]]; [display setText: displayString]; currentNumber = 0; isNumerator = YES; firstOperand = YES; [displayString setString: @ ””]; } -(IBAction) clickClear: (id) sender { isNumerator = YES; firstOperand = YES; currentNumber = 0; [myCalculator clear]; read more..

  • Page - 495

    485 An iPhone Fraction Calculator There are a lot more buttons in Program 21.2 than in the first application. Most of the complexity in the view controller’s implementation file revolves around building the frac- tions and displaying them. As noted, as a digit button 0–9 gets pressed, the action method clickDigit : gets executed.That method calls the processDigit: method to tack read more..

  • Page - 496

    486 Chapter 21 Writing iPhone Applications Program 21.2 Fraction.m Implementation File #import “Fraction.h” @implementation Fraction @synthesize numerator, denominator; -(void) setTo: (int) n over: (int) d { numerator = n; denominator = d; } -(void) print { NSLog (@ ”%i/%i”, numerator, denominator); } -(double) convertToNum { if (denominator != 0) return (double) numerator / denominator; else return read more..

  • Page - 497

    487 An iPhone Fraction Calculator resultNum = numerator * f.denominator + denominator * f.numerator; resultDenom = denominator * f.denominator; [result setTo: resultNum over: resultDenom]; [result reduce]; return [result autorelease]; } -(Fraction *) subtract: (Fraction *) f { // To sub two fractions: // a/b - c/d = ((a*d) - (b*c)) / (b * d) Fraction *result = [[Fraction alloc] init]; int read more..

  • Page - 498

    488 Chapter 21 Writing iPhone Applications while (v != 0) { temp = u % v; u = v; v = temp; } numerator /= u; denominator /= u; } @end The convertToString: method checks the numerator and denominator of the frac- tion to produce a more eye-pleasing result. If the numerator and denominator are equal (but not zero), we return @ ”1”. If the numerator is zero, the string read more..

  • Page - 499

    489 An iPhone Fraction Calculator @synthesize operand1, operand2, accumulator; -(id) init { self = [super init]; operand1 = [[Fraction alloc] init]; operand2 = [[Fraction alloc] init]; accumulator = [[Fraction alloc] init]; return self; } -(void) clear { if (accumulator) { accumulator.numerator = 0; accumulator.denominator = 0; } } -(Fraction *) performOperation: (char) op { Fraction *result; switch read more..

  • Page - 500

    490 Chapter 21 Writing iPhone Applications Designing the UI You may have noticed that you have two xib files in your project’s Resources folder: one called MainWindow.xib and the other called Fraction_CalculatorViewController.xib .You don’t need to work with the former file at all, so open up the latter by double-clicking on its file name.When Interface Builder starts up, read more..

  • Page - 501

    491 Summary Summary Figure 21.24 shows the Xcode project window so that you can see all the files related to the Fraction calculator project. Figure 21.24 Fraction calculator project files. The following summarizes the steps you followed to create you iPhone fraction calcu- lator application: 1. Created a new View-based Application. 2. Entered your UI code into the read more..

  • Page - 502

    492 Chapter 21 Writing iPhone Applications 8. Control-click-dragged from each button in the View window to the File ’s Owner and made the connection to the appropriate action method. For each digit button, you selected the clickDigit: method. Also, for each digit button, you set the tag button attribute to the corresponding digit 0-9 so that the clickDigit: method could identify read more..

  • Page - 503

    493 Exercises Figure 21.25 Adding an application icon. read more..

  • Page - 504

    read more..

  • Page - 505

    Part IV Appendixes A Glossary B Objective-C Language Summary C Address Book Source Code D Resources read more..

  • Page - 506

    read more..

  • Page - 507

    Glossary This appendix contains informal defini- tions for many of the terms you will encounter. Some of these terms have to do directly with the Objective-C lan- guage itself, whereas others gain their etymology from the discipline of object- oriented programming. In the latter case, I provide the meaning of the term as it specifically applies to the Objective-C language. abstract read more..

  • Page - 508

    automatic variable A variable that is automatically allocated and released when a statement block is entered and exited. Automatic variables have scope that is limited to the block in which they are defined and have no default initial value.They are optionally preceded by the keyword auto . autorelease pool An object defined in the Foundation framework that keeps track of objects read more..

  • Page - 509

    delegate An object directed to carry out an action by another object. designated initializer The method that all other initialization methods in the class, or in subclasses (through messages to super ), will invoke. dictionary A collection of key/value pairs implemented under Foundation with the NSDictionary and NSMutableDictionary classes. directive In Objective-C, a special construct that begins read more..

  • Page - 510

    gdb The standard debugging tool for programs compiled with gcc. getter method An accessor method that retrieves the value of an instance variable. See also setter method. global variable A variable defined outside any method or function that can be accessed by any method or function in the same source file or from other source files that declare the variable as extern . header file read more..

  • Page - 511

    and handling things such as local time zones, currency symbols, date formats, and so on. Sometimes localization is used just to refer to the language translation, and the term internationalization is used to refer to the rest of the process. message The method and its associat- ed arguments that are sent to an object (the receiver). message expression An expression enclosed in square read more..

  • Page - 512

    property declaration A way to speci- fy attributes for instance variables that enables the compiler to generate leak- free and thread-safe accessor methods for instance variables. Property declarations can also be used to declare attributes for accessor methods that will be dynamical- ly loaded at runtime. property list A representation of dif- ferent types of objects in a standardized read more..

  • Page - 513

    super A keyword used in a method to refer to the parent class of the receiver. super class The parent class of a par- ticular class. See also super . synthesized method A setter or get- ter method that the compiler automati- cally creates for you. It was added to the Objective C 2.0 language. UIKit A framework for developing applications on the iPhone and iTouch. In addition read more..

  • Page - 514

    read more..

  • Page - 515

    Digraph Meaning <: [ :> ] <% { %> } %: # %:%: ## Appendix B Objective-C 2.0 Language Summary This appendix summarizes the Objective-C language in a format suitable for quick ref- erence. It is not intended to be a complete definition of the language, but rather a more informal description of its features.You should thoroughly read the material in this ap- pendix after you read more..

  • Page - 516

    506 Appendix B Objective-C 2.0 Language Summary Identifiers An identifier in Objective-C consists of a sequence of letters (upper- or lowercase), univer- sal character names (1.2.1), digits, or underscore characters.The first character of an iden- tifier must be a letter, an underscore, or a universal character name.The first 31 characters of an identifier are guaranteed to be significant read more..

  • Page - 517

    507 Digraphs and Identifiers Table B.1 Compiler Directives Directive Meaning Example @ ”chars” Defines a constant NSSTRING character string object (Adjacent strings are concatenated.) NSString *url = @ ”http://www.kochan-wood.com”; @class c1, c2,... Declares c1, c2, ... as classes. @class Point, Rectangle; @defs ( class) Returns a list of the structure variables for class. struct Fract { read more..

  • Page - 518

    508 Appendix B Objective-C 2.0 Language Summary Table B.1 Compiler Directives Directive Meaning Example @interface Begins an interface section. @interface Fraction: NSObject <Copying> @private Defines the scope of one or more instance variables. See “Instance Variables.” @protected Defines the scope of one or more instance variables @public Defines the scope of one or more instance variables read more..

  • Page - 519

    509 Comments Predefined Identifiers Table B.2 lists identifiers that have special meanings in Objective-C programs. Table B.2 Special Predefined Identifiers Identifier Meaning _cmd A local variable automatically defined in a method that contains the selector for the method _ _ func_ _ A local character string variable automatically defined in a function or method containing the name of the read more..

  • Page - 520

    510 Appendix B Objective-C 2.0 Language Summary Constants Integer Constants An integer constant is a sequence of digits, optionally preceded by a plus or minus sign. If the first digit is 0 , the integer is taken as an octal constant, in which case all digits that fol- low must be 0 –7. If the first digit is 0 and is immediately followed by the letter x (or X ), read more..

  • Page - 521

    511 Constants Character Meaning \a Audible alert \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \\ Backslash \ ” Double quote \ ’ Single quote \? Question mark \ nnn Octal character value \u nnnn Universal character name \U nnnnnnnn Universal character name \x nn Hexadecimal character value exponent) represents the power of 10 by which the value read more..

  • Page - 522

    512 Appendix B Objective-C 2.0 Language Summary In the octal character case, from one to three octal digits can be specified. In the last three cases, hexadecimal digits are used. Wide Character Constants A wide character constant is written as L 'x'.The type of such a constant is wchar_t , as de- fined in the standard header file <stddef.h> .Wide character constants provide read more..

  • Page - 523

    513 Data Types and Declarations Wide Character String Constants Character string constants from an extended character set are expressed using the format L '...'.The type of such a constant is “pointer to wchar_t ,” where wchar_t is defined in <stddef.h> . Constant Character String Objects A constant character string object can be created by placing an @ character in front of read more..

  • Page - 524

    The language also enables storage to be allocated at the same time that a particular structure, union, or enumerated data type is defined.This is done by simply listing the variables before the terminating semicolon of the definition. Basic Data Types The basic Objective-C data types are summarized in Table B.3. A variable can be declared to be of a particular basic data type read more..

  • Page - 525

    Note that the signed modifier can also be placed in front of the short int, int, long int, and long long int types. Because these types are signed by default anyway, this has no ef- fect. _Complex and _Imaginary data types enable complex and imaginary numbers to be declared and manipulated, with functions in the library for supporting arithmetic on these types. Normally, you read more..

  • Page - 526

    516 Appendix B Objective-C 2.0 Language Summary Library routines such as creal and cimag can then be used to extract the real and imaginary parts of c1 , respectively. An implementation is not required to support types _Complex and _Imaginary , and it can optionally support one but not the other. Derived Data Types A derived data type is one that is built up from one or more read more..

  • Page - 527

    517 Data Types and Declarations By enclosing an element number in a pair of brackets, specific array elements can be initialized in any order. For example int x = 1233; int a[] = { [9] = x + 1, [2] = 3, [1] = 2, [0] = 1 }; defines a 10-element array called a (based on the highest index into the array) and initial- izes the last element to the value read more..

  • Page - 528

    518 Appendix B Objective-C 2.0 Language Summary Elements in the first row of matrix are set to the values 1, 2, and 3, respectively; in the second row they are set to 4, 5, and 6, respectively; and in the third row they are set to 7, 8, and 9, respectively.The elements in the fourth row are set to 0 because no values are specified for that row.The declaration int read more..

  • Page - 529

    519 Data Types and Declarations This format cannot be used if name is omitted when the structure is defined. In that case, all variables of that structure type must be declared with the definition. The format for initializing a structure variable is similar to that for arrays. Its members can be initialized by enclosing the list of initial values in a pair of curly braces. read more..

  • Page - 530

    520 Appendix B Objective-C 2.0 Language Summary or equivalently like this: struct entry { char *word; char *def; } dictionary[1000] = { { {.word = “a”, .def = “first letter of the alphabet ” }, {.word = “aardvark”, .def = “a burrowing African mammal ”} , {.word = “aback”, .def = “to startle ”} }; An automatic structure variable can be initialized to read more..

  • Page - 531

    521 Data Types and Declarations Variables can be declared at the time that the union is defined, or they can be subse- quently declared using the notation union name variableList; provided the union was given a name when it was defined. It is the programmer’s responsibility to ensure that the value retrieved from a union is consistent with the last value stored inside the read more..

  • Page - 532

    522 Appendix B Objective-C 2.0 Language Summary declares myFract to be an object of type Fraction —or more explicitly, myFract is used to hold a pointer to the object’s data structure after an instance of the object is created and assigned to the variable. Pointers that point to elements in an array are declared to point to the type of element contained in the array. For read more..

  • Page - 533

    523 Data Types and Declarations If you want to declare variables to be of a previously defined (and named) enumera- tion type, you can use the following construct: enum name variableList; A variable declared to be of a particular enumerated type can be assigned only a value of the same data type, although the compiler might not flag this as an error. typedef The typedef read more..

  • Page - 534

    524 Appendix B Objective-C 2.0 Language Summary The restrict keyword can be used with pointers. It is a hint to the compiler for op- timization (similar to the register keyword for variables).The restrict keyword speci- fies to the compiler that the pointer will be the only reference to a particular object—that is, it will not be referenced by any other pointer within the read more..

  • Page - 535

    525 Expressions Table B.4 Summary of Objective-C Operators Operator Description Associativity () Function call [] Array element reference or message expression -> Pointer to structure member reference Left to right . Structure member reference or method call - Unary minus + Unary plus ++ Increment -- Decrement ! Logical negation ~ Ones complement Right to left * Pointer reference (indirection) & read more..

  • Page - 536

    526 Appendix B Objective-C 2.0 Language Summary Because the modulus and multiplication operators appear in the same grouping in Table B.4, they have the same precedence.The associativity listed for these operators is left to right, indicating that the expression would be evaluated as follows: ( b % c ) * d As another example, the expression ++a->b would be evaluated as read more..

  • Page - 537

    527 Expressions it is not defined whether the compiler will evaluate the left side of the plus operator or the right side first. Here, the way that it’s done affects the result because the value of i might be incremented before x[i] is evaluated. Another case in which the order of evaluation is not defined is in the expression shown here: x[i] = ++i In this situation, read more..

  • Page - 538

    528 Appendix B Objective-C 2.0 Language Summary Constant Expressions A constant expression is an expression in which each of the terms is a constant value. Con- stant expressions are required in the following situations: 1. As the value after a case in a switch statement 2. For specifying the size of an array 3. For assigning a value to an enumeration identifier 4. For specifying read more..

  • Page - 539

    529 Expressions Arithmetic Operators Given that In each expression, the usual arithmetic conversions are performed on the operands (see the section “Conversion of Basic Data Types”). If a is unsigned, -a is calculated by first applying integral promotion to it, subtracting it from the largest value of the pro- moted type, and adding 1 to the result. If two integral values are read more..

  • Page - 540

    530 Appendix B Objective-C 2.0 Language Summary The usual arithmetic conversions are applied to a and b (see the section “Conversion of Basic Data Types”).The type of the result in all cases is int . Relational Operators Given that The usual arithmetic conversions are performed on a and b (see the section “Conver- sion of Basic Data Types”).The first four relational tests are read more..

  • Page - 541

    531 Expressions The usual arithmetic conversions are performed on the operands, except with << and >> , in which case just integral promotion is performed on each operand (see the section “Conversion of Basic Data Types”). If the shift count is negative or is greater than or equal to the number of bits contained in the object being shifted, the result of the read more..

  • Page - 542

    532 Appendix B Objective-C 2.0 Language Summary In the first expression, if a is one of the basic data types (except void ), it is converted to match the type of l . If l is a pointer, a must be a pointer to the same type as l ,a void pointer, or the null pointer. If l is a void pointer, a can be of any pointer type.The second expression is treated as if it read more..

  • Page - 543

    533 Expressions If type is char , the result is defined to be 1 . If a is the name of an array that has been dimensioned (either explicitly or implicitly through initialization) and is not a formal pa- rameter or undimensioned extern array, sizeof a gives the number of bytes required to store the elements in a. If a is the name of a class, sizeof (a) gives the size of read more..

  • Page - 544

    534 Appendix B Objective-C 2.0 Language Summary In each case, the type of the result is the type of the elements contained in a . See the section “Basic Operations with Pointers” for a summary of operations with pointers and arrays. Basic Operations with Structures Note This also applies to unions. Given that x is a modifiable lvalue expression of type struct s ; y is an read more..

  • Page - 545

    535 Expressions Basic Operations with Pointers Given that x.m = v assigns v to the member m of x and is of the type declared for the member m ; x = y assigns y to x and is of type struct s ; f (y) calls the function f , passing contents of the structure y as the argument (inside f , the formal parameter must be declared to be of type struct s ); [obj M: y] read more..

  • Page - 546

    536 Appendix B Objective-C 2.0 Language Summary Pointers to Arrays Given that a is an array of elements of type t ; pa1 is a modifiable lvalue expression of type “pointer to t ” that points to an element in a ; pa2 is an lvalue expression of type “pointer to t ” that points to an element in a , or to one past the last element in a ; v is an expression; n is read more..

  • Page - 547

    537 Expressions pa2 - pa1 produces the number of elements in a contained between the pointers pa2 and pa1 (assuming that pa2 points to an element further in a than pa1 ) and has integer type; a + n produces a pointer to element number n of a , has type “pointer to t ,” and is in all ways equivalent to the expression &a[n] ; *(a + n) references element number n of read more..

  • Page - 548

    538 Appendix B Objective-C 2.0 Language Summary Compound Literals A compound literal is a type name enclosed in parentheses followed by an initialization list. It creates an unnamed value of the specified type, which has scope limited to the block in which it is created, or global scope if defined outside of any block. In the latter case, the initializers must all be constant read more..

  • Page - 549

    539 Storage Classes and Scope 6. If the unsigned operand is equal in size or larger than the signed operand, the signed operand is converted to the type of the unsigned operand, and that is the type of the result. 7. If the signed operand can represent all the values in the unsigned operand, the latter is converted to the type of the former if it can fully represent read more..

  • Page - 550

    540 Appendix B Objective-C 2.0 Language Summary defined outside it. Label names are known throughout the BLOCK, as are formal param- eter names. Labels, instance variables, structure and structure member names, union and union member names, and enumerated type names do not have to be distinct from each other or from variable, function, or method names. However, enumeration read more..

  • Page - 551

    541 Storage Classes and Scope Instance Variables Instance variables can be accessed by any instance method defined for the class, either in the interface section that explicitly defines the variable or in categories created for the class. Inherited instance variables can also be accessed directly without any special declara- tions. Class methods do not have access to instance read more..

  • Page - 552

    542 Appendix B Objective-C 2.0 Language Summary another of the three listed directives is used. For example, the following begins an inter- face declaration for a class called Point containing four instance variables: @interface Point: NSObject { @private int internalID; @protected float x; float y; @public BOOL valid; } The internalID variable is private , the x and y variables are read more..

  • Page - 553

    543 Functions Functions This section summarizes the syntax and operation of functions. Function Definition General Format: returnType name ( type1 param1, type2 param2, .. ) { variableDeclarations programStatement programStatement ... return expression; } The funct on called name is defined, which returns a value of type returnType and has formal parameters param1 , param2 , .... param1 is declared to read more..

  • Page - 554

    544 Appendix B Objective-C 2.0 Language Summary Here, just the parameter names are listed inside the parentheses. If no arguments are expected, nothing appears between the left and right parentheses.The type of each pa- rameter is declared outside the parentheses and before the opening curly brace of the function definition. For example, the following defines a function called rotate read more..

  • Page - 555

    545 Functions declares power to be a function that returns a long double and that takes two argu- ments—the first of which is a double and the second of which is an int .The argument names inside the parentheses are actually dummy names and can be omitted if desired, so long double power (double, int); works just as well. If the compiler has previously encountered the read more..

  • Page - 556

    546 Appendix B Objective-C 2.0 Language Summary Classes This section summarizes the syntax and semantics associated with classes. Class Definition A class definition consists of declaring the instance variables and methods in an interface section and defining the code for each method in an implementation section. Interface Section General Format: @interface className : parentClass < protocol, read more..

  • Page - 557

    547 Classes You can only specify one of the attributes assign , copy , or retain . If you don’t use garbage collection, then one of these attributes should be explicitly used; otherwise you will get a warning from the compiler. If you use garbage collection and you don’t specify one of these three attributes, the default attribute, assign , will be used. In that case, read more..

  • Page - 558

    548 Appendix B Objective-C 2.0 Language Summary Method Declaration General Format: mType ( returnType) name1 : ( type1) param1 name2 : ( type2) param2, ...; The method name1:name2:.. is declared, which returns a value of type returnType and has formal parameters param1 , param2 , .... param1 is declared to be of type type1 , param2 is declared to be of type type2 , and so on. Any read more..

  • Page - 559

    549 Classes object. It has two instance methods called setTo:: and setNumerator:andDenominator: , each of which takes two arguments and does not re- turn a value. It also has two instance methods called numerator and denominator that take no arguments and return an int . Implementation Section General Format: @implementation className; methodDefinition methodDefinition ... @end The class called read more..

  • Page - 560

    550 Appendix B Objective-C 2.0 Language Summary An instance method can reference the class’s instance variables and any variables it has inherited directly by name. If a class method is being defined, it cannot reference any in- stance variables. The identifier self can be used inside a method to reference the object on which the method was invoked—that is, the receiver of read more..

  • Page - 561

    551 Classes Category Definition General Format: @interface className ( categoryName) <protocol,...> methodDeclaration methodDeclaration ... @end This defines the category categoryName for the class specified by className with the associated listed methods. If one or more protocols are listed, the category adopts the listed protocols. The compiler must know about className through a previous read more..

  • Page - 562

    552 Appendix B Objective-C 2.0 Language Summary } -(Complex *) exp { ... } -(Complex *) log { ... } -(Complex *) sqrt { ... } @end A category that defines methods meant for other subclasses to implement is known as an informal protocol or abstract category. Unlike formal protocols, the compiler does not perform any checks for conformance to an informal protocol. At runtime, an read more..

  • Page - 563

    553 Classes The @optional directive can precede a list of methods whose implementation is op- tional. An @required directive can subsequently be used to resume the list of required methods that must be implemented for conformance to the protocol. Protocols are often not associated with any particular class but provide a way to define a common interface that is shared among read more..

  • Page - 564

    554 Appendix B Objective-C 2.0 Language Summary Object Declaration General Format: className * var1, * var2, ...; This defines var1 , var2 , ... to be objects from the class className . Note that this de- clares pointer variables and does not reserve space for the actual data contained in each object.The declaration Fraction *myFract; defines myFract as a Fraction object or, technically, read more..

  • Page - 565

    555 Classes method. So, if the add: method takes an integer argument and you are passing it a Fraction object above, the compiler complains. The system keeps track of the class to which each object belongs; therefore, at runtime it can determine the class of an object and then select the correct method to invoke. These two processes are known as dynamic typing and dynamic read more..

  • Page - 566

    556 Appendix B Objective-C 2.0 Language Summary All arguments to a method are passed by value; therefore, their values cannot be changed by the method. If a pointer is passed to a method, the method can change values referenced by the pointer, but it still cannot change the value of the pointer itself. Format 3: receiver.property This calls the getter method (by default read more..

  • Page - 567

    557 Statements Execution of a break statement from within a for , while , do , or switch statement causes execution of that statement to be immediately terminated. Execution continues with the statement that immediately follows the loop or switch . The continue Statement General Format: continue; Execution of the continue statement from within a loop causes any statements that follow the read more..

  • Page - 568

    558 Appendix B Objective-C 2.0 Language Summary Format 2: for ( var in expression ) programStatement This variant of the for loop sets up a fast enumeration. var is a variable whose type can also be declared, making its scope local to the for loop. expression is an expression that produces a result that conforms to the NSFastEnumeration protocol.Typically, expression is a collection, read more..

  • Page - 569

    559 Statements programStatement_1 else if ( expression_2 ) programStatement_2 ... else programStatement_n An else clause is always associated with the last if statement that does not contain an else . Braces can be used to change this association if necessary. The null Statement General Format: ; Execution of a null statement has no effect and is used primarily to satisfy the require- ment read more..

  • Page - 570

    560 Appendix B Objective-C 2.0 Language Summary The switch Statement General Format: switch ( expression ) { case constant_1: programStatement programStatement ... break; case constant_2: programStatement programStatement ... break; ... case constant_n: programStatement programStatement ... break; default: programStatement programStatement ... break; } expression is evaluated and compared against the constant expression values read more..

  • Page - 571

    561 Preprocessor Exception Handling Exceptions can be handled at runtime by enclosing statements that might generate an ex- ception inside an @try block, whose general format is as follows: @try programStatement 1 @catch ( exception) programStatement 2 @catch ( exception) ... @finally programStatement n If an exception is thrown by programStatement 1 , the @catch blocks that follow will be read more..

  • Page - 572

    562 Appendix B Objective-C 2.0 Language Summary Preprocessor Directives All preprocessor directives begin with the character # , which must be the first nonwhite- space character on the line.The # can be optionally followed by one or more space or tab characters. The #define Directive Format 1: #define name text This defines the identifier name to the preprocessor and associates with read more..

  • Page - 573

    563 Preprocessor If a definition requires more than one line, each line to be continued must end with a backslash character. After a name has been defined, it can be used anywhere in the file. The # operator is permitted in #define directives that take arguments and is followed by the name of an argument to the macro.The preprocessor puts double quotation marks around the read more..

  • Page - 574

    564 Appendix B Objective-C 2.0 Language Summary printx(10) produces printf ( “x10 = %i\n ”, x10); after substitution and concatenation of the character strings. Spaces are not required around the # and ## operators. The #error Directive General Format: #error text ... The specified text is written as an error message by the preprocessor. The #if Directive Format 1: #if constant_expression ... read more..

  • Page - 575

    565 Preprocessor ... #endif causes the code between the #if and #endif to be processed if the identifier DEBUG has been previously defined (see also #ifdef in the next section).The parentheses are not nec- essary around the identifier, so #if defined DEBUG works just as well. The #ifdef Directive General Format: #ifdef identifier ... #endif If the value of identifier has been previously read more..

  • Page - 576

    566 Appendix B Objective-C 2.0 Language Summary Format 2: #import < fileName> If the file has not been previously included, the preprocessor searches for the specified file only in the standard places. Specifically, the current source directory is omitted from the search.The action taken after the file is found is otherwise identical to that described previously. In either format, read more..

  • Page - 577

    567 Preprocessor The #undef Directive General Format: #undef identifier The specified identifier becomes undefined to the preprocessor. Subsequent #ifdef or #ifndef directives behave as if the identifier were never defined. The # Directive This is a null directive and is ignored by the preprocessor. Predefined Identifiers The following identifiers are defined by the preprocessor: Identifier read more..

  • Page - 578

    read more..

  • Page - 579

    Appendix C Address Book Source Code For your reference purposes, here are the complete interface and implementation files for the address book example you worked with throughout Part II,“The Foundation Framework.”This includes the definitions for the AddressCard , and AddressBook classes. You should implement these classes on your system; then extend the class definitions to make them read more..

  • Page - 580

    570 Appendix C Address Book Source Code AddressBook Interface File #import <Foundation/Foundation.h> #import “AddressCard.h” @interface AddressBook: NSObject <NSCopying, NSCoding> { NSString *bookName; NSMutableArray *book; } @property (nonatomic, copy) NSString *bookName; @property (nonatomic, copy) NSMutableArray *book; -(id) initWithName: (NSString *) name; -(void) sort; read more..

  • Page - 581

    571 AddressCard Implementation File } -(void) print { NSLog (@ ”====================================”); NSLog (@ ”| | ”); NSLog (@ ”| %-31s | ”, [name UTF8String]); NSLog (@ ”| %-31s | ”, [email UTF8String]); NSLog (@ ”| read more..

  • Page - 582

    572 Appendix C Address Book Source Code [name release]; [email release]; [super dealloc]; } @end AddressBook Implementation File #import “AddressBook.h” @implementation AddressBook @synthesize book, bookName; // set up the AddressBook ’s name and an empty book -(id) initWithName: (NSString *) name{ self = [super init]; if (self) { bookName = [[NSString alloc] initWithString: name]; book = read more..

  • Page - 583

    573 AddressBook Implementation File } -(void) list { NSLog (@ ”======== Contents of: %@ ========= ”, bookName); for ( AddressCard *theCard in book ) NSLog (@ ”%-20s %-32s ”, [theCard.name UTF8String], [theCard.email UTF8String]); NSLog (@ ”==================================================”); } // lookup address card by name — assumes an exact match -(AddressCard *) lookup: (NSString *) read more..

  • Page - 584

    574 Appendix C Address Book Source Code // Method for NSCopying protocol -(id) copyWithZone: (NSZone *) zone { AddressBook *newBook = [[self class] allocWithZone: zone]; [newBook initWithName: bookName]; [newBook setBook: book]; return newBook; } @end read more..

  • Page - 585

    Appendix D Resources This appendix contains a selective list of resources you can turn to for more informa- tion. Some of the information might be on your system, online at a Web site, or available from a book.We’ve compiled resources for C language, Objective-C, Cocoa, and iPhone/iTouch programming.This list gives you a good starting point to help you locate whatever it is read more..

  • Page - 586

    576 Appendix D Resources Websites n http://developer.apple.com/documentation/Cocoa/ObjectiveCLanguage-date.html— The part of the Apple Web site devoted to Objective-C language. Contains, among other things, online documentation, sample code, and technical notes. C Programming Language Because C is the underlying programming language, you might want to study it in more depth.The language has been read more..

  • Page - 587

    577 iPhone and iTouch Application Development Books n Introduction to Cocoa Fundamentals Guide.Apple Computer, Inc., 2007—This is an excellent text covering application development with Cocoa.You can access it from Xcode’s Documentation window.You can access it online and get a pdf ver- sion from here: http://developer.apple.com/documentation/Cocoa/Conceptual/ CocoaFundamentals/CocoaFundamentals.pdf. n Cocoa read more..

  • Page - 588

    578 Appendix D Resources Books n iPhone OS Programming Guide.Apple Computer, Inc., 2008—This is an excellent text covering application development for the iPhone.You can access it from Xcode’s Documentation window.You can access it online and get a pdf version from here: http://developer.apple.com/iphone/library/documentation/iPhone/ Conceptual/iPhoneOSProgrammingGuide/iPhoneAppProgrammingGuide.pdf. n The iPhone read more..

Write Your Review