BEGINNING Mac OS X Snow Leopard Programming

This book is for anyone who wants to get started writing programs that run on Mac OS X.

Michael Trent, Drew McCormack

676 Pages

55133 Reads



PDF Format

61.7 MB

iOS App Development

Download PDF format

  • Michael Trent, Drew McCormack   
  • 676 Pages   
  • 21 Feb 2015
  • Page - 1

    Wrox Programmer to Programmer™ Join the discussion @ Michael Trent, Drew McCormack Beginning Mac OS® X Snow Leopard® Programming Your guide to programming on the Mac OS ® X 10.6 Platform read more..

  • Page - 2

    Get more out of Programmer to Programmer™ Interact Take an active role online by participating in our P2P forums @ Wrox Online Library Hundreds of our books are available online through Wrox Blox Download short informational pieces and code to keep you up to date and out of trouble! Join the Community Sign up for our free monthly read more..

  • Page - 3

    BEGINNING MAC OS® X SNOW LEOPARD™ PROGRAMMING INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv PART I MAC OS X DEVELOPER RESOURCES CHAPTER 1 The Mac OS X Environment . . . . . . . . . . . . . . . . read more..

  • Page - 4

    ffirs.indd ii 12/12/09 1:58:02 PM read more..

  • Page - 5

    BEGINNING Mac OS® X Snow Leopard™ Programming Michael Trent and Drew McCormack ffirs.indd iii 12/12/09 1:58:02 PM read more..

  • Page - 6

    Beginning Mac OS® X Snow Leopard™ Programming Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 Copyright © 2010 by W iley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-57752-3 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, read more..

  • Page - 7

    For Angela, Katie, and Sophie —MT For Jennifer, Gileesa, and Rylan —DMc ffirs.indd v 12/12/09 1:58:04 PM read more..

  • Page - 8


  • Page - 9

    ABOUT THE AUTHORS MICHAEL TRENT has been programming in Objective-C since 1997 and programming Macs since well before that. He is a professional computer programmer and engineering manager, a technical reviewer for numerous books and magazine articles, and an occasional dabbler in Mac OS X open source projects. Currently, he is using Objective-C and Apple Computer’s Cocoa read more..

  • Page - 10

    ACKNOWLEDGMENTS I WOULD LIKE TO THANK STEVE KOCHAN for his early help with this project. Thanks also to Brett Halle, Pete Steinauer, Yaniv Gur, and many others for their encouragement. Most of all, I would like to thank my wife, Angela, and my daughters, Katie and Sophie, for putting up with all the late nights. —Michael Trent I WISH TO THANK MY WIFE, Jennifer, read more..

  • Page - 11

    CONTENTS INTRODUCTION xv PART I: MAC OS X DEVELOPER RESOURCES CHAPTER 1: THE MAC OS X ENVIRONMENT 3 Introducing the Mac OS X 4 The Core Operating System 6 The Kernel 8 The System Library 9 Unix Commands 9 Graphics and Media Layers 12 The Quartz Compositor 12 Quartz 2D 15 OpenGL 15 QuickTime 15 Core Animation 16 Application Frameworks and UI 16 Cocoa 17 read more..

  • Page - 12

    x CONTENTS Apple Developer Connection 46 Documentation 47 Examples 48 Mailing Lists 49 Developer Tools 49 Developer Support 50 Summary 50 CHAPTER 3: XCODE 53 Starting a New Project 54 Working with Files 58 Writing Your Code 63 A Second Look at Indenting 69 Building and Running 71 Finding Problems with the Static Analyzer 75 Using the Debugger 78 Online Documentation read more..

  • Page - 13

    xi CONTENTS CHAPTER 6: THE C LANGUAGE 145 A Little History 145 Getting Started 146 Variables and Data Types 149 Operators 152 Arrays and Pointers 156 Conditional Branching 163 Loops 168 Functions and Blocks 175 Characters and Strings 179 Input/Output 184 Data Structures 193 Memory Management 196 The Preprocessor 200 Organizing Programs 206 Summary 227 CHAPTER 7: THE OBJECTIVE-C read more..

  • Page - 14

    xii CONTENTS CHAPTER 9: DOCUMENT-BASED COCOA APPLICATIONS 313 Working with Documents 314 Creating a New Document 315 Subclassing Controls in Interface Builder 327 Connecting Menus 330 Summary 337 CHAPTER 10: CORE DATA–BASED COCOA APPLICATIONS 341 Archiving Objective-C Objects 342 Modeling Objects with Core Data 343 Connecting User Interface to Core Data 348 Selecting Files read more..

  • Page - 15

    xiii CONTENTS CHAPTER 12: THE BASH SHELL 425 Getting Started 425 The Command-Line Interface 426 Interactive versus Script 426 The Terminal Application 427 Editors 427 Confi guring Bash 429 Unix Basics 433 Paths 433 Locating and Learning Commands 434 Running Commands and Other Executables 436 Redirecting Input and Output 438 Navigating the File System 443 read more..

  • Page - 16

    xiv CONTENTS Classes 521 Working with Scripts 521 AppleScript Applications 531 The AppleScriptObjC Bridge 532 Using Xcode 533 Using Interface Builder 535 Summary 549 CHAPTER 14: JAVASCRIPT, DASHBOARD, AND DASHCODE 553 JavaScript 554 Dashboard 560 Dashcode 576 Summary 589 Appendix A: Answers to Exercises 591 Appendix B: Developer Resources 631 INDEX 633 ftoc.indd xiv 12/15/09 read more..

  • Page - 17

    INTRODUCTION MAC OS X REPRESENTS A UNION OF many different operating system technologies. At its core you will fi nd Unix, an operating system once reserved for high - end servers and workstations, now found on common desktop systems. With Unix comes a whole history of tools, computer languages, and runtime environments. At a higher read more..

  • Page - 18

    xvi INTRODUCTION If you are an experienced programmer familiar with one aspect of Mac OS X programming (such as shell scripting or Carbon), you can use this book to explore other aspects of Mac OS X programming. In addition, you learn how to incorporate these new techniques into your existing programming style. HOW THIS BOOK IS STRUCTURED This read more..

  • Page - 19

    xvii INTRODUCTION In Chapter 5, “ The Application, ” you pick apart the individual elements that make up an application on Mac OS X. You learn how application resources are stored and how applications work in multiple languages. Chapter 6, “ The C Language, ” offers a brief introduction to the C programming language. If you are new read more..

  • Page - 20

    xviii INTRODUCTION Examples and fi gures in this book were made using Mac OS X v10.6 Snow Leopard and Xcode 3. Although many code examples will still work on earlier versions of Mac OS X, a few have been updated using features new to Snow Leopard. Apple periodically makes new versions of Xcode available for download. Earlier versions of Xcode can be obtained at no read more..

  • Page - 21

    xix INTRODUCTION SOURCE CODE As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code fi les that accompany the book. All of the source code used in this book is available for download at . Once at the site, simply locate the book ’ s read more..

  • Page - 22

    xx INTRODUCTION At you will fi nd a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps: 1. Go to and click the Register link. 2. Read the terms of use and read more..

  • Page - 23

    PART I Mac OS X Developer Resources CHAPTER 1: The Mac OS X Environment CHAPTER 2: Developer Tools CHAPTER 3: Xcode CHAPTER 4: Interface Builder c01.indd 1 12/12/09 1:01:15 PM read more..

  • Page - 24

    c01.indd 2 12/12/09 1:01:24 PM read more..

  • Page - 25

    1 The Mac OS X Environment WHAT YOU WILL LEARN IN THIS CHAPTER: How the Mac OS X operating system is structured, including what the major areas of the system are and how they work together How to use Mac OS X ’ s command - line interface How applications take advantage of the operating system read more..

  • Page - 26

    4 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT INTRODUCING THE MAC OS X What comes to mind when you think of Mac OS X? Is it the applications you use? Perhaps you recall Mac OS X ’ s distinctive user interface? Or maybe you think of Mac OS X ’ s stability? In truth, Mac OS X embodies all these things. The read more..

  • Page - 27

    3. Run the Slide Master application by double-clicking it in Finder. The application opens an unti- tled document window. 4. Add the pictures in the Images folder to Slide Master by choosing Slide Show ➪ Add Slide. You can select all the fi les at once from the open panel. The images appear in a drawer to the side of the document read more..

  • Page - 28

    6 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT Much of the functionality you see here comes from Slide Master’s application framework: Cocoa. The Cocoa application framework provides the implementation for the things you see on the screen: win- dows, pictures, menus, buttons, and so on. Cocoa also provides support for managing the document: read more..

  • Page - 29

    Although Mac OS X tries to hide Darwin from the average user, there are some places where the Unix command line pokes through. The most obvious example is the Terminal application, found in /Application/Utilities . You can use Terminal to work directly with Darwin ’ s command - line tools. A more subtle example includes the way you read more..

  • Page - 30

    8 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT NOTE If you look in /Applications/Utilities in the Finder, you might notice that there is no; instead there ’ s just a program called Terminal. By default, Finder and other applications hide fi le extensions such as .app and .txt from you. So the read more..

  • Page - 31

    The System Library The kernel is responsible for critical functions such as memory management and device access, so programs must ask the kernel to perform work on its behalf. Programs communicate with the kernel through an application program interface (API) provided by a special library. This library defi nes some common data structures for describing read more..

  • Page - 32

    10 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT TRY IT OUT Experiencing Darwin’s Command-Line Interface 1. In the Finder, go to Applications ➪ Utilities and launch the Terminal application. You will see a few status lines of text ending in a command-line prompt (your lines may look slightly different from what is shown here): read more..

  • Page - 33

    drwx------+ 9 sample staff 306 Jul 18 23:37 FontCollections drwx------+ 2 sample staff 68 Jul 15 09:19 Fonts drwxr-xr-x 2 sample staff 68 Jul 16 00:05 Fonts Disabled drwx------+ 3 sample staff 102 Jul 15 09:19 Input Methods drwx------+ 2 sample staff 68 Jul 15 09:19 Internet Plug-Ins drwx------+ 2 sample staff read more..

  • Page - 34

    12 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT When the shell has decided which command to launch, the shell starts that command and passes the remaining fl ags and arguments into the command for further evaluation. That’s why ls , man , and echo all interpret their arguments in different ways. Flags are also interpreted by individual read more..

  • Page - 35

    Among its many duties, the Quartz Compositor handles these tasks: Manages all the windows on your screen — Although the actual look of the window may come from an application or an application framework such as Cocoa or Carbon, the Quartz Compositor provides most of the window ’ s guts: where the window sits on the screen, how the read more..

  • Page - 36

    14 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT FIGURE 1-5 WHAT ARE PDF FILES? PDF stands for Portable Document Format. The PDF standard was invented by Adobe as a means for describing documents that can be displayed or printed virtually anywhere. The fi le specifi cation itself is open, meaning the public-at-large can view the read more..

  • Page - 37

    Quartz 2D The Quartz 2D graphics library is Mac OS X ’ s native graphics library. It is responsible for all the two - dimensional drawing performed by Mac OS X. As you might imagine, Quartz 2D provides an interface for drawing two - dimensional shapes, such as lines and rectangles, and compositing images. It is also capable of read more..

  • Page - 38

    16 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT Mac OS X increased Apple ’ s commitment to QuickTime by building it directly into the operating system. Though versions of QuickTime shipped with Mac OS releases since the earliest days of QuickTime, Mac OS X actually relies on QuickTime in ways earlier OS versions did not. For read more..

  • Page - 39

    It is important that all applications present their user interface (UI) in a consistent manner, regardless of which application framework the program uses. In other words, all windows, menus, buttons, text fi elds, and so on should look and behave the same way on Mac OS X. These UI elements together on Mac OS X form a distinctive user read more..

  • Page - 40

    18 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT Apple set out to revise the traditional Mac OS API and eliminate these problems, which would give existing Macintosh developers an easy path for migrating their code to Mac OS X. This revised API was called Carbon. It used to be the case that you needed to work with Carbon read more..

  • Page - 41

    example, different systems may have widely divergent hardware characteristics, supply dif- ferent kinds of operating system services, and so on. Java Virtual Machine levels the playing fi eld for all Java apps, so that Java programmers do not need to worry about these issues themselves. Java ’ s greatest strength is that it enables you to read more..

  • Page - 42

    20 ❘ CHAPTER 1 THE MAC OS X ENVIRONMENT The information in the Apple Human Interface Guidelines is quite extensive. It covers all the user interface elements available within Mac OS X, such as windows, menus, controls, separators, text labels, and icons. All Mac OS X programmers should be familiar with the Apple Human Interface read more..

  • Page - 43

    WHAT YOU LEARNED IN THIS CHAPTER Kernel the heart of the Core OS, responsible for talking to hardware and running programs System Library API for “ talking to ” the Core OS Quartz Compositor the process responsible for all application drawing and event handling Quartz 2D API for drawing rich 2D read more..

  • Page - 44

    c01.indd 22 12/12/09 1:01:54 PM read more..

  • Page - 45

    2 Developer Tools WHAT YOU WILL LEARN IN THIS CHAPTER : How to install the developer tools that came with your copy of Mac OS X Where to fi nd the tools and documentation you just installed How to use the Apple Developer Connection web site Since the earliest releases of Mac OS X, a complete set of developer read more..

  • Page - 46

    24 ❘ CHAPTER 2 DEVELOPER TOOLS In Mac OS X Snow Leopard, the developer tools live in a package called Xcode . You can fi nd this package on your install DVD. The Installer will ask you to customize the Xcode installation, and you can just accept the default options. If you ’ re not sure, go ahead and install read more..

  • Page - 47

    Mac OS X includes Instruments, an application you can use to diagnose most of your performance problems. It helps you fi nd common memory problems, troublesome fi le usage, and computation bottlenecks. You learn more about Instruments in a little bit. Instruments resides in /Developer/ Applications along with Xcode and Interface Builder. read more..

  • Page - 48

    26 ❘ CHAPTER 2 DEVELOPER TOOLS These instruments are organized in a timeline similar to GarageBand. Start by dragging instruments into the timeline from a Library, or by opening a pre confi gured template. You can watch performance statistics change in real - time as your program runs. When you see something interesting, you can go back and read more..

  • Page - 49

    Time Profi ler and Spin Monitor Time Profi ler shows you how a program ’ s call stack changes over time. Simply start your program while using the Time Profi ler instrument. When you fi nish recording, you can analyze the results to fi nd out where your program spent most of its time during the recording period. Time Profi ler works by read more..

  • Page - 50

    28 ❘ CHAPTER 2 DEVELOPER TOOLS Imagine that your program has become unresponsive. It no longer responds to user events, and Mac OS X automatically shows the spinning wait cursor. You want to sample your program to fi nd out what is chewing up its time, but you don ’ t want to have to search through a lot of instrument read more..

  • Page - 51

    But writing multi - threaded programs can be challenging, because programmers must deal with the fact that a program is performing two or more things at once. You can get into trouble if two threads start competing for the same resource. For example, if you have two programs trying to write to the same fi le at the same time, the read more..

  • Page - 52

    30 ❘ CHAPTER 2 DEVELOPER TOOLS Using the User Interface instrument couldn ’ t be simpler. Simply add User Interface to your timeline, run your program, use it normally, and then stop recording. Next time you run your program, Instruments will play your keyboard and mouse events back for you. This is especially read more..

  • Page - 53

    You can fi nd a complete user guide under Shark ’ s Help menu. Shark also comes with PowerPC, Intel, and ARM assembly command reference guides to help you understand Shark ’ s assembly code view. FIGURE 2-5 Other Utilities Mac OS X ’ s developer tools include other utilities that can make your life easier. Though these utilities are read more..

  • Page - 54

    32 ❘ CHAPTER 2 DEVELOPER TOOLS FileMerge FileMerge lets you compare two text fi les side by side and see how they differ. As you scroll through the fi les, FileMerge highlights places where text has been added, removed, or moved within the fi les. You can also use FileMerge to compare entire directories of fi les, read more..

  • Page - 55

    FIGURE 2-7 PackageMaker PackageMaker builds packages for use in Installer, Mac OS X ’ s built - in software installer. After you ’ ve written your own programs, you might want to distribute them as packages to help simplify the installation process for your users. You simply point PackageMaker at a directory of fi les, fi ll out read more..

  • Page - 56

    34 ❘ CHAPTER 2 DEVELOPER TOOLS Packages can actually support a lot of custom functionality, more than can be confi gured using PackageMaker ’ s interface. To enable a package ’s advanced features, you need to get into the details of the package format. PackageMaker ’ s online help contains detailed notes on the read more..

  • Page - 57

    Script Editor Script Editor is an application for writing and running AppleScripts. Strictly speaking, Script Editor isn ’ t a developer tool; it ’ s a standard part of Mac OS X. You can fi nd Script Editor in /Applications/AppleScript . Script Editor is a specialized tool for working with AppleScripts. It validates your AppleScript syntax as read more..

  • Page - 58

    36 ❘ CHAPTER 2 DEVELOPER TOOLS Command - Line Tools As you learned in Chapter 1, Unix development is traditionally done through command - line tools. Although Mac OS X includes applications for designing, building, and debugging programs on Mac OS X, the developer packages include several powerful command - line tools as read more..

  • Page - 59

    cc/gcc Since the very beginning, Unix operating systems have come with a built - in C compiler: cc . In the old days, this compiler was necessary to install software: you would download a program ’ s source code and compile it specifi cally for your system. Sometime later, the Free Software Foundation created and distributed a read more..

  • Page - 60

    38 ❘ CHAPTER 2 DEVELOPER TOOLS Breakpoint 1 at 0xedf68: file /Projects/Slide Master/main.m, line 13. (gdb) run Starting program: Slide Master Breakpoint 1, main (argc=1, argv=0xbffffe9c) at /Projects/Slide Master/main.m:13 13 return NSApplicationMain(argc, argv); (gdb) You ’ ve learned that the primary tool read more..

  • Page - 61

    authors) and tcsh , both of which come with Mac OS X. bash is a modern replacement derived (if only in spirit) from the original sh command syntax. It is quite common on Linux and other Unix systems and is the default shell for Mac OS X. tcsh is a modern replacement for an older shell, csh , which featured read more..

  • Page - 62

    40 ❘ CHAPTER 2 DEVELOPER TOOLS phrase into the Search fi eld to search through the documentation on your system. Xcode will look through class and function references, overview documentation, and source code examples. You will learn more about Xcode in the next chapter. FIGURE 2-12 Earlier, you learned how to use Mac OS read more..

  • Page - 63

    Developer Documentation and Examples ❘ 41 FIGURE 2-13 RESOURCE T YPE DESCRIPTION Articles Documents meant to quickly illustrate a single topic, such as using a development tool or working with specifi c technologies. Getting Started Short pages that link articles, guides, and reference documentation for a specifi c read more..

  • Page - 64

    42 ❘ CHAPTER 2 DEVELOPER TOOLS The documents shown in the following table and explained in more detail in the following sections describe important Mac OS X concepts that aren ’ t specifi c to individual technologies. You have already learned about some of them in Chapter 1, but they bear repeating. You can fi read more..

  • Page - 65

    collects these user guides into a list called Recommended Reading for Xcode Developers, which is located in the Tools section of the documentation index. API Reference After you understand the fundamental concepts behind a particular framework and work through a tutorial or two, you will want to roll up your sleeves and start writing some read more..

  • Page - 66

    44 ❘ CHAPTER 2 DEVELOPER TOOLS FIGURE 2-15 This API reference is arguably the most important piece of Mac OS X ’ s developer documentation. You use it to discover what a framework is capable of and to learn how to write code that uses that framework ’ s specifi c features. Without the API reference, you could still learn a lot about read more..

  • Page - 67

    documents, basic scriptability, and printing. TextEdit is quite old for a Cocoa app, and it doesn ’ t use some of the newer additions to Cocoa, such as Cocoa ’ s document abstraction. Sketch is a drawing application written in Cocoa that ’ s a little more current than the TextEdit example. Man Pages In Chapter 1, you learned about the read more..

  • Page - 68

    46 ❘ CHAPTER 2 DEVELOPER TOOLS When you ask for a man page, the man command searches its sections for a matching page and returns the fi rst one it fi nds. So if pages in two or more sections share the same name, man displays only one of those fi les. In these cases, you have to ask for the read more..

  • Page - 69

    Apple Developer Connection ❘ 47 FIGURE 2-16 The Apple Developer Connection is split into two main areas: the Macintosh Developer Program and the iPhone Developer Program. It turns out iPhone and Mac programmers use most of the same tools, libraries, and techniques, so there is some overlap in developer content. But there are some unique differences read more..

  • Page - 70

    48 ❘ CHAPTER 2 DEVELOPER TOOLS In fact, the similarities between the ADC web site and the documentation in Xcode are not coincidental. The documentation installed by Xcode is a snapshot of the ADC web site, ensuring that you have complete and reasonably recent information even if you aren ’ t connected to the Internet. And if read more..

  • Page - 71

    Apple Developer Connection ❘ 49 FIGURE 2-18 All the examples in the ADC Source Code library are available at no cost and do not require an ADC membership. Mailing Lists Apple maintains a number of mailing lists about specifi c developer topics. These mailing lists are available at . Here you can discuss various topics read more..

  • Page - 72

    50 ❘ CHAPTER 2 DEVELOPER TOOLS Developer Support Another benefi t of having an Apple Developer Connection account is access to a number of developer support services. All these services are available from the ADC home page. These services include the following: The ability to report bugs against Apple software using Bug Reporter read more..

  • Page - 73

    WHAT YOU LEARNED IN THIS CHAPTER Xcode Mac OS X ’ s development environment for writing Mac OS X applications Interface Builder a tool for building graphical user interfaces Instruments a tool for analyzing program computation and memory performance Shark a tool that analyzes the performance of a program or the read more..

  • Page - 74

    c02.indd 52 12/12/09 1:07:35 PM read more..

  • Page - 75

    3 Xcode WHAT YOU WILL LEARN IN THIS CHAPTER: How to create new projects in Xcode How to organize fi les in an Xcode project How Xcode can help you write and format your code How to build and run your application, and examine your project in Xcode ’ s built - in debugger How to access online read more..

  • Page - 76

    54 ❘ CHAPTER 3 XCODE During the development process, you may fi nd yourself checking and double - checking the developer documentation on your system. Xcode provides a full - featured documentation browser within easy reach, so you don ’ t need to fumble with a web browser or PDF viewer to review the API. A number of shortcuts read more..

  • Page - 77

    2. Choose the Create A New Xcode Project option. A New Project window appears, such as the one in Figure 3-2. FIGURE 3-2 3. Select the Command Line Tool project type from the Application list and click the Choose button. A standard save panel will appear, giving you a chance to name your project and choose the directory it will live read more..

  • Page - 78

    56 ❘ CHAPTER 3 XCODE 5. Double-click main.c , and the fi le appears in a new window. Notice that main.c already contains the following code. Keep this code for now: #include <stdio.h> int main (int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); return 0; } read more..

  • Page - 79

    welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys002 Loading program into debugger… Program loaded. run [Switching to process 3480] Running… Hello, World! read more..

  • Page - 80

    58 ❘ CHAPTER 3 XCODE WORKING WITH FILES As with the Finder, Xcode allows you to specify how your project fi les are organized. Unlike the Finder, your changes don ’ t necessarily refl ect how the fi les are stored on disk. Just as it does when creating a project, Xcode automates some of the busywork of creating new read more..

  • Page - 81

    4. If necessary, click once on Source to select it, and then click it again after a short pause. Make sure you click to the right of the disclosure triangle. You can now rename the Source group to My Source Files . 5. Select and then click main.c and rename your source fi le to Hello2.c . 6. Click Hello2.1 and drag it read more..

  • Page - 82

    60 ❘ CHAPTER 3 XCODE 11. Choose C and C++ from the Mac OS X list, select C File, and click the Next button. The assistant changes, giving you a chance to name your fi le, as shown in Figure 3-7. FIGURE 3-6 FIGURE 3-7 c03.indd 60 12/12/09 1:09:08 PM read more..

  • Page - 83

    12. Name the fi le Example.c . 13. Make sure the Also Create “Example.h” ch eckbox is checked, as shown in Figure 3-7. Ignore the others settings for now. 14. Click Finish. Two fi les, Example.c and Example.h , will appear in the My Source Files group, and Example.h is visible in the project’s fi le editor. Your read more..

  • Page - 84

    62 ❘ CHAPTER 3 XCODE FIGURE 3-9 17. Select the entry for the main symbol. Hello2.c appears in the fi le editor with the fi rst line of the main function selected. Double-click the entry for the main symbol, and Hello2.c will appear in a new window. How It Works The Groups & Files list uses the Option key to open read more..

  • Page - 85

    When you rename fi les, Xcode actually changes the name of the fi le on disk. In this example, the fi le main.c changed to Hello2.c when the fi le was renamed. This is often very helpful, because Xcode tends to lose track of source fi les if you rename them in the Finder or in Terminal. If Xcode cannot fi nd a fi read more..

  • Page - 86

    64 ❘ CHAPTER 3 XCODE In the following example, you write a small C program called Calculator that lets you add and subtract numbers. The program consists of two functions: the main function, which interacts with the user via Mac OS X ’ s command - line interface, and a calculate function that does some arithmetic. The calculate read more..

  • Page - 87

    10. Add the following line of code to Calculate.h : int calculate(int a, int b, char operator); code snippet MacOSXProg ch03/Calculator/Calculate.h 11. Choose View ➪ Switch to Header/Source File. The source editor window switches to display the contents of Calculate.c . Notice that the left arrow is no longer grayed out and the pop-up menu now says read more..

  • Page - 88

    66 ❘ CHAPTER 3 XCODE 18. Choose Edit ➪ Format ➪ Shift Right. The selection indents four spaces to the right. 19. Select the three lines of code that comprise the fi rst case statement. That corresponds to lines 20–22 in Figure 3-11. 20. Press Command-] to invoke the Shift Right command. The selection indents four more read more..

  • Page - 89

    23. Make sure your text insertion point is in the calculate function; if not, click line 19 to set the selection. By now you may have noticed there is a second pop-up menu in the small button bar, next to the fi le history pop-up menu. The menu currently says calculate() . 24. Move the text insertion point cursor to the very read more..

  • Page - 90

    68 ❘ CHAPTER 3 XCODE 30. Save your changes to main.c . 31. Command–double-click the word calculate in your main function. The Calculate.c fi le appears in the same fi le editor, with the calculate function name selected. How It Works You started by turning on line numbers in Xcode’s gutter. The gutter is the region just to read more..

  • Page - 91

    A Second Look at Indenting In the previous example, you learned two different ways of indenting your code: using the Tab key to insert four spaces at the text insertion point, and using the Shift Left and Shift Right menu commands to quickly remove or insert four spaces at the beginning of a line. Xcode provides a third way of indenting read more..

  • Page - 92

    70 ❘ CHAPTER 3 XCODE 9. Click OK to save your preference changes. 10. Open main.c and delete all the text in the fi le. 11. Re-enter the code from the previous example. The code is reprinted here for your convenience. This time, do not do any formatting yourself; do not press the Tab key or add extra spaces, and do not use read more..

  • Page - 93

    However, neither indenting method is perfect. Under some rare circumstances, the Re-Indent command might misinterpret how you want your code to be formatted. Or maybe you don’t agree with the style in which Xcode indents your text. Perhaps you just fi nd auto-indenting distracting. If any of these are true, you can simply fall back to the Tab read more..

  • Page - 94

    72 ❘ CHAPTER 3 XCODE 7. Try rebuilding Calculator . The build will fail again, and the Build Results window will update to show errors in Calculate.c . 8. Select the fi rst error for Calculate.c . Again, the contents of Calculate.c appear in the fi le editor. This time, line 17 is missing a semicolon. 9. Add a semicolon to read more..

  • Page - 95

    18. Enter 44 + 7 , and press Return. The Run Log displays the results of your program. It looks as though it’s working correctly. Enter an expression: 44 + 7 44 + 7 = 51 Debugger stopped. Program exited with status value:0. 19. Run Calculator again by clicking the Build and Run button on the Debugger Console window. 20. read more..

  • Page - 96

    74 ❘ CHAPTER 3 XCODE How It Works When you ask Xcode to build your project, Xcode actually does a number of smaller tasks for you and presents the results all at once. The fi rst thing Xcode does is convert all your source code to machine- friendly instructions using a tool called a compiler. The compiler’s main job is to take read more..

  • Page - 97

    Notice that Xcode actually reported more problems in your program than you fi xed. A single error in a source fi le may actually result in several problems within the C compiler. So the fact that adding a semicolon to one line of code in main.c fi xed all the compile errors there is not all that surprising. This is true of read more..

  • Page - 98

    76 ❘ CHAPTER 3 XCODE TRY IT OUT Using the Static Analyzer 1. In Xcode, open the Calculator project you created and saved earlier. 2. Build your project and verify that Xcode fi nds no build errors or warnings. If you do see prob- lems, look over the previous example carefully. 3. Choose Build ➪ Build & An alyze. read more..

  • Page - 99

    8. In the Build Results window, select the fi rst error in the list: Value stored to ‘answer’ is never read . Xcode will scroll to that warning in your main.c source fi le. Xcode is telling you that you never actually use the result of the calculate function, even though you went to the trouble of storing that result in answer read more..

  • Page - 100

    78 ❘ CHAPTER 3 XCODE 12. Select the second detail: 2. Pass-by-value argument in function call is undefined . An arrow appears between where the variable aa was defi ned without an initial value and where you read the value of aa . Now the problem is clear. The solution is to remove the bad aa variable and print the value of answer read more..

  • Page - 101

    TRY IT OUT Debugging Changes to Calculator 1. In Xcode, open your Calculator project that you saved earlier. 2. Make sure the Project fi le’s Overview pop-up says the Active Confi guration is Debug. Change it if necessary. 3. If you changed your project’s Active Confi guration, clean your build results using the Build ➪ Clean read more..

  • Page - 102

    80 ❘ CHAPTER 3 XCODE 9. Open the Debugger Console with the Run ➪ Console menu item and enter 4 * 5 . Calculator prints the following result. Obviously, something is wrong. Enter an expression: 4 * 5 4 * 5 = -1 Debugger stopped. Program exited with status value:0. 10. Open main.c in your project window’s fi le editor. 11. read more..

  • Page - 103

    13. Choose Run ➪ Debugger. The Debugger window appears as shown in Figure 3-20. The Debugger window has a toolbar with a number of debugger commands, a list showing your program’s stack, a second list showing the current stack’s variables, and a fi le editor. FIGURE 3-19 FIGURE 3-20 Using the Debugger ❘ 81 c03.indd 81 12/12/09 read more..

  • Page - 104

    82 ❘ CHAPTER 3 XCODE 14. Click the debugger toolbar’s Step Over button. The selection advances to line 15. 15. Click the Step Over button again. The selection disappears, and the debugger’s toolbar changes so that only the Pause and Terminate buttons are enabled. 16. Return to the Debugger Console menu, using Run ➪ Console if read more..

  • Page - 105

    21. Click the Step Over button. Sure enough, the Variable table shows result changing to –1 . 22. Click the Tasks button, which currently looks like a stop sign, to quit the program. 23. Without leaving the debugger, correct Calculate.c by changing the operator at line 27 from - to * . 24. Save your changes to Calculate.c . 25. Choose Build read more..

  • Page - 106

    84 ❘ CHAPTER 3 XCODE Xcode’s debugger has the power to pause your program, control when the program’s instructions are fed to the processor, and examine or change the contents of the program’s memory. A paused program is actually in a state of suspended animation: a process exists, but machine instructions are not being processed. The read more..

  • Page - 107

    The debugger also displays your current stack history in the list in the Debugger window’s upper-left corner. In other words, this list shows your program’s stack. Each entry in the stack represents a function call or stack frame. The topmost entry represents the function your program is currently “in”; th at function was called by read more..

  • Page - 108

    86 ❘ CHAPTER 3 XCODE 2. Name your project Greetings . 3. Open Greetings.m in your project window’s fi le editor, and replace its contents with the follow- ing code: #import <Foundation/Foundation.h> int main (int argc, const char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; read more..

  • Page - 109

    Notice you haven’t actually initialized the time variable to something useful. You need to fi nd some kind of function or method call that returns the current time. 4. Choose Help ➪ Developer Documentation. A window titled Xcode Quick Start appears, as shown in Figure 3-24. The window resembles a simple web browser, with Forward, read more..

  • Page - 110

    88 ❘ CHAPTER 3 XCODE 9. Select descriptionWithCalendarFormat:timeZone:locale: from the symbol pop-up. The Developer Documentation window jumps to the entry describing descriptionWithCalendarFormat: timeZone:locale: , as shown in Figure 3-25. FIGURE 3-25 This method returns the current time with a particular formatting. The example provided in the documentation read more..

  • Page - 111

    14. Click the entry for main in the stack list. The debugger updates to match the contents of Figure 3-27. It looks like the program has crashed trying to print the full username. It looks as though the compile warning comes from line 7, where the full username is stored in the user variable. That’s no coincidence. FIGURE 3-26 FIGURE 3-27 read more..

  • Page - 112

    90 ❘ CHAPTER 3 XCODE 15. Stop debugging the program by clicking the Tasks button. 16. Option–double-click NSFullUserName . A small window will appear containing documentation for NSFullUserName , as shown in Figure 3-28. This small window is called the Quick Help win- dow. It turns out that the NSFullUserName symbol is a function call, not read more..

  • Page - 113

    21. Select the NSString class from the API list. The Developer Documentation window displays documentation for the NSString class. 22. Select UTF8String from the Jump To pop-up menu (it’s toward the very bottom of the menu). It looks as though UTF8String returns a const char * type, which should be exactly what printf expects. 23. Return read more..

  • Page - 114

    92 ❘ CHAPTER 3 XCODE How It Works The code in this example looks a little different from the earlier examples because it is Objective-C. Don’t worry about following along with the specifi cs of what this program is doing; you learn more about Objective-C in Chapter 6. In this example, you ran your program without fi rst starting read more..

  • Page - 115

    In the next chapter, you learn how to use Interface Builder, a tool for building graphical user interfaces. Before proceeding, however, try the exercises that follow to test your understanding of the material covered in this chapter. You can fi nd the solutions to these exercises in Appendix A. EXERCISES 1. Use Xcode to look up the man page for read more..

  • Page - 116

    94 ❘ CHAPTER 3 XCODE WHAT YOU LEARNED IN THIS CHAPTER Project an Xcode fi le representing your entire program Source Files text fi les containing your program’s source code Templates sample project and source fi les with existing content Symbols names of variables, functions, classes, read more..

  • Page - 117

    4 Interface Builder WHAT YOU WILL LEARN IN THIS CHAPTER: How to build menus and controls How to make windows resizable How to use Interface Builder ’ s Inspector to confi gure individual interface elements How to test your interface directly in Interface Builder Interface Builder, as its name implies, is a tool read more..

  • Page - 118

    96 ❘ CHAPTER 4 INTERFACE BUILDER STARTING A NEW INTERFACE As with Xcode, Interface Builder has templates that help you get started with a new nib fi le. These templates are grouped by application framework, so you can quickly zero in on the kind of interface you need. TRY IT OUT Creating a New Interface 1. Launch read more..

  • Page - 119

    3. Close the window representing your interface’s main window. This window is simply named Window and has no content. 4. Double-click the Window (Window) icon in your nib fi le. The window representing the main window reappears. Also notice that the Inspector displays some settings for your window, shown in Figure 4-3. 5. Click once on the Window read more..

  • Page - 120

    98 ❘ CHAPTER 4 INTERFACE BUILDER 7. Choose File ➪ Simulate Interface. Interface Builder opens your interface in a program called Cocoa Simulator. The Cocoa Simulator displays your menu bar and window, as shown in Figure 4-4. 8. Quit Cocoa Simulator, and you are returned to Interface Builder. FIGURE 4-4 How It Works When read more..

  • Page - 121

    try out the controls, check that your window’s keyboard focus moves properly when you press the Tab key, verify that windows look good when they are resized, and similar tasks. You quit the simulation by pressing Command-Q or by selecting Quit from your interface’s menu bar. It is interesting to note at this point that Interface Builder did read more..

  • Page - 122

    100 ❘ CHAPTER 4 INTERFACE BUILDER 4. Double-click the NewApplication menu on the left side of your interface’s menu bar. You can rename the menu to something more appropriate. 5. Name the menu Cocoa Example and press Return. 6. Click Cocoa Example to reveal its menu. Note that this time the menu has a number of read more..

  • Page - 123

    11. Rename Menu to Extras . 12. Select Item from the Extras menu. 13. Rename the item to Empty The Trash . Notice the item’s name in the Inspector window also changed to Empty The Trash. 14. Click the gray box next named Key Equiv. in the Inspector win- dow. The gray box will be lit with a curious highlight. You can now defi read more..

  • Page - 124

    102 ❘ CHAPTER 4 INTERFACE BUILDER Interface Builder’s Library contains the following objects that you will fi nd useful when building menus: Empty menus and menu items, such as Menu Item and Submenu Menu Item — You can drag the Submenu Menu Item into the main menu bar to create new menus, or you can drag it into read more..

  • Page - 125

    Dialog boxes, alerts, and sheets are often the simplest windows, containing only enough items to ask a simple question and collect an answer from the user. Interface Builder ’ s drag - and - drop interface should be well suited for building windows. Theoretically, all you need to do is drag some controls into your window and you ’ re read more..

  • Page - 126

    104 ❘ CHAPTER 4 INTERFACE BUILDER 7. Drag a Label item out of the Library and into the center of your blank window. This creates a new label in your window. 8. Double-click the label to change its text. Replace Label with First Name: . Press Return or click once outside the label to end the text entry process. 9. Click the read more..

  • Page - 127

    14. Move the text fi eld so that it sits to the right of the First Name: label. Guides appear, suggesting the proper distance between the text fi eld and its label, as shown in Figure 4-15. A guide also aligns the label and text fi eld’s baselines. FIGURE 4-15 15. Be sure the text fi eld is selected and choose the read more..

  • Page - 128

    106 ❘ CHAPTER 4 INTERFACE BUILDER 22. Make the window narrower by clicking in the window’s resize control and dragging it to the left. As before, Interface Builder uses guides to suggest a reasonable distance between the window’s right edge and your controls. Don’t worry about keeping your window’s height exactly the same; you can read more..

  • Page - 129

    31. Now you can fi nish resizing the window so that it fi ts all its controls snugly. The guides suggest the proper 20-pixel buffer between the controls and the window’s edges. Figure 4-18 illustrates your fi nal window. 32. Choose File ➪ Simulate Interface. Your window appears on-screen, giving you a chance to test your read more..

  • Page - 130

    108 ❘ CHAPTER 4 INTERFACE BUILDER MAKING WINDOWS RESIZABLE When designing windows, you need to consider what will happen when the user tries to resize them. For some windows, such as simple sheets and dialog boxes, you may choose to prohibit resizing. But most user - friendly interfaces allow the user to resize windows as read more..

  • Page - 131

    4. Drag a second button from the Library and place it in the upper-right corner of your window. 5. Drag a Text Field from the Library and place it between the two buttons. Use the guides to make sure that the text fi eld lines up vertically with the buttons. Don’t worry about centering the text fi eld right now. 6. Make sure the read more..

  • Page - 132

    110 ❘ CHAPTER 4 INTERFACE BUILDER 10. Choose File ➪ Simulate Interface to check your work. Your win- dow is displayed in test mode. 11. Grab the window by its resize control and resize the window in a bunch of different directions. Start using small, circular motions and move toward progressively larger movements. You’ll read more..

  • Page - 133

    contracts horizontally, and the text view fi lls the remaining avail- able space. But if you make the window too small, the text fi eld goes away; when that happens, making the window large again leaves the text fi eld in an unusual state. The solution to this problem is to set a minimum size for the window. 24. Quit test read more..

  • Page - 134

    112 ❘ CHAPTER 4 INTERFACE BUILDER the upper-left corner of the window. The two springs within the light-gray rectangle represent the size of your interface element. Enabled springs mean the size can change, and disabled springs mean the size remains constant. You enabled the text fi eld’s horizontal spring, and left the vertical read more..

  • Page - 135

    EXERCISES 1. Modify the example dialog you built in the Try It Out “ Building a Dialog Window ” to make it resizable. All the controls should be pinned to the upper - left corner of the window. Allow the text fi elds to expand when the window is resized. 2. Carbon and Cocoa both support read more..

  • Page - 136

    114 ❘ CHAPTER 4 INTERFACE BUILDER WHAT YOU LEARNED IN THIS CHAPTER Nib File a fi le containing application UI elements Library Panel a window containing UI elements and other helpful objects Attributes Inspector an inspector panel for setting object options Size Inspector an inspector panel read more..

  • Page - 137

    PART II Application Programming CHAPTER 5: The Application CHAPTER 6: The C Language CHAPTER 7: The Objective-C Language CHAPTER 8: Introduction To Cocoa CHAPTER 9: Document-Based Cocoa Applications CHAPTER 10: Core Data–Based Cocoa Applications c05.indd 115 12/12/09 1:13:29 PM read more..

  • Page - 138

    c05.indd 116 12/12/09 1:13:34 PM read more..

  • Page - 139

    5 The Application WHAT YOU WILL LEARN IN THIS CHAPTER: How applications and other bundles are structured What kind of fi les you fi nd in a bundle How application preferences are stored Mac OS X applications seem simple enough. They appear with friendly icons that bounce in the Dock when you launch read more..

  • Page - 140

    118 ❘ CHAPTER 5 THE APPLICATION Although applications themselves are self - contained, they do store some data in other places on your computer. These data normally represent things such as your application preferences — the directory that opens by default when you bring up an Open panel — the contents of an read more..

  • Page - 141

    The system keeps track of opaque bundle directories in a number of ways. The fi rst way is simply by checking the fi le extension. All application bundles (directories that end in .app ) are made opaque automatically. The second way is by setting a piece of fi le meta data called a bundle bit . If a directory ’ s read more..

  • Page - 142

    120 ❘ CHAPTER 5 THE APPLICATION Here is an example of a versioned bundle: FunFramework.framework FunFramework.framework/FunFramework FunFramework.framework/Resources FunFramework.framework/Versions FunFramework.framework/Versions/A FunFramework.framework/Versions/A/FunFramework FunFramework.framework/Versions/A/Resources FunFramework.framework/Versions/A/Resources/English.lproj read more..

  • Page - 143

    INFO.PLIST KEY USAGE CFBundleGetInfoString Text displayed by the Finder when the user brings up the Info window for this bundle. CFBundleIconFile The fi lename of this bundle ’ s icon. This key is used only for application bundles. CFBundleIdentifier A string representing a unique identifi er for read more..

  • Page - 144

    122 ❘ CHAPTER 5 THE APPLICATION You can fi nd more information about Info.plist keys in Mac OS X ’ s conceptual documentation for Runtime Confi guration Guidelines: Snow Leopard Core Library ➪ Mac OS X ➪ Runtime Confi guration Guidelines . Executable Code Bundles can contain executable code, as is the read more..

  • Page - 145

    Localized resources live in Language Project directories, commonly known as lprojs (named for their .lproj fi le extension), which live in the bundle ’ s Resources directory. Language project directories gather up resources for a specifi c language or locale into a single directory named after that language or locale. read more..

  • Page - 146

    124 ❘ CHAPTER 5 THE APPLICATION FIGURE 5-2 8. Scroll the Finder window to the left if necessary and select Contents/Resources . This directory is full of all kinds of fi les: AppleScript fi les, image fi les saved in TIFF format, lproj directories, and so on. Figure 5-2 shows a few of those fi les. FIGURE 5-1 c05.indd read more..

  • Page - 147

    9. Scroll down until you see an lproj directory and select it. Figure 5-3 shows the Finder window with da.lproj selected. The lproj directory contains a number of other fi les, primarily Interface Builder and Strings fi les. FIGURE 5-3 10. Close this window. 11. Launch /Applications/Utilities/Terminal . 12. Change the current directory to read more..

  • Page - 148

    126 ❘ CHAPTER 5 THE APPLICATION read more..

  • Page - 149

    BUILDING AN APPLICATION BUNDLE Bundles are basically directories, and building a bundle could be as simple as just creating a folder in the Finder. However, much of the bundle ’ s power is wrapped up in its specifi c directory tree and Info.plist fi le. Xcode manages most of the complexity of building bundles for you as part of read more..

  • Page - 150

    128 ❘ CHAPTER 5 THE APPLICATION 2. Build and run the new project. After a few moments of building, your new Slide Master applica- tion appears. Right now the application just displays a window saying Your document contents here . Slide Master appears in the Dock using a generic app icon, as shown in Figure 5-5. FIGURE 5-5 3. Choose read more..

  • Page - 151

    6. In the Finder, locate your new Slide Master program. If you’re not sure where it might be, search for Slide in your Xcode project window, select it from the list, and choose Reveal In Finder from the Action menu in Xcode’s toolbar. 7. Drag the Slide Master icon from Finder into your Terminal window. The path to the read more..

  • Page - 152

    130 ❘ CHAPTER 5 THE APPLICATION 10. Switch back to Xcode and select Slide Master in the Groups & Fi les list. The fi le list changes to display the source fi les and other resources that make up your project. 11. Open Credits.rtf . This is where the credits you saw in step 3 came from. Go ahead and make the credits read more..

  • Page - 153

    14. Check the Copy Items Into Destination Group’s folder checkbox and click the Add button to dis- miss the sheet. The fi le will appear in your Groups & Fi les list. 15. If necessary, rename the icon fi le to appl.icns . 16. Choose Project ➪ Add To Project again and then add slim.icns to your project. Again, borrow from read more..

  • Page - 154

    132 ❘ CHAPTER 5 THE APPLICATION 21. Select the Build tab in the Target Info window. The window displays lists of build options, as shown in Figure 5-9. Note Product Name is set to Slide Master and Wrapper Extension is set to app . FIGURE 5-9 22. Select the Properties tab in the Target Info window. You will now see an read more..

  • Page - 155

    23. Change Identifi er to com.wrox.Slide Master . 24. Change Icon File to appl.icns . 25. Change Creator to Slid . 26. Change the Version to 1.0 . Your Target Info window should now resemble the one shown in Figure 5-11. 27. Close the Target Info window. 28. Build and run the new project. After building, Slide Master should launch and your icon read more..

  • Page - 156

    134 ❘ CHAPTER 5 THE APPLICATION 32. Re-open the Target Info window by double-clicking the Slide Master target; if necessary, select the Properties tab. Notice a table named Document Types at the bottom of the window. The table has one entry, for a document named DocumentType . 33. Change the entry for DocumentType to match the information in read more..

  • Page - 157

    34. Build and run the new project. After building, Slide Master should launch. 35. Choose File ➪ Open. An Open panel should now allow you to select fi les ending with a .slim extension. If you don’t happen to have any .slim fi les, save some slideshows from the version of Slide Master you downloaded off the Web. If you read more..

  • Page - 158

    136 ❘ CHAPTER 5 THE APPLICATION How It Works Slide Master works with slideshow documents (.slim fi les), so the Cocoa Document-Based Application template is the logical choice for your project. This project template is set up to emit a complete Cocoa application at build time. When you built the project, Xcode laid out Slide Master’s read more..

  • Page - 159

    Xcode provides several ways to modify your Info.plist fi le. One way is to use the Properties tab in Xcode’s Target Info window, which is convenient for projects that do not require anything special of their Info.plist fi le. Alternatively, you can simply open your project’s Info.plist fi le in a source editor and view its contents read more..

  • Page - 160

    138 ❘ CHAPTER 5 THE APPLICATION 8. In the Finder go to the Library/Preferences directory in your home directory. You will see a number of fi les and folders. The majority of fi les are property lists, or .plist fi les. 9. Open the fi le. The fi le should open in a program called Property read more..

  • Page - 161

    14. Launch TextEdit again and open the Preferences window. 15. Uncheck the Delete Backup File checkbox found on the Open And Save tab and close the Preferences window. 16. Quit TextEdit. 17. In Terminal, enter defaults read again. The output of the defaults command will change to resemble the following: [Macintosh:~] sample% defaults read read more..

  • Page - 162

    140 ❘ CHAPTER 5 THE APPLICATION path = "/System/Library/Screen Savers/Arabesque.qtz"; type = 1; }; } [ ... ] How It Works Most applications store preferences of some kind. Normally, preferences are edited in an application’s Preferences pane. Other settings might be set more transparently, such as an read more..

  • Page - 163

    DIRECTORY PURPOSE /Library/Preferences Preferences specifi c to all users on a given system are saved in the system - wide /Library/Preferences directory. For example, preferences related to starting up your computer or for running Software Update are stored here. But in general, such settings are rare. read more..

  • Page - 164

    142 ❘ CHAPTER 5 THE APPLICATION Both Property List Editor and defaults allow you to change the content of your preference fi les. This comes with a quick word of caution. Although the property list format is common to most preference fi les, the semantic meaning of the content of the property list is specifi c to the read more..

  • Page - 165

    d. Some document types actually are bundles rather than solitary fi les. Examine an Xcode project (bundles with an .xcodeproj extension). What kind of fi les might you fi nd in an Xcode project? e. What is the current bundle version of the AppKit framework? 2. The defaults read more..

  • Page - 166

    144 ❘ CHAPTER 5 THE APPLICATION WHAT YOU LEARNED IN THIS CHAPTER Bundle a directory structure containing multiple fi les, usually masquerading as a single fi le Info.plist a fi le found in most bundles containing common metadata such as the bundle ’ s name and copyright string Global read more..

  • Page - 167

    The C Language WHAT YOU WILL LEARN IN THIS CHAPTER: How to write programs in the C programming language How to write C programs using the structured programming style used in the Mac OS X C frameworks, including Core Foundation, Quartz 2D, Core Audio, and OpenGL C is probably the most successful programming read more..

  • Page - 168

    146 ❘ CHAPTER 6 THE C LANGUAGE journey to greatness at Bell Labs in 1969, where Ken Thompson and Dennis Ritchie created it. It was used to write the fi rst Unix operating system, from which Mac OS X ultimately descends. Other operating systems, such as Windows and Mac OS, also owe a lot to C. In 1989, the American read more..

  • Page - 169

    contains defi nitions that can be used in C programs. Header fi les are an important part of C, and you generally need to write many of them to defi ne the functions and data structures in your programs. The main function itself begins on the next line: int main (int argc, const char * argv[]) { The word read more..

  • Page - 170

    148 ❘ CHAPTER 6 THE C LANGUAGE C makes no distinction between the two. Note that unlike some other languages, you do not need any character to indicate that a line continues. C takes the opposite approach — you need a character to indicate a line has ended. In the next Try It Out, you compile your fi read more..

  • Page - 171

    How It Works This is an example of the infamous Hello World program that is the bane of every beginning program- mer, whatever the language they are learning. It simply prints out “ Hello, World! ” when it is run, as you will have seen in the Debugger Console and can also see in Figure 6 - 1. NOTE Apple, with read more..

  • Page - 172

    150 ❘ CHAPTER 6 THE C LANGUAGE INTEGER T YPE MINIMUM VALUE MA XIMUM VALUE SIZE IN BY TES int - 2147483648 2147483647 4 short int - 32768 32767 2 long int - 2147483648 2147483647 4 read more..

  • Page - 173

    WARNING You may be wondering if the variable names chosen have any signifi cance. The answer is no. They can be just about anything you like, with a few limitations: variable names can contain only alphanumeric characters and the underscore character, and variable names cannot begin with a number. Other than that, you are free to choose any variable names read more..

  • Page - 174

    152 ❘ CHAPTER 6 THE C LANGUAGE You can ’ t get far with integers alone, so C has a variety of decimal number types. These are referred to as fl oating - point numbers in C, because the decimal point is able to “ fl oat ” to any position in the number. The following table shows the most read more..

  • Page - 175

    OPERATOR SYMBOL DESCRIPTION EX AMPLE Increment ++ Increases the integer variable by one ++i Decrement – – Decreases the integer variable by one – – i Addition Assignment += Adds the LHS to the RHS and read more..

  • Page - 176

    154 ❘ CHAPTER 6 THE C LANGUAGE If you are now cursing C for having ever been invented, note that sometimes you may actually want the result of an integer division. And furthermore, you may want the remainder left after the division. You can use the modulus operator in such instances, as shown in the following example: int read more..

  • Page - 177

    int i = 5; i++; // i is now 6 i--; // i is 5 again i += 1; // i is now 6 i *= 2; // i is now 12, i.e., 6 * 2 int j = 2; i -= j + 1; // i is 9 The last two statements demonstrate clearly how these operators work. In the last expression, i is set as the value of read more..

  • Page - 178

    156 ❘ CHAPTER 6 THE C LANGUAGE Now that you know about simple data types and operators, it ’ s time to move on to more advanced data types. In the next section, you learn about arrays and closely related types known as pointers, which enable you to store multiple data values in a single variable. ARRAYS AND read more..

  • Page - 179

    If you don ’ t explicitly set the value of an array element, its value is undefi ned. It could have any value, and you shouldn ’ t try to access its value until you have initialized it. There is a shorthand way of initializing an array that can save you typing in the same variable name over and over. When you read more..

  • Page - 180

    158 ❘ CHAPTER 6 THE C LANGUAGE The value pointed to by p is printed next. printf("%d\n", *p); It is important to recognize the distinction between the pointer ’ s value, which is an address in memory, and the value it points to, which is an int in this case. To access the pointer ’ s read more..

  • Page - 181

    int a[3]; *a = 2; // Sets a[0] *(a+1) = 5; // Sets a[1] *(a+2) = 10; // Sets a[2] int *p; p = & a[1]; printf("%d\n", *p); // Should print a[1], which is 5 printf("%d\n", *(p-1)); // Should print a[1-1], which is a[0], which is 2 An array a has been declared, but its contents have been set as read more..

  • Page - 182

    160 ❘ CHAPTER 6 THE C LANGUAGE TRY IT OUT Working with Pointers 1. Create a new Command Line Tool project with Xcode and name it Pointy. 2. Open the main function in the editor by opening the Source group in the Groups & Files view and clicking the main.c read more..

  • Page - 183

    if ( answer == *p ) { ++score; printf("Very good!\n"); } else { printf("No, the answer is %d\n", *p); } printf("You got %d out of 3.\n", score); return 0; } code snippet MacOSXProg ch06/Pointy/main.c 4. Build and run the read more..

  • Page - 184

    162 ❘ CHAPTER 6 THE C LANGUAGE After printing an introductory message, the main function begins like this: int intArray[] = {10,20,30,40,50}; printf("The variable intArray holds these values: %d %d %d %d %d\n", intArray[0], intArray[1], intArray[2], intArray[3], intArray[4] ); int answer; read more..

  • Page - 185

    In the preceding example, the value entered by the user, which is stored in the variable answer , is compared for equality with the value pointed to by p . If it is the same, the user was right, so the score variable is incremented and a congratulatory message is printed. If the user was wrong, the correct answer is printed, read more..

  • Page - 186

    164 ❘ CHAPTER 6 THE C LANGUAGE You may also see this variation: if ( everestIsHigh ) { printf("Everest is apparently a high mountain"); } else { printf("Which world do you originate from?"); } The point is that all these variations are legal in C. It is up to read more..

  • Page - 187

    It is reasonable, however, to leave out the braces when you use a solitary if , without an else branch, as shown in the following example: if ( everestIsHigh ) ++highMountainCount; You have already seen this form of if in many of the examples. It is fairly safe to use, because you are unlikely to accidentally forget read more..

  • Page - 188

    166 ❘ CHAPTER 6 THE C LANGUAGE printf("Pre-schooler\n"); break; case 5: printf("School Kid\n"); break; default: printf("That ain't no kid!\n"); } switch is used to branch based on the value of an integer variable. read more..

  • Page - 189

    The ternary operator consists of a condition — in this case, the comparison between the variable person and the constant DAD — followed by a question mark, and then two expressions separated by a colon. The ternary operator is used here to set the value of the variable favorite , according to the value of person . If read more..

  • Page - 190

    168 ❘ CHAPTER 6 THE C LANGUAGE NOTE Constant variables are often given names that are all capitalized. This is a convention to make code more readable, but it is not a requirement of the C language itself. LOOPS If there is one thing that computers are good at, it is repetitive tasks. C has various constructs for read more..

  • Page - 191

    A disadvantage of while loops is that if you are not careful, you can end up in an infi nite loop . This arises when the condition in the while statement never evaluates to false, and no other provision for escaping the loop is made. Here is the simplest infi nite loop we can think of: while (1) { } read more..

  • Page - 192

    170 ❘ CHAPTER 6 THE C LANGUAGE that determines whether the loop should continue or not, just like the while loop has. The last are statements that are executed at the beginning of each new iteration, which are usually used to update indexing variables. A for loop typically looks something like this: read more..

  • Page - 193

    NOTE The for loop responsible for printing array3 does not include any braces. Braces are not necessary in this case because there is only one statement to be performed. This is a general aspect of C that you have already encountered for if statements. You should take careful notice of the form of the for read more..

  • Page - 194

    172 ❘ CHAPTER 6 THE C LANGUAGE TRY IT OUT Statistical Analysis of Array Data 1. Create a new Command Line Tool project with Xcode and call it Statistics. 2. Open the fi le main.c in the editor by clicking it in the Groups & Files view. You can fi nd it in the read more..

  • Page - 195

    How It Works This program calculates a number of statistics for a data array of the heights of 1,000 people, given in centimeters. Rather than use real data, the data is generated randomly within a realistic range of val- ues. The statistics calculated are the average or mean, the maximum height, and the minimum height. You will need to use the read more..

  • Page - 196

    174 ❘ CHAPTER 6 THE C LANGUAGE NOTE The function rand returns an int between 0 and the constant RAND_MAX . The declarations of both rand and RAND_MAX come from the stdlib.h fi le that has been included at the beginning of the program . To generate a random fl oat between 0.0 and 1.0, the read more..

  • Page - 197

    FUNCTIONS AND BLOCKS Many of the examples you have seen thus far have included the printf statement, but what is printf exactly? printf is a function in the C standard library that prints a string to standard output. A function is a block of code that can be executed from any other point in your read more..

  • Page - 198

    176 ❘ CHAPTER 6 THE C LANGUAGE You must use void when there is no return value, but the void in the parameter list is optional, so you could rewrite DoNothingFunc like this: void DoNothingFunc() { } When a function is called, it must already be declared. You could try to keep all your functions read more..

  • Page - 199

    Without going into too much detail, the example demonstrates a rather obscure way of adding the numbers from 1 to 10 . calcSum is called fi rst from main with the value 1 for the parameter n , and 0 for sum . Because n is not greater than 10 , calcSum calls addToSum , read more..

  • Page - 200

    178 ❘ CHAPTER 6 THE C LANGUAGE If you run this version of the program, 5 will be printed for the value of a . Notice that func now expects a pointer to an int . It sets the value pointed to by the pointer param to 5 by using the dereferencing operator * . The call to read more..

  • Page - 201

    v += j; } return v; } It looks similar to a function defi nition, but has a caret (^) in place of a name. In this case, there is also no return type; the return type is optional for blocks, as long as the compiler can fi gure read more..

  • Page - 202

    180 ❘ CHAPTER 6 THE C LANGUAGE As you will undoubtedly have guessed, you can create a literal string by simply putting it between double quotation marks. But how do you declare a string variable? This is trickier, because a string variable is actually an array of characters, which have the type char in C. char read more..

  • Page - 203

    NOTE You may have noticed that there was no terminating null character used in the previous literal strings. Literal strings have a terminating null character added automatically. The only thing you have to remember is to make enough space in your strings to accommodate this extra character. For example, if your literal string read more..

  • Page - 204

    182 ❘ CHAPTER 6 THE C LANGUAGE Another function from string.h is strncpy , which can be used to copy one string into another, up to a maximum number of characters. It can be a bit safer to use than strcpy , because it will not go on forever, looking for a terminating null character. Here is the preceding read more..

  • Page - 205

    WARNING The table of functions for manipulating strings is fairly straightforward, but the keyword NULL may have you worried. If so, worry not. NULL is actually just another way of saying 0, and is used to indicate that a pointer is not pointing to any useful address. In the table, it can be returned from strstr read more..

  • Page - 206

    184 ❘ CHAPTER 6 THE C LANGUAGE Sometimes you will see a main function declared like this: int main( const int argc, const char** argv ); In this case, the second parameter is given as a pointer to a pointer . Because an array is equivalent to a pointer in C, this declaration is equivalent to the read more..

  • Page - 207

    The use of quotations inside a string is made possible by escaping the special meaning of the quotation marks. You do this by adding a backslash character before each quotation mark. This principle applies to all characters with special meaning. Another example is the % symbol, which generally implies a format character. If you want to read more..

  • Page - 208

    186 ❘ CHAPTER 6 THE C LANGUAGE Note that scanf takes pointers to variables as arguments, and not the variables themselves, as is the case for printf . This is because scanf must change the variables ’ values inside the function. As you learned earlier in this chapter, because C uses pass - read more..

  • Page - 209

    sprintf includes the same parameters as printf , except it takes an extra one at the beginning of the parameter list, which is the string it is to write to. In this case, the variable str is passed, which is 34 characters long. If you count how many letters there are in the output string, you should come to 33. So an read more..

  • Page - 210

    188 ❘ CHAPTER 6 THE C LANGUAGE This program begins by declaring two pointers to variables of the type FILE . The FILE type is not as simple as a float or int . It is a struct , which you will learn about later in the chapter. In the meantime, you can use FILE pointers read more..

  • Page - 211

    FUNCTION SIGNATURE DESCRIPTION gets char *gets(char *line); Reads a string from standard input up to a new line character, and copies the string into the line variable. It also returns the pointer to the line string. If the end of fi le is encountered before a line is read, the line read more..

  • Page - 212

    190 ❘ CHAPTER 6 THE C LANGUAGE // and the search string if ( argc != 3 ) return 1; // Indicate error // Get input file paths from standard input const char *inpPath = argv[1]; // Get string to search for const char *searchString = argv[2]; // Open read more..

  • Page - 213

    8. Now run the program by choosing Run from the Run menu, and bring up the Debugger Console to check the results (Run ➪ Console). You should see each of the lines from the input fi le that con- tains the search string. How It Works Grepper utilizes many of the skills that you have learned up to this point in the chapter, read more..

  • Page - 214

    192 ❘ CHAPTER 6 THE C LANGUAGE WARNING The scope in global scope refers to where a particular variable can be accessed, and how long it remains in existence. Variables with global scope are visible everywhere in a program, and exist for the runtime of the program, but for most variables, this isn’t the read more..

  • Page - 215

    The if construct in the loop uses the function strstr , which was introduced in the previous section “ Characters and Strings. ” This function searches the string passed as the fi rst argument for the string passed second. If it fi nds the second string in the fi rst, a pointer to the location of the second string read more..

  • Page - 216

    194 ❘ CHAPTER 6 THE C LANGUAGE break; default: printf("I have an undefined beast\n"); } The keyword typedef is used in conjunction with the keyword enum to defi ne a new type called Pet . This type can take three meaningful values: DOG , CAT , and read more..

  • Page - 217

    You can then access the variables inside the struct using the . operator. To set them, you can do this: me.firstName = "Bob"; me.secondName = "Bobbs"; me.address = "1 Holy Smoke Crescent, Who Knows Where, USA"; me.height = 180.0; me.weight = 90.0; me.eyeColor = BLUE; To use the variables, you can do this: float read more..

  • Page - 218

    196 ❘ CHAPTER 6 THE C LANGUAGE This example also demonstrates that, just as with any other type of variable, you can declare a variable that is a pointer to a struct . When you want to access a member of such a variable, it looks like this: (*me).address = "55 Melancholy Road, Loserville"; You fi rst have read more..

  • Page - 219

    The variable heapVar is declared as a pointer, and then assigned to the return value of the function malloc , which is declared in stdlib.h . The name malloc stands for memory allocation — it takes a single argument, which is an integer indicating how many bytes of memory are required to hold the variable. You could read more..

  • Page - 220

    198 ❘ CHAPTER 6 THE C LANGUAGE list.firstNode- > nextNode = NULL; // NULL indicates there are no more nodes // Add a new node in front of the other one ListNode *newNode = malloc(sizeof(ListNode)); newNode- > data = 3.0; newNode- > nextNode = list.firstNode; list.firstNode = read more..

  • Page - 221

    The List type is a struct that holds a single pointer to the fi rst node in the list. typedef struct List_ { ListNode *firstNode; } List; The List is declared and initialized as follows: // Create a list on the stack, and add a node to it List list; read more..

  • Page - 222

    200 ❘ CHAPTER 6 THE C LANGUAGE // Free the memory of all nodes currentNode = list.firstNode; while ( currentNode ) { ListNode *next = currentNode- > nextNode; free(currentNode); currentNode = next; } The current node is again initialized to the fi read more..

  • Page - 223

    When you communicate with the preprocessor in your source code, you give it directives . These are commands to do something, and they are all preceded by a # symbol. The fi rst directive, and probably the most widely used, is #include . Its purpose is to tell the preprocessor to include the text of another fi le in the read more..

  • Page - 224

    202 ❘ CHAPTER 6 THE C LANGUAGE This defi nes the macro MY_AGE to be 21 . Note that MY_AGE is not the number 21, but a string with the value 21 . Macros are just strings of characters to the preprocessor. You could instead write the following, and the preprocessor would not complain: #define MY_AGE read more..

  • Page - 225

    NOTE By now you will probably have realized that macros are usually named in uppercase letters, with underscores separating words. This is a convention only to help distinguish them from standard variables. The preprocessor does not require you to use the convention, but it is good to do so. Otherwise, other programmers may have trouble understanding your read more..

  • Page - 226

    204 ❘ CHAPTER 6 THE C LANGUAGE Simple arithmetic is also allowed in macro defi nitions. Take this reworking of the preceding example: #define BUFFER_BLOCK_SIZE 1024 #if defined USE_SMALL_BUFFER #define BUFFER_SIZE BUFFER_BLOCK_SIZE #elif defined USE_MEDIUM_BUFFER #define BUFFER_SIZE BUFFER_BLOCK_SIZE * 2 #else read more..

  • Page - 227

    Jokes aside, the preceding code includes the operators *, +, > , > = , and ==. You should also have noticed this strange - looking construction: #elif MY_AGE > \ OLD_AGE + MIDDLE_AGE Apart from the strange logic used, the backslash is new. A backslash at the end of a preprocessor line is a line continuation read more..

  • Page - 228

    206 ❘ CHAPTER 6 THE C LANGUAGE ORGANIZING PROGRAMS As explained in Chapter 3, C programs typically comprise many source fi les with the extension .c . These fi les contain the defi nitions of the functions and variables that make up the program. Each source fi le is usually accompanied by a header fi le read more..

  • Page - 229

    The struct Monkey and the function DoSomething are now accessible inside the main function, as shown in the following: #include < stdio.h > #include "Monkey.h" int main() { Monkey monkey; = "Bonzo"; DoSomething( & monkey); return 0; } The last piece of the read more..

  • Page - 230

    208 ❘ CHAPTER 6 THE C LANGUAGE TRY IT OUT Getting Started with MyAddressBook 1. Create a new Command Line Tool project in Xcode and call it MyAddressBook. 2. Create a new C fi le called Person.c in the Source group. To do this, select the Source group in the Groups & Fi les view on the left, and read more..

  • Page - 231

    void InitPerson( Person *person, char *name, char *address ); void DeallocPerson( Person *person ); #endif code snippet MacOSXProg ch06/MyAddressBook 1/Person.h PERSON.C #include "Person.h" #include <stdio.h> #include <stdlib.h> #include <string.h> Person* AllocPerson() { return malloc( sizeof(Person) ); } void InitPerson( Person *person, read more..

  • Page - 232

    210 ❘ CHAPTER 6 THE C LANGUAGE 4. Compile and run the program by clicking the Build and Go toolbar item, and view the output in the Debugger Console. How It Works The MyAddressBook program is considerably more complex than anything you have seen to this point. It makes use of all the aspects of C that you have read more..

  • Page - 233

    The Init . . . functions allocate and initialize any variables in the ADT. The Dealloc . . . method frees the data structures, as well as the ADT variable itself. As you can see in the preceding code, DeallocPerson frees the memory associated with the name and address variables, and then frees the Person read more..

  • Page - 234

    212 ❘ CHAPTER 6 THE C LANGUAGE int numPersons; int maxNumPersons; } AddressBook; AddressBook* CreateAddressBook( const char *pathToAddressBookFile ); AddressBook* AllocAddressBook(); void InitAddressBook( AddressBook *addressBook, const int maxNumPersons ); void InitAddressBookWithFile( AddressBook *addressBook, FILE *file); void read more..

  • Page - 235

    return malloc( sizeof(AddressBook) ); } void InitAddressBook( AddressBook *addressBook, const int maxNumPersons ) { addressBook->persons = malloc( sizeof(Person*) * maxNumPersons ); addressBook->maxNumPersons = maxNumPersons; addressBook->numPersons = 0; } void InitAddressBookWithFile( AddressBook *addressBook, FILE *file ) { int numPersons, read more..

  • Page - 236

    214 ❘ CHAPTER 6 THE C LANGUAGE AddressBook* AddPerson( AddressBook *addressBook, Person *person ) { int n = addressBook->numPersons; // Check that the persons array is big enough. Otherwise indicate error. if ( ++n > addressBook->maxNumPersons ) return NULL; // Array is big enough, so add the new read more..

  • Page - 237

    AddPerson(addressBook, person); // Search for person in the address book person = FindPerson(addressBook, "Joe Citizen"); printf("Found person\nName: %s\nAddress: %s\n", person->name, person->address); DeallocAddressBook(addressBook); return 0; } code snippet MacOSXProg ch06/MyAddressBook 2/main.c read more..

  • Page - 238

    216 ❘ CHAPTER 6 THE C LANGUAGE The other functions declared in the AddressBook.h fi le are AddPerson , for adding a new Person ; FindPerson , for fi nding an existing Person ; and SaveToFile , for saving the whole AddressBook to a fi le. This fi le can be read later to initialize a new read more..

  • Page - 239

    The order in which the data is read from the fi le in InitAddressBookWithFile has to be exactly the same as the order in which it was written. The function SaveToFile is used for writing the AddressBook to a fi le as follows: void SaveToFile( AddressBook *addressBook, FILE *file) { fprintf(file, "%d\n", addressBook- > read more..

  • Page - 240

    218 ❘ CHAPTER 6 THE C LANGUAGE To check if the fi le exists, an attempt is made to open it with fopen . If a NULL pointer is returned, the fi le does not exist. If there is no fi le, an empty AddressBook is initialized with the function InitAddressBook . The AddPerson function in read more..

  • Page - 241

    The last function you should consider is the DeallocAddressBook function, because it demonstrates the sort of actions you must take to clean up when you destruct an ADT variable. void DeallocAddressBook( AddressBook *addressBook ) { // Dealloc all Persons first int i; for ( i = 0; i < addressBook- > numPersons; read more..

  • Page - 242

    220 ❘ CHAPTER 6 THE C LANGUAGE person = FindPerson(addressBook, "Joe Citizen"); printf("Found person\nName: %s\nAddress: %s\n", person- > name, person- > address); DeallocAddressBook(addressBook); return 0; } This creates an AddressBook instance, adds two Person instances to it read more..

  • Page - 243

    CONTROLLER.C #include "Controller.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Person.h" #include "AddressBook.h" Controller* AllocController() { return malloc( sizeof(Controller) ); } void InitController(Controller *controller) { controller->pathToAddressBookFile = "/var/tmp/addressbook.txt"; read more..

  • Page - 244

    222 ❘ CHAPTER 6 THE C LANGUAGE case 'q': ProcessSaveRequest(controller); shouldStop = 1; break; default: printf("You entered an invalid choice. Try again.\n"); } return shouldStop; } read more..

  • Page - 245

    int main () { Controller *controller = AllocController(); InitController(controller); PrintIntroductoryMessage(controller); // Main run loop int exitMainLoop = 0; while ( !exitMainLoop ) { PrintUserOptions(controller); char line[256]; gets( line ); read more..

  • Page - 246

    224 ❘ CHAPTER 6 THE C LANGUAGE WARNING This design is known as Model-View-Controller (MVC), and is very important in Cocoa programming, which you learn about in Chapter 8. Put simply, the data objects, such as Person and AddressBook , make up the Model. The View is the interface with the user, in this case a console read more..

  • Page - 247

    case 'f': ProcessFindPersonRequest(controller); break; case 's': ProcessSaveRequest(controller); break; case 'q': ProcessSaveRequest(controller); shouldStop = 1; read more..

  • Page - 248

    226 ❘ CHAPTER 6 THE C LANGUAGE ProcessSaveRequest fi rst opens a fi le for writing, and then asks the AddressBook to save its contents on the fi le using the SaveToFile function, and fi nally closes the fi le again. void ProcessSaveRequest(Controller *controller) { FILE *file = fopen(controller- read more..

  • Page - 249

    is passed to the Controller function ProcessUserChoice , which takes the appropriate action. ProcessUserChoice returns a non - zero value when the program should stop. After the loop exits, the DeallocController method frees the memory of the Controller and the AddressBook that it contains. This concludes your exploration read more..

  • Page - 250

    228 ❘ CHAPTER 6 THE C LANGUAGE WHAT YOU LEARNED IN THIS CHAPTER C the Latin of programming languages, forming the basis of most modern operating systems Function a block of source code that can be executed via a call from other parts of the program Variable a labeled read more..

  • Page - 251

    7 The Objective - C Language WHAT YOU WILL LEARN IN THIS CHAPTER : What OOP is, and its most important characteristics The extensions to C defi ned by the Objective - C 2.0 language, including object - oriented programming How to write object - oriented programs in Objective - C, using the Foundation framework read more..

  • Page - 252

    230 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE OBJECT - ORIENTED PROGRAMMING Before you begin to learn Objective - C, you need to know a little bit about what it was designed to achieve. OOP has really caught on during the last 20 years or so, but it is now the de facto standard for all programming languages. read more..

  • Page - 253

    The last major aspect of OOP languages not possessed by procedural languages is polymorphism . The word may be terrifying, but the meaning is less so: polymorphism is the capability of something to behave differently depending on the circumstances. In the context of OOP, it refers to the ability of a single method invocation — the read more..

  • Page - 254

    232 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE Person inherits all the data and methods of the class NSObject . NSObject is an important Cocoa class from which nearly all classes ultimately descend. You learn more about this class as you go. After the superclass, a block in braces declares the data belonging to the class. read more..

  • Page - 255

    The implementation usually appears in a fi le with the extension .m , and the same base name as the header fi le in which the interface block appeared. In this case, the Person interface would probably be in the fi le Person.h , and the implementation in Person.m . The implementation block is similar to the interface read more..

  • Page - 256

    234 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE of a class without writing a subclass. You should be wary, however, that you cannot easily call the original method from inside your category method when you do this. Finally, Objective - C 2.0 introduced a new type of category, the class extension . Class extensions are unnamed, anonymous read more..

  • Page - 257

    The parameter types in a method declaration are also optional, but if you exclude them, the parameter is assumed to be an object. A generic object has the type id in Objective - C, as shown in the following method declaration: -(void)doSomethingWithObject:(id)object1 andObject:(id)object2; Here is an equivalent declaration: read more..

  • Page - 258

    236 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE The whole invocation appears between square brackets. The object to which the method belongs — in this case, the object obj — comes fi rst, followed by the segmented method name. After each colon in the name, an argument is given. In this case, the argument variables read more..

  • Page - 259

    In the following Try It Out example, you rewrite the Grepper program from Chapter 6 in Objective - C. This will give you an idea of what Objective - C looks like, and the way objects and classes are used. TRY IT OUT Rewriting Grepper in Objective - C 1. Create a new project in Xcode. In the New Project read more..

  • Page - 260

    238 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE NSRange searchStringRange = [line rangeOfString:searchString]; // If string was found, write it to standard output // Also add a new line character if ( searchStringRange.location != read more..

  • Page - 261

    The main body of the code appears in a block between the Objective - C keywords @try and @catch . These are used for exception handling. Exception handling is about treating exceptional occurrences and errors. Objective - C provides facilities for exception handling that allow you to jump from anywhere in the @try block to the read more..

  • Page - 262

    240 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE Various methods are used to create the strings, including stringWithCString:encoding: to create strings from the char* string parameters of the main function, and stringWithContentsOfFile:usedEncoding: error: , which reads the fi le at the path passed and places its contents in an read more..

  • Page - 263

    These keywords can be inserted into the data section of a class ’ s interface block and applies to any data that follows, up to the end of the block or the next keyword. For example, imagine that you want to restrict access to the name attribute of the Person class, but wish to make the address attribute directly read more..

  • Page - 264

    242 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE -(NSString *)address; // Getter method for address -(void)setAddress:(NSString *)newAddress; // Setter method for address ... @end Accessors generally come in pairs, with a setter and a getter for each read more..

  • Page - 265

    NOTE Languages such as Objective - C and Java have opted for single inheritance, but add a second mechanism to mimic one of the better aspects of multiple inheritance: the ability to have two classes not in the same inheritance tree share some interface. Objective - C provides protocols for this purpose, which are covered later in this chapter. read more..

  • Page - 266

    244 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE The SuperClass also inherits from SuperDuperClass , so all the instance variables and methods in SuperDuperClass are also included in SubClass , as though it had declared them itself. SubClass is said to be a descendent of SuperDuperClass , and includes its methods read more..

  • Page - 267

    This method fi rst invokes the release method of the instance variable instanceVar , and then invokes the dealloc method of the superclass. Methods in the superclass can be called using the variable super . Effectively, the dealloc method in the superclass has been extended in the subclass to include the line that read more..

  • Page - 268

    246 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE Looking at this function, you may be led to think that PrintAndReturnString can be used only with objects of the class NSString . This is not true. It can be used with objects of any class descending from NSString , including NSMutableString . So the following calling read more..

  • Page - 269

    objc_msgSend performs a search for a function matching the arguments passed to it. It fi rst looks in the class of obj to see if a doSomething method has been defi ned there. If not, it moves to the superclass to see if doSomething appears there. It then moves to the superclass of the superclass, and so read more..

  • Page - 270

    248 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE DYNAMIC VERSUS STATIC TYPING Programming languages generally fall into two basic categories: statically typed and dynamically typed . Statically typed languages such as C++ and Java require that the type of an object be explicitly known when the program is compiled, so that the compiler can read more..

  • Page - 271

    @interface Task : NSObject < Execution > { } @end Protocols that a class conforms to are added after the superclass in triangular brackets. If there are multiple protocols, they are separated by commas. It is not necessary to re - declare the protocol methods in the conforming class ’ s interface block, though you can if you want. read more..

  • Page - 272

    250 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE The Execution protocol requires that all of its methods be implemented by each conforming class. Sometimes this is what you want, and sometimes it isn ’ t. When you have a situation where you want to give classes the option of leaving some methods out, you can use a protocol with read more..

  • Page - 273

    The class TaskObserver implements two of the methods of the TaskDelegate protocol. The method taskExecutionShouldBegin: is sent by a Task object to its delegate whenever the execute method is called, and execution is about to begin. The Task object passes itself as the only argument so that the read more..

  • Page - 274

    252 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE The preceding example dealt with optional methods in protocols as they are used to implement a delegation relationship, which is a common application, but by no means the only one. Other applications also exist, and many involve mixing required and optional methods in the same protocol. NAMING read more..

  • Page - 275

    NOTE The example is a bit artifi cial, because you should always call setDate: in your code, rather than setValue:forKey: . KVC should be reserved for cases where you want to program to a generic interface, rather than explicitly including methods such as setDate: in your code. In other words, when you don ’ t know what setters and read more..

  • Page - 276

    254 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE The return value of an assignment is simply the value of the left - hand side (LHS) after the assignment — in this case, the value of self . Another Cocoa convention says that if there is an error in an initializer, that initializer should return nil . The if statement read more..

  • Page - 277

    -(id)initWithName:(NSString *)newName andAge:(unsigned)newAge { if ( self = [super init] ) { [self setName:newName]; [self setAge:newAge]; } return self; } ... @end The designated initializer is the most general one: initWithName:andAge: . It allows you read more..

  • Page - 278

    256 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE Here is the dealloc method for the Cat class: -(void)dealloc { [name release]; [super dealloc]; } A release message is sent to the name string to indicate that it is not needed anymore by the Cat object. If it is still being used by read more..

  • Page - 279

    any object that you want to store in the dictionary. The NSDictionary used in the preceding code is created with only a single entry, which has the NSString key @ “ TempDir ” and the NSString value @ “ /var/tmp ” . MEMORY MANAGEMENT There are two types of memory management that can be used in an read more..

  • Page - 280

    258 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE You can also explicitly indicate that an object should remain in existence by sending it a retain message, which increases the retain count by 1. retain is used when part of your code needs to ensure that an object instantiated elsewhere remains in existence. NOTE read more..

  • Page - 281

    TRY IT OUT Memory Management with Cats 1. Create a new Foundation Command Line Tool project in Xcode. Select Command Line Tool in the Application group of the New Project pane, and then choose Foundation from the Type pop - up button. Name the project Memories of Cats . 2. Select the Memories of Cats.m read more..

  • Page - 282

    260 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE [cat4 release]; // Deallocates cat4 [pool release]; // Deallocates cat1 and cat2 return 0;} code snippet MacOSXProg ch07/Memories of Cats/Memories of Cats.m 3. Click the Build and Run toolbar item to compile and run the program, read more..

  • Page - 283

    retainCount method of NSObject returns the retain count of an object. A bit further on, cat3 gets copied, which does not affect its retain count, and then it gets released. At this point, the retain count drops to 0 , so the Cat is deallocated immediately, with its dealloc method called. cat4 read more..

  • Page - 284

    262 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE -(NSDate *)date; -(void)setDate:(NSDate *)newDate; -(WeatherStation *)weatherStation; -(void)setWeatherStation:(WeatherStation *)newStation; @end The question is, how do you implement the accessor methods in the WeatherConditions class? The float variable read more..

  • Page - 285

    The problem with this is that it doesn ’ t account for instances when newDate and date are the same object. If they are, the object will be released by the fi rst line of the setter and may be deallocated before the second line is executed. This is why it is necessary to check whether the two are the same before read more..

  • Page - 286

    264 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE There are two parts to creating a property: declaring it in the interface block of the class, and directing the compiler to generate it in the class implementation. Here is how you declare the WeatherConditions class using properties instead of accessor methods: @interface WeatherConditions { float read more..

  • Page - 287

    are using the Core Data framework, which automatically generates accessor methods for you at runtime. (Core Data is covered in Chapter 10.) By far the most common of these is @synthesize . Here is how you would use @synthesize with the WeatherConditions class: @implementation WeatherConditions @synthesize read more..

  • Page - 288

    266 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE NOTE The dot notation feels very familiar to developers coming from other programming languages, but it caused quite a controversy when it was introduced with Objective - C 2.0. Many felt it was just a marketing trick to attract developers from other platforms. To this read more..

  • Page - 289

    PERSON.M #import "Person.h" @implementation Person @synthesize name, address; // Designated -(id)initWithName:(NSString *)aName andAddress:(NSString *)anAddress { if ( self = [super init] ) { name = [aName copy]; self.address = anAddress; read more..

  • Page - 290

    268 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE NSData *data = [si availableData]; NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"\n"]; return [string stringByTrimmingCharactersInSet:set]; } read more..

  • Page - 291

    The description method of Person is used in other parts of the program to write out the details of the Person for the user. The WriteToStandardOutput function uses the class NSFileHandle to write to the standard output stream as follows: void WriteToStandardOutput(NSString *string) { NSFileHandle *so = read more..

  • Page - 292

    270 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE TRY IT OUT Writing the AddressBook Class 1. Open the MyAddressBook in Objective C project, and create the fi les AddressBook.h and AddressBook.m in the Source group of the Groups & Files view. Choose the fi le type Objective - C Class in the read more..

  • Page - 293

    else { // Create a new AddressBook sharedAddressBook = [[AddressBook alloc] init]; } } return sharedAddressBook; } -(id)init { if ( self = [super init] ) { personForNameDict = [[NSMutableDictionary alloc] init]; read more..

  • Page - 294

    272 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE +(void)writeSharedAddressBookToFile { [[AddressBook sharedAddressBook] writeToFile:AddressBookFilePath]; } -(void)addPerson:(Person *)newPerson { [personForNameDict setObject:newPerson]; } -(Person *)personForName:(NSString *)name { return read more..

  • Page - 295

    How It Works The AddressBook class stores Person objects in a Foundation container class called NSMutableDictionary . An NSMutableDictionary stores key - value pairs, such as an NSDictionary ; in fact, it is a subclass of NSDictionary . The difference is that an NSMutableDictionary is mutable and can be modifi read more..

  • Page - 296

    274 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE NSFileManager *fm = [NSFileManager defaultManager]; if ( [fm fileExistsAtPath:AddressBookFilePath] ) { sharedAddressBook = [[AddressBook alloc] initWithFile:AddressBookFilePath]; } else { read more..

  • Page - 297

    Fast enumeration is used to move through the values of the NSMutableDictionary . Each Person ’ s name is appended to an NSMutableString , followed by the address. ( NSMutableString is a subclass of NSString . The value of an NSMutableString can change after it is created, unlike instances of NSString .) After read more..

  • Page - 298

    276 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE At the completion of each loop iteration, a new Person is created with the name and address read, and added to the AddressBook with the addPerson method. The main function is again used for testing purposes. It creates an AddressBook object, adds two Person read more..

  • Page - 299

    @end @implementation Controller +(void)initialize { NSMutableDictionary *dict = [NSMutableDictionary dictionary]; for ( Class c in [Command commandClasses] ) { [dict setObject:c forKey:[c commandIdentifier]]; } commandClassForChoiceDict = [dict retain]; } read more..

  • Page - 300

    278 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE } else { NSDictionary *infoDict = [self requestCommandInfoFromUser:commClass]; AddressBook *ab = [AddressBook sharedAddressBook]; Command *comm = [[[commClass alloc] initWithAddressBook:ab] autorelease]; outputString = [comm executeWithInfoDictionary:infoDict]; read more..

  • Page - 301

    -(AddressBook *)addressBook; @end @interface Command (AbstractMethods) +(NSString *)commandIdentifier; +(NSString *)commandDescription; +(NSArray *)requiredInfoIdentifiers; // Info needed from the user -(NSString *)executeWithInfoDictionary:(NSDictionary *)infoDict; @end read more..

  • Page - 302

    280 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE @end @implementation QuitCommand +(NSString *)commandIdentifier { return @"q"; } +(NSString *)commandDescription { return @"Save and quit"; } +(NSArray *)requiredInfoIdentifiers { return [NSArray array]; } -(NSString *)executeWithInfoDictionary:(NSDictionary *)infoDict { [AddressBook writeSharedAddressBookToFile]; return nil; } @end code read more..

  • Page - 303

    4. Compile and run the program by clicking the Build and Run toolbar item, and open the console by choosing Console from the Run menu . 5. Follow the instructions in the console. Quit the program by typing q at the prompt. 6. Rerun the program by selecting Run from the Run menu. Try entering invalid responses read more..

  • Page - 304

    282 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE printUserOptions begins by calling the Command class method commandClasses . This returns an NSArray containing all the subclasses of Command , which represent the different options available to the user. The built - in Objective - C keyword Class is used to read more..

  • Page - 305

    The commandClasses method returns an NSArray that is also called commandClasses , which gets initialized in the initialize class method as follows: +(void)initialize { commandClasses = [[NSArray arrayWithObjects: [QuitCommand class], nil] retain]; } +(NSArray read more..

  • Page - 306

    284 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE This method basically consists of a for loop that prints out a request for each piece of information required by the Command , and stores the user response in an NSMutableDictionary with the request string as key. The last method of the Command class is read more..

  • Page - 307

    The advantage of the OO design used here is that the Controller class is quite generic. It makes no reference to the various commands available to the user — this functionality has been split off into the Command class hierarchy. To add a new command (that adds a person to the address book, for example), you only have to read more..

  • Page - 308

    286 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE TRY IT OUT Adding Command Subclasses 1. Open the MyAddressBook in Objective C project and add the following source code to the bottom of the Commands.h and Commands.m fi les: COMMANDS.H @interface NewPersonCommand : Command { } @end read more..

  • Page - 309

    +(NSString *)commandIdentifier { return @"f"; } +(NSString *)commandDescription { return @"Find an address"; } +(NSArray *)requiredInfoIdentifiers { return [NSArray arrayWithObject:@"Name of person"]; } -(NSString *)executeWithInfoDictionary:(NSDictionary *)infoDict { read more..

  • Page - 310

    288 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE 3. Compile and run the program by clicking the Build and Run toolbar item. 4. Open the console by choosing Console from the Run menu. Enter a few names and addresses, and then try to retrieve them again with a fi nd request. Try saving the address book and then quit. 5. read more..

  • Page - 311

    Aspects of Objective - C such as classes, protocols, categories, methods, properties, data hiding, messaging, and memory management How to write a Foundation Tool in Objective - C that makes use of fundamental Cocoa classes from the Foundation framework, leveraging the OO capabilities of Objective - C In the next chapter, you learn read more..

  • Page - 312

    290 ❘ CHAPTER 7 THE OBJECTIVE-C LANGUAGE WHAT YOU LEARNED IN THIS CHAPTER OOP object - oriented programming, a popular programming paradigm based on combining data and behavior in objects Objective - C the C - based OOP language used to develop applications for Mac OS X Class an read more..

  • Page - 313

    8 Introduction to Cocoa WHAT YOU WILL LEARN IN THIS CHAPTER: How to use outlets and actions to connect Cocoa application interfaces to your custom code How to use Cocoa Bindings as an alternative to outlets and actions How Apple uses the Model/View/Controller design pattern to build reusable, extendable classes People use the read more..

  • Page - 314

    292 ❘ CHAPTER 8 INTRODUCTION TO COCOA As a topic, Cocoa is huge. The API reference alone would make a hefty book if it was printed. Fortunately, Cocoa ’ s API reference is installed on your hard drive, where you can search through it at your leisure. This chapter builds upon your experience from Chapter 7 about writing read more..

  • Page - 315

    Here, IBAction is really the same as void ; it ’ s just a marker to remind you that this method is known to Interface Builder as an action. The sender parameter is normally a pointer to the control that triggered the action. For example, when you click the button, it sends its action message to a target object. You set read more..

  • Page - 316

    294 ❘ CHAPTER 8 INTRODUCTION TO COCOA TRY IT OUT Building the Email Formatter Interface 1. In Xcode, create a new Cocoa Application project named Email Formatter . Make sure all the options are unchecked — you just want a simple Cocoa application. 2. Double - click the MainMenu.xib nib fi le. It read more..

  • Page - 317

    How It Works There isn ’ t much new here, because you got a lot of practice building UIs in Chapter 4. However, there are some important things to note. One is the horizontal separator shown in Figure 8 - 2. This control can be found in the Library under the name Horizontal Line and is actually an instance of the read more..

  • Page - 318

    296 ❘ CHAPTER 8 INTRODUCTION TO COCOA 4. Scroll up in the list until the Outlets section is visible. The Outlets section has two items: delegate and nextKeyView . 5. Select the nextKeyView outlet. The overlay disappears and a line connecting both text fi elds fl ashes a few times. 6. read more..

  • Page - 319

    How It Works You can set outlets either by Control - dragging from one instance to another, or by dragging from the Connections Inspector to a target instance. Control - dragging between instances is often convenient when you want to make a connection between two objects quickly. The Connections Inspector is often convenient when you want to make a number read more..

  • Page - 320

    298 ❘ CHAPTER 8 INTRODUCTION TO COCOA TRY IT OUT Declaring a Custom Controller 1. In Xcode, create a new Objective - C class fi le named EmailController.m . Make sure you create the corresponding EmailController.h header fi le. 2. Replace the contents of EmailController.h with the read more..

  • Page - 321

    6. Change the object ’ s class from the default NSObject to EmailController . As you start typing, Interface Builder will auto- matically suggest class names found within your Xcode project. 7. Switch to the Connections Inspector. The list of Outlets and Received Actions contains the new instance variables and methods you added read more..

  • Page - 322

    300 ❘ CHAPTER 8 INTRODUCTION TO COCOA 3. Control - drag from the First Name editable text fi eld to the Email Controller instance in your nib window. A small list appears, showing you an outlet named delegate and an action named textFieldChanged: . 4. Choose the textFieldChanged: action. The small read more..

  • Page - 323

    TRY IT OUT Writing Your Controller 1. Open EmailController.m in Xcode. The class implementation is currently empty, as shown here: #import "EmailController.h" @implementation EmailController @end 2. Add the following textFieldChanged: method to the class: - read more..

  • Page - 324

    302 ❘ CHAPTER 8 INTRODUCTION TO COCOA The textFieldChanged: method does three things. First, it gets the content of the text fi elds using its - stringValue methods. The NSTextField objects inherit - stringValue from their superclass, NSControl . The NSControl class is the common ancestor read more..

  • Page - 325

    Apple introduced Cocoa Bindings , a new way of connecting Cocoa controls to your custom Objective - C objects, to deal with some of these scalability issues. Instead of connecting a control to outlet instance variables and action methods, Cocoa Bindings lets you connect a control directly to an object ’ s value. When the control read more..

  • Page - 326

    304 ❘ CHAPTER 8 INTRODUCTION TO COCOA TRY IT OUT Creating an NSObjectController 1. In Xcode, create a new Objective - C class fi le named EmailAddress.m . Make sure you create the corre- sponding EmailAddress.h header fi le. Don ’ t worry about editing these fi les for now. 2. In read more..

  • Page - 327

    TRY IT OUT Connecting Controls to NSObjectController 1. Select the editable First Name text fi eld in your Window editor. 2. Choose the Bindings panel in the Inspector window. The Bindings Inspector appears, as shown in Figure 8 - 15. 3. Click the Value disclosure triangle under the Value section read more..

  • Page - 328

    306 ❘ CHAPTER 8 INTRODUCTION TO COCOA 8. If necessary, click the Value disclosure triangle under the Value section to reveal the group of controls. These controls resemble the ones you saw in Figure 8 - 16. 9. Enter formattedEmail in the Model Key Path text fi eld and press Return. Again note that the read more..

  • Page - 329

    TRY IT OUT Writing Your EmailAddress Class 1. Open EmailAddress.h in Xcode. The class interface is currently empty, as shown here: @interface EmailAddress : NSObject { } @end 2. Change the declaration of EmailAddress to include the following instance variables: @interface read more..

  • Page - 330

    308 ❘ CHAPTER 8 INTRODUCTION TO COCOA email]; } return nil; } @end code snippet MacOSXProg ch08/Email Formatter 2/EmailAddress.m 6. Save your changes to EmailAddress.m . 7. Build and run your project. Xcode compiles your code, builds your application read more..

  • Page - 331

    However, Key Value Coding doesn ’ t explain why your application knew to request the formattedEmail value when your text fi elds changed. You used a special class method named +keyPathsForValuesAffectingValueForKey: to tell Cocoa Bindings that formattedEmail depends on the values of your other keys. This method is built read more..

  • Page - 332

    310 ❘ CHAPTER 8 INTRODUCTION TO COCOA Objects responsible for presenting information to the user are called views . Concrete examples of views abound in Cocoa; for example, windows, buttons, menus, and text fi elds are all views. Many AppKit classes even use the term in their class names, such as NSTextView and read more..

  • Page - 333

    How to bind your application to your custom code using Cocoa Bindings. When you use Cocoa Bindings, you no longer need to create outlets and actions that exist only to marshal data into and out of your user interface. About the Model/View/Controller design pattern and how it can encourage code reuse. In the next chapter, you learn about read more..

  • Page - 334

    312 ❘ CHAPTER 8 INTRODUCTION TO COCOA WHAT YOU LEARNED IN THIS CHAPTER Instance an Objective - C object visible in Interface Builder fi les Outlet a reference to an instance that can be set within Interface Builder, often marked with an IBOutlet keyword Action an Objective - C read more..

  • Page - 335

    Document - Based Cocoa Applications WHAT YOU WILL LEARN IN THIS CHAPTER: How to use an NSDocument subclass to store your document data How to use an NSWindowController subclass to organize and display your document interface How to bind menu items to your documents using Interface Builder Macintosh read more..

  • Page - 336

    314 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS In this chapter you learn : To use an NSDocument subclass to store your document data To use an NSWindowController subclass to organize and display your document interface How to bind menu items to your documents using Interface Builder WORKING WITH DOCUMENTS The read more..

  • Page - 337

    Creating a New Document In the following Try It Out sections, you build a simple image viewer application that uses a custom NSWindowController class along with a custom NSDocument class. Rather than building a small standalone example, you build this functionality directly into the Slide Master project you started in Chapter 5. This gives read more..

  • Page - 338

    316 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS TRY IT OUT Confi guring a Scrollable Image View 1. In Xcode, open the Slide Master project you created in Chapter 5. If you haven ’ t built this project yet for some reason, fl ip back to Chapter 5 and follow the example in the “ Building read more..

  • Page - 339

    How It Works The NSImageView class is a simple control that draws images. It ’ s useful in cases such as this where you need to draw an image in a window. NSImageView objects can also be editable, meaning you can change the image by dragging in a new image fi le from the Finder. These kinds of image views are often read more..

  • Page - 340

    318 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS bearing on the fi nished product. You made sure the NSImageView doesn ’ t resize with the window because its viewable area is being managed by an NSScrollView . When the window changes size, your NSScrollView changes with it, allowing you to see more of the read more..

  • Page - 341

    9. In Xcode, replace the content of ImageWindowController.m with the following code: #import "ImageWindowController.h" #import "ImageDocument.h" @implementation ImageWindowController - (void)windowDidLoad { [super windowDidLoad]; // get the image from the read more..

  • Page - 342

    320 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS How It Works In Cocoa applications, interface fi les are opened on behalf of a particular object, which is known as the interface fi le ’ s owner . You can think of the interface fi le ’ s owner as the object that actually loaded the nib fi read more..

  • Page - 343

    typedef struct _NSSize { float width; float height; } NSSize; typedef struct _NSRect { NSPoint origin; NSSize size; } NSRect; You can work these data types either by setting their values directly, or by using constructor functions such as NSMakeRect or NSMakePoint . Normally when changing the size of a window, you read more..

  • Page - 344

    322 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS 3. Open ImageDocument.m . Xcode has added a lot of starter code to this fi le for you, including some usage notes. This provides a good place to start when hooking up your document functionality. 4. Replace the ImageDocument.m content with the read more..

  • Page - 345

    - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **) outError { mImage = [[NSImage alloc] initWithData:data]; return (mImage != nil); } #pragma mark Slide Accessors @synthesize image = mImage; #pragma mark Menu Management read more..

  • Page - 346

    324 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS 8. Build and run Slide Master. The Slide Master application opens various image fi les and displays them in a simple window, much as the Preview application does. As you resize the window, scrollbars appear. However, when the window is larger than the image data, the read more..

  • Page - 347

    Document classes that delegate window management to NSWindowController objects should use the makeWindowControllers method instead of windowNibName . ImageDocument uses makeWindowControllers to initialize its window controllers. Window controllers normally manage windows found in a nib fi le, and in these cases you simply need to pass read more..

  • Page - 348

    326 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS opportunity for target objects to modify menu and menu item states prior to display, typically to enable or disable menu items. If - validateMenuItem: returns YES , the item will be enabled; otherwise the menu will be grayed out. Your validateMenuItem: read more..

  • Page - 349

    To solve this problem cleanly, you need to change the way your NSImageView resizes. When the window is larger than the image, the NSImageView should grow along with the window. This allows you to take advantage of NSImageView ’ s ability to center images in a large area. When the window is smaller than the read more..

  • Page - 350

    328 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS 3. Replace the content of SlideImageView.m with the following code: #import "SlideImageView.h" @implementation SlideImageView - (void)setFrameSize:(NSSize)viewSize { NSScrollView *scrollView = self.enclosingScrollView; read more..

  • Page - 351

    5. Save your changes to source fi les. 6. Open the ImageDocument interface fi le in Interface Builder. 7. Double - click the NSScrollView in your document window to select its NSImageView . Again, you may need to click in the lower - left corner of the scroll view to hit the image view. read more..

  • Page - 352

    330 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS SlideImageView makes sure the new frame size is at least as large as its image. That ’ s simply a matter of checking the image size against the image ’ s visible area, and using the larger of the two. Because the image document uses an NSScrollView to manage the read more..

  • Page - 353

    When you ’ re done, the Inspector should resemble Figure 9 - 8. 4. Remove the Format menu from the main menu by selecting it and pressing Delete twice. The fi rst Delete will remove the Format menu ’ s items, and the second Delete will remove the Format menu itself from the menu bar. 5. Add Actual Size, Zoom In, Zoom Out, read more..

  • Page - 354

    332 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS Responder instance is exactly that placeholder. Recall from the Email Formatter examples that you manually set your window ’ s initialFirstResponder to a specifi c item, and that the fi rst responder changed as you tabbed from item to item. First Responder is AppKit read more..

  • Page - 355

    RESPONDER DESCRIPTION The window ’ s fi rst responder This is the NSScrollView instance in your image window. The window ’ s view hierarchy Each superview between the scroll view and the window gets an opportunity to handle the actions. Currently, this is the window ’ s content view. The read more..

  • Page - 356

    334 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS { NSClipView *clipView = scrollView.contentView; // compute normal clip bounds from the frame NSRect bounds = clipView.frame; bounds.origin = NSZeroPoint; // reset the read more..

  • Page - 357

    // constrain the zoom out to fit the actual size. bounds.size.width = MIN(bounds.size.width, frame.size.width); bounds.size.height = MIN(bounds.size.height, frame.size.height); // adjust the bounds origin so the image remains centered while zooming. bounds.origin.x = NSMidX(visible) - read more..

  • Page - 358

    336 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS Every NSView also has a bounds rect. The bounds rect describes the position and size of the view relative to itself . Normally a view ’ s bounds rect is the same size as its frame rect, and the bounds origin is 0, 0. Changing the bounds rect origin read more..

  • Page - 359

    SUMMARY The Cocoa frameworks go beyond a simple toolkit for windows, menus, and buttons. They also provide a lot of common application behavior. By giving you such things as an Open Recent window and a pop - up menu embedded in your window title bar for free, they encourage you, and everyone else, to use them. As a result, nearly every read more..

  • Page - 360

    338 ❘ CHAPTER 9 DOCUMENT - BASED COCOA APPLICATIONS EXERCISES 1. Create a document - based application that reads and writes text fi les. You can use the following: - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding to read fi le data into an NSString , and you can use - (NSData read more..

  • Page - 361

    WHAT YOU LEARNED IN THIS CHAPTER NSDocument A model object encapsulating a document, commonly backed by a fi le NSWindowController A controller object that manages a document window and its controls makeWindowControllers NSDocument method responsible for creating one or more window controllers for a document read more..

  • Page - 362

    c09.indd 340 12/12/09 1:34:52 PM read more..

  • Page - 363

    10 Core Data - Based Cocoa Applications WHAT YOU WILL LEARN IN THIS CHAPTER: How to design a document data model in an object graph How to observe, change, and sort Core Data objects using Cocoa Bindings How to create your own Core Data objects and insert them into a managed object context How to manually set read more..

  • Page - 364

    342 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS simply as fi les — especially with Core Data handles, with all the particulars of pushing objects into, and out of, the database. There are other benefi ts to using Core Data, as you will soon see. Apple describes Core Data as an advanced programming topic. Core Data read more..

  • Page - 365

    You can use any of these techniques in your NSDocument subclass ’ s fi le handling code. Xcode ’ s template for new NSDocument subclasses is slightly biased toward the approach of encoding objects into an NSData object. This technique is fairly practical for Cocoa applications, where document state is normally stored in read more..

  • Page - 366

    344 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS In practice, Core Data doesn ’ t need to construct custom Objective - C classes for you, though it will if you ask. Normally Core Data uses the NSManagedObject class for object graph model objects. The specifi c details of an object ’ s relationships and attributes are read more..

  • Page - 367

    TRY IT OUT Building a Core Data Object Graph 1. In Xcode, add a group to the Groups & Files list. Name it Models. 2. Create a new fi le in the Models group. Use the data model template for this fi le, shown in Figure 10 - 3. Name the fi le SlideShowDocument.xcdatamodel . FIGURE read more..

  • Page - 368

    346 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS FIGURE 10-5 4. Click Finish. A new empty SlideShowDocument.xcdatamodel fi le has been added to your project and is selected. Xcode ’ s editor has changed from the usual text view to a special data modeling tool you saw in Figure 10 - 2. 5. In the read more..

  • Page - 369

    10. In the Entity table, rename Entity1 to Slide. 11. In the Property table, create a new Attribute named image . Change its Type from Undefi ned to Transformable, as shown in Figure 10 - 7. FIGURE 10-7 12. Create a new Slide Relationship named slideShow . Set the Destination to SlideShow and set Inverse read more..

  • Page - 370

    348 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS Application and Use Core Data For Storage options when you created the Slide Master project, Xcode would have created this fi le for you. One benefi t of having data model support built into Xcode is tighter integration with other fi les in your project. When you create a read more..

  • Page - 371

    This sounds familiar to other Cocoa technologies you ’ ve worked with: Cocoa Bindings and Properties. You learned about Properties in Chapter 7, where you used them to synthesize accessors for Objective - C instance variables. You declared what kind of variable accessors you wanted (such as “ readonly ” or “ readwrite, read more..

  • Page - 372

    350 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 5. Open SlideShowDocument.m and replace its contents with the following code. Note that the default windowNibName method was replaced by a makeWindowControllers method. You don ’ t need special code to read and write the document. #import read more..

  • Page - 373

    replace the source fi les with new ones than to rename them and change all the references to MyDocument within the source code. That leaves you with the task of updating the nib fi le and Info.plist by hand. SlideShowDocument subclasses from NSPersistentDocument , which is the base class for all Core Data- based documents. read more..

  • Page - 374

    352 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 12. Click once on the table view to select its enclosing scroll view. 13. In the scroll view ’ s Size Inspector change the view so that it resizes horizontally and vertically and is anchored to the window ’ s sides. 14. Select the table view by read more..

  • Page - 375

    21. Drag a Gradient Button from your Library into your window. Position it against the bottom edge of the table at the left corner. 22. Change the button ’ s title to + , resize the button to 26 pixels wide, and anchor the button to the lower - left corner of the window. 23. Copy the button, name read more..

  • Page - 376

    354 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 31. In the Size Inspector, make sure the image view shrinks and grows properly when its window is resized. Also anchor the edges to the sides of the window. 32. In the Bindings Inspector bind Value to Slides Controller and change the Model Key Path to image . read more..

  • Page - 377

    First you created an object controller that represents the main SlideShow model object. In the Email Formatter 2 program from Chapter 8 your object controller was bound to an object that was instantiated by the nib fi le. In Slide Master you bound the object controller to the document ’ s slideshow by way of the File ’ s Owner: read more..

  • Page - 378

    356 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS or a menu command. But it ’ s easy to create simple add and remove buttons and connect them to the array controller ’ s add: and remove: actions. In this example, you confi gured the table column to display images. Changing the column ’ s data type read more..

  • Page - 379

    key slideShow. 2009-09-26 11:49:19.770 Slide Master[6928:a0b] [ < SlideShowDocument 0x100473c50 > valueForUndefinedKey:]: this class is not key value coding-compliant for the key slideShow. The slideShow property isn ’ t just an instance variable, it is the root object of your document model. It needs to be an object in read more..

  • Page - 380

    358 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS ofType:(NSString *)fileType modelConfiguration:(NSString *)configuration storeOptions:(NSDictionary *)storeOptions error:(NSError **)error; { BOOL result = [super configurePersistentStoreCoordinatorForURL:url read more..

  • Page - 381

    [self addWindowController:slideShowWindowController]; } #pragma mark Properties @synthesize slideShow = mSlideShow; @end code snippet MacOSXProg ch10/Slide Master 2/SlideShowDocument.m 3. While you ’ re in Xcode, open SlideImageView.m and add the following method to the SlideImageView read more..

  • Page - 382

    360 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 6. Drag an image into the window. The image will appear both in the large image area and also in the table. 7. Repeat steps 5 and 6 a number of times until you have added two or three images to your document. Your document should resemble Figure 10 - 16. read more..

  • Page - 383

    initWithType:error: which gets called only for new untitled documents. This method is the ideal place to create your root slideshow object. Creating a managed object in a managed object context is ordinarily a two - step process: fi rst to get the entity description for that object, and then to create the new managed object with read more..

  • Page - 384

    362 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS SELECTING FILES WITH OPEN PANELS As you know, AppKit ’ s NSDocument class handles your application ’ s File ➪ Open menu command for you. It reads the list of supported fi le extensions and fi le types out of your application ’ s Info. plist read more..

  • Page - 385

    } @end code snippet MacOSXProg ch10/Slide Master 3/SlideShowWindowController.h 7. Open SlideShowDocument.xib in Interface Builder. 8. Connect the First Responder ’ s mSlidesController outlet to the Slides Controller array controller, and save the fi le. 9. In Xcode, open read more..

  • Page - 386

    364 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS [self.document addSlidesAtURLs:openPanel.URLs]; } } - (void)removeSlides:(id)sender { [mSlidesController remove:sender]; } @end code snippet MacOSXProg ch10/Slide Master 3/SlideShowWindowController.m 10. Open SlideShowDocument.h and read more..

  • Page - 387

    12. Save your changes to the SlideShowWindowController and SlideShowDocument fi les . 13. Build and run the Slide Master project. 14. Choose Slide Show ➪ Add Slides. The open panel appears as a sheet on the Slide Show window. You can select one or more image fi les from this panel. When you read more..

  • Page - 388

    366 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS by the call to NSImage ’ s imageFileTypes method. modalForWindow: takes the NSWindow instance to which the open panel will be anchored. SlideShowWindowController uses its own window instance. The last three arguments refer to a callback method that will be read more..

  • Page - 389

    also documents. When you double - click a source fi le in an Xcode project, you ’ re creating a new source fi le document. It doesn ’ t really matter that you didn ’ t use the File ➪ Open command or double - click the fi le in the Finder. In the next Try It Out you will write a File ➪ Import read more..

  • Page - 390

    368 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 11. Add the newFromFolderWithOpenPanel class method at the top of the Document Initialization section: #pragma mark Document Initialization + (SlideShowDocument *)newFromFolderWithOpenPanel { SlideShowDocument *document = nil; NSOpenPanel *openPanel = [NSOpenPanel read more..

  • Page - 391

    { [urls addObject:url]; } [self addSlidesAtURLs:urls]; } code snippet MacOSXProg ch10/Slide Master 4/SlideShowDocument.m 13. Open ApplicationDelegate.m and replace its contents with the following code: #import "ApplicationDelegate.h" #import "SlideShowDocument.h" read more..

  • Page - 392

    370 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS runModalForDirectory:file:types: method. Because newFromFolderWithOpenPanel doesn ’ t need to customize the dialog, it passes nil in as all the arguments to runModalForDirectory:file: types: . When you click the OK button, the newFromFolderWithOpenPanel will make a call read more..

  • Page - 393

    example, you could return all text strings in alphabetical order. Or you could return all song fi les sorted by artist and album name. In the next Try It Out you will sort your Slide Entities by creation date. This will fi x the random reordering problems you see during undo and redo. TRY IT OUT Sorting Core Data Results read more..

  • Page - 394

    372 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 10. Save your changes to Slide.m and SlideShowWindowController.m . 11. Build and run Slide Master. Test adding images using the Add Slides menu and test removing them with Undo. The contents of the table view will remain sorted in the order they were read more..

  • Page - 395

    You can use transient Core Data attributes to solve these problems. A transient attribute is one that doesn ’ t get saved to the persistent object store. They ’ re meant to hold a temporary state that can easily be derived from other attributes. Even though they aren ’ t saved they are still tracked by Core Data, and you can get them read more..

  • Page - 396

    374 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS [self setPrimitiveValue:image forKey:@"image"]; } @end code snippet MacOSXProg ch10/Slide Master 6/Slide.m 7. Open SlideImageView.h and add the instance variable and property shown here: @interface SlideImageView : NSImageView { NSString read more..

  • Page - 397

    [observed setValue:fileURL forKeyPath:mURLKeyPath]; } else { // this isn't what we expected, let super handle it [super concludeDragOperation:sender]; } } } code snippet MacOSXProg ch10/Slide Master 6/SlideImageView.m 9. Open read more..

  • Page - 398

    376 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS How It Works The slideshow document user interface is still bound to the Slide Entity ’ s image property. This means the user interface continues to ask for NSImage objects from Core Data. By making image a transient property you told Core Data to stop archiving this read more..

  • Page - 399

    TRY IT OUT Creating a Preference Window Interface 1. Open Slide Master ’ s MainMenu nib fi le in Interface Builder. 2. Add an orderFrontPreferencePanel: action to the First Responder. 3. Connect your menu bar ’ s Slide Master ➪ Preferences menu item to the First Responder read more..

  • Page - 400

    378 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 12. Back in Interface Builder, change File Owner ’ s Class to PreferencesWindowController in the Identity Inspector. 13. Connect the OK and Cancel buttons to the File ’ s Owner ’ s handleOKCancel: action. If you have trouble seeing the handleOKCancel: read more..

  • Page - 401

    2. Switch to PreferencesWindowController.m and replace its contents as follows: #import "PreferencesWindowController.h" @implementation PreferencesWindowController + (PreferencesWindowController*)sharedInstance { static PreferencesWindowController *sharedInstance = nil; if read more..

  • Page - 402

    380 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS 4. Add the following methods to the ApplicationDelegate implementation: - (void)applicationWillFinishLaunching:(NSNotification *)notification { NSColor *color = [NSColor whiteColor]; NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color]; NSDictionary *defaults = [NSDictionary read more..

  • Page - 403

    @synthesize backgroundColor = mBackgroundColor; - (void)setBackgroundColor:(NSColor *)color { if (mBackgroundColor != color) { [mBackgroundColor release]; mBackgroundColor = [color retain]; [self setNeedsDisplay]; } } - (void)drawRect:(NSRect)rect { NSColor* read more..

  • Page - 404

    382 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS - (void)windowDidLoad { [super windowDidLoad]; NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey: @"creationDate" ascending:YES]; NSArray *descriptors = [NSArray arrayWithObject:descriptor]; [mSlidesController read more..

  • Page - 405

    The shared PreferencesWindowController instance runs its window as a modal dialog box by sending a runModalForWindow: message to an object named NSApp . NSApp is the shared instance of the NSApplication singleton class; NSApp is initialized by AppKit automatically when your program starts. You use the NSApp read more..

  • Page - 406

    384 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS NOTE Remember that color values can ’ t be stored in NSUserDefaults directly as NSColor objects; instead Cocoa Bindings is embedding the NSColor object in an NSData object using NSKeyedArchiver . When you manually read color values from read more..

  • Page - 407

    Neither Core Data nor Cocoa Bindings prevent you from writing your own custom code if you need it. You manually inserted objects into the slideshow document, you pushed automatically generated values into Core Data entities, and you even added a replacement setBackgroundColor: accessor for SlideImageView that requests redraw when the color changes. read more..

  • Page - 408

    386 ❘ CHAPTER 10 CORE DATA-BASED COCOA APPLICATIONS WHAT YOU LEARNED IN THIS CHAPTER Entity a class of objects known to Core Data, conceptually similar to an Objective - C class Attributes properties of an Entity that store discrete pieces of data Relationships entity properties that refer to read more..

  • Page - 409

    PART III Script Programming CHAPTER 11: Overview of Scripting Languages CHAPTER 12: The Bash Shell CHAPTER 13: AppleScript and AppleScriptObjC CHAPTER 14: JavaScript, Dashboard, and Dashcode c11.indd 387 12/12/09 1:37:13 PM read more..

  • Page - 410

    c11.indd 388 12/12/09 1:37:20 PM read more..

  • Page - 411

    11 Overview of Scripting Languages WHAT YOU WILL LEARN IN THIS CHAPTER: What a scripting language is, and how it diff ers from languages such as Java and Objective - C The strengths and weaknesses of the following scripting languages: Bash, AppleScript, Python, Ruby, and JavaScript The basic properties of each of the read more..

  • Page - 412

    390 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES WHAT IS A SCRIPT? In Chapters 6 and 7 you learned about the C and Objective - C programming languages, which form the basis of much of the development taking place on Mac OS X today. These languages are compiled languages , which means they have to be converted from source read more..

  • Page - 413

    PHP is designed for building web sites, with features for accessing databases and producing HTML. JavaScript is designed to work in web browsers and can be used to create Dashboard widgets. Scripting languages are often referred to as glue languages , because they are generally used to glue together other applications and programs. read more..

  • Page - 414

    392 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES from the output of another program. The latter is known as a pipe , because it is similar to running the data down a pipe from one program to the next. A good shell scripter can do some amazing things, such as piping the output of one Unix command to the input of a second, read more..

  • Page - 415

    CreateImage() { echo Creating a volume /usr/bin/hdiutil create -quiet "$DISK_IMAGE_NAME.dmg" -fs HFS+ \ -volname "$VOLUME_NAME" -megabytes $DMG_SIZE } AttachVolume() { echo Attaching volume local TMPFILE=`mktemp -t "hdiutil_output"` /usr/bin/hdiutil attach "$DISK_IMAGE_NAME.dmg" > "$TMPFILE" read more..

  • Page - 416

    394 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES – fs HFS+ , which instructs the command to create an HFS+ fi le system in the disk image. The – megabytes $DMG_SIZE option gives the size of the disk image. The variable DMG_SIZE is used for this purpose. WARNING To access the value of a variable in Bash, you need read more..

  • Page - 417

    The path of the device that is needed is the fi rst one that appears, /dev/disk2 , in the line with Apple_partition_scheme . To extract this path, a number of different commands are chained together. The command used to get the path is enclosed between backticks and amounts to the following: cat "$TMPFILE" | grep 'Apple_partition_scheme' | read more..

  • Page - 418

    396 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES Aside from Chapter 12, the man page for Bash is a good resource for documentation. Open the Terminal utility and enter this command: man bash Use the spacebar to move down the page, and press q to quit the man program. Countless sites on the Internet cover Bash read more..

  • Page - 419

    with languages such as Python and Ruby. This doesn ’ t mean AppleScript has no part to play when you are faced with such tasks, because the best solution may involve some combination of AppleScript for handling applications and another scripting language for processing text and data. TRY IT OUT An AppleScript Example AppleScript and read more..

  • Page - 420

    398 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES How It Works This script begins by setting a variable called email_text to a string that contains the content of all the e - mails to be sent: set email_text to "Hello < name > . How are you?" The string contains a message, with a placeholder used to read more..

  • Page - 421

    (* Create personalized email text *) set name_offset to offset of " < name > " in email_text set end_offset to name_offset + (length of " < name > ") set text_length to length of email_text set email_beginning to get text 1 thru (name_offset - 1) of read more..

  • Page - 422

    400 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES After the new_message variable has been confi gured, the e - mail is sent using the send command of the Mail application. If all goes well, an e - mail should be sent to the e - mail address entered by the user, with the recipient ’ s read more..

  • Page - 423

    To summarize The Zen of Python, Python aims to make things as simple as possible, yet still provide all the power you need. Why Python? Python provides very powerful programming constructions, such as object - orientation (OO), in a very simple syntax. OO features become particularly important as your programs grow in size and read more..

  • Page - 424

    402 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES Mac OS X ships with a few Python packages that are not available on any other platform. First, there are a set of bindings for the CoreGraphics framework. These bindings allow you to access the Quartz graphics layer in your Python scripts. For example, you could use a Python script to read more..

  • Page - 425

    class TagRemovingWordCounter (WordCounter): """ Counts all whitespace separated words, after removing XML tags. """ def __init__(self): self.tagRegEx = re.compile(r'\ < \/?.+?\ > ') def read more..

  • Page - 426

    404 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES root directory path. All files with the extension in the root directory and subdirectories, are processed. The number of words in all the processed files are summed and printed. The number of words excluding XML-like tags are also printed. read more..

  • Page - 427

    Python has many different modules in its library, and many more are available from third parties. To use the functions and classes in a module, you fi rst must import it so that the interpreter knows that it must be loaded. In this case, the modules imported are re , for regular expressions; string , for string handling; sys , read more..

  • Page - 428

    406 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES By now you may have noticed that there are no end class or end def keywords to indicate where a class or method fi nishes. How does the Python interpreter know when one method fi nishes and the next begins? The answer has to do with whitespace. Whitespace, or read more..

  • Page - 429

    The countWords method accepts a string argument. It fi rst calls _reduceString with the string, before splitting the string into a list of words with the string.split function, and returning the length of the list: return len( string.split(str) ) The split function is from the module string , which is read more..

  • Page - 430

    408 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES interpreter will pass it to the compile function exactly as it is written in the program. If a string is not a raw string, python will substitute characters that have special meaning. The _reduceString method of TagRemovingWordCounter uses the regular read more..

  • Page - 431

    built - in file function opens the fi le and returns an object giving access to its contents. The contents are read with the read method before the fi le is closed with the close method. The WordCounter object passed to the function is used to count the words in the string read in, and the variable read more..

  • Page - 432

    410 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES example, you may want to use the WordCounter class in an entirely different setting. You want to import the classes and functions in the example script, but do not want the main program of the word counting script to be executed. The if statement makes this possible, read more..

  • Page - 433

    Why Ruby? Ruby inherits a lot from the granddaddy of scripting languages, Perl. As Perl matures, it gains more and more functionality, but it began as basically the scripting equivalent of C. It did not have any OO features, but did provide functions, and more powerful data containers such as arrays and hashes (dictionaries). String manipulations read more..

  • Page - 434

    412 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES #---------------- # Classes #---------------- class WordCounter # Counts all whitespace separated words in a string. def reduceString(str) # Removes anything that should not be counted. Here it does nothing. str end read more..

  • Page - 435

    def Usage # Return a string with the usage of the script "Usage: wc.rb file_extension root_directory" end #---------------- # Main program #---------------- def Main # The script takes two arguments: a file extension, and a root directory path. # All files with the extension in the root directory and read more..

  • Page - 436

    414 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES def reduceString(str) # Removes anything that should not be counted. Here it does nothing. str end def countWords(str) # Counts all words in a string reduceString(str).split.length end end A Ruby class read more..

  • Page - 437

    In the Python script, a string was used to store a regular expression, and stored in an instance variable. In Ruby, a regular expression object is created directly in code and stored in the instance variable tagRegEx . In Ruby, the @ symbol is prepended to delineate an instance variable, rather than using the self variable. read more..

  • Page - 438

    416 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES In this particular example, a block is being called repeatedly much as if it were code in a for loop. In fact, a for loop was the solution used in the Python script. Ruby uses blocks in contexts where more traditional language constructs would be used in Python. Again, read more..

  • Page - 439

    More Information The Ruby language web site is a good place to begin your exploration of Ruby ( ). It includes links to many other Ruby resources. If you want to start developing a web application with Ruby on Rails, visit the Rails web site fi rst ( ). You can fi nd Ruby modules and libraries read more..

  • Page - 440

    418 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES The reason JavaScript has risen together with the Web is that it is so closely coupled to its other technologies: HTML and CSS. JavaScript gives you direct access to elements of a HTML document, including its CSS stylesheets. You can change these elements and effectively modify the page in time. JavaScript can read more..

  • Page - 441

    < ?xml version="1.0" encoding="UTF-8"? > < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" > "" < html xmlns="" xml:lang="en" > < head > < title > Moving Image < /title > < style type="text/css" > body { width:500px; height:500px; border:solid gray 1px; read more..

  • Page - 442

    420 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES height:500px; border:solid gray 1px; } img#movingimage { position:absolute; top:100px; left:100px; } < /style > The body is sized and given a border; it read more..

  • Page - 443

    The DOM is also used to set the position of the image. The style attribute of any element contains its CSS style information; in this example, the top and left attributes of the style are set, which effectively moves the image on the screen. Note that styles are always strings, so the coordinate numbers must fi read more..

  • Page - 444

    422 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES PHP: A language used mostly to build web sites. It can be mixed with HTML to produce web pages that get dynamically built by the web server whenever requested by a client web browser. PHP allows you to easily integrate a database with your web site, upload fi les via a web read more..

  • Page - 445

    EXERCISES 1. A friend says to you that she is interested in scripting a weekly backup of her user directory. She asks you what you think the best scripting language to use would be. What would you advise, based on what you have learned in this chapter? 2. Another friend wants to build a complex web content read more..

  • Page - 446

    424 ❘ CHAPTER 11 OVERVIEW OF SCRIPTING LANGUAGES WHAT YOU LEARNED IN THIS CHAPTER Script a program that is interpreted line - by - line rather than being compiled into machine code Scripting Language a high - level language used to write scripts Interpreter a program that reads and read more..

  • Page - 447

    12 The Bash Shell WHAT YOU WILL LEARN IN THIS CHAPTER: How to confi gure and use Bash interactively and for running scripts How to use the Terminal application for accessing the command line The most important Unix commands and where to fi nd information about commands Some of the commands that are available only on Mac read more..

  • Page - 448

    426 ❘ CHAPTER 12 THE BASH SHELL The Command - Line Interface The Mac has always had an excellent graphical user interface (GUI) — it ’ s what made the Mac famous to begin with. With Mac OS X, Apple continues to lead the way when it comes to GUI design. The original Mac OS may have had a great GUI, but it lacked a read more..

  • Page - 449

    The Terminal Application The easiest way to access Bash on Mac OS X is to use the Terminal application, which you can fi nd in the /Applications/Utilities folder. Terminal can be used to open windows, each of which contains a prompt that you can use to enter commands. Each Terminal window is running a different copy of the Bash read more..

  • Page - 450

    428 ❘ CHAPTER 12 THE BASH SHELL NOTE If you talk to Unix users about their preference for emacs or vi, you may hit a nerve. The competition between these two editors is something akin to a religious war and can prompt very lively discussions. Instead of discussing vi or emacs, this chapter introduces a very simple command - line editor read more..

  • Page - 451

    COMMAND DESCRIPTION Control - X Exits Nano. If you have unsaved changes, Nano prompts you for whether you would like to save them. Control - K Cuts the selected text, or a single line if there is no selection. You can ’ t make a selection with the mouse; instead, you set the start position of read more..

  • Page - 452

    430 ❘ CHAPTER 12 THE BASH SHELL NOTE In this chapter, the word directory is used interchangeably with folder. These words are testimony to the heritage of Mac OS X, arising out of a marriage between Unix and Mac OS. The word directory is used in the Unix world, and folder was the equivalent term in the original read more..

  • Page - 453

    TRY IT OUT Confi guring Your Bash Shell 1. Start the Terminal application in /Applications/Utilities . 2. Create the fi le .profile in your home directory using the Nano editor. To do this, simply issue the following command at the prompt: nano .profile 3. Type the following text into the read more..

  • Page - 454

    432 ❘ CHAPTER 12 THE BASH SHELL Many users like to add the current working directory, as given by . , to their PATH variable. Adding . to the PATH means that the shell will look for executable programs in the current working directory, as well as at other paths. It is quite common to want to read more..

  • Page - 455

    The exit command allows you to terminate a shell. You can also supply a number to the exit command, which is returned to the parent process as the exit code. This is usually used to indicate if an error occurred and what the error was. UNIX BASICS The Unix philosophy, which Mac OS X shares at its lower levels, can read more..

  • Page - 456

    434 ❘ CHAPTER 12 THE BASH SHELL The period can also be used in paths; the presence of a period effectively leaves the path unchanged. For example, the following command lists the contents of the Desktop folder if issued from inside the user ’ s home directory: ls ./Desktop This is completely equivalent to ls read more..

  • Page - 457

    NOTE If you look for /bin in the Finder, you may be surprised to see that it ’ s missing. It isn ’ t actually missing, it ’ s just hidden. Apple prefers that everyday users not be bothered by low - level details such as /bin , and hides them in Finder. You can still navigate to the /bin directory in read more..

  • Page - 458

    436 ❘ CHAPTER 12 THE BASH SHELL Running Commands and Other Executables By now it should be quite clear that running an executable in a shell is simply a matter of typing its name and supplying any options required. If the command is not in one of the paths in your PATH environment variable, you can run the command by giving read more..

  • Page - 459

    This command searches for text fi les in the current directory and any of its subdirectories. Because this may take a while, it makes sense to run the command in the background so that you can continue issuing commands while the search proceeds. The & at the end of the line indicates to the shell that it should return from the find read more..

  • Page - 460

    438 ❘ CHAPTER 12 THE BASH SHELL The source command is similar to eval , but it executes commands from a fi le. The commands are again executed in the existing shell, with no subprocess initiated. With the exec command, you can replace the shell with another running script or program. The initiating script is read more..

  • Page - 461

    GetFileInfo ... zip zipcloak zipgrep zipinfo zipnote zipsplit zless zmore znew zprint Results differ depending on the commands you have installed in the /usr/bin directory. The output gets piped to the input of the command grep cc , which extracts any line containing the text cc . The original output of the ls command is read more..

  • Page - 462

    440 ❘ CHAPTER 12 THE BASH SHELL A second pipe has been added, taking the output of the grep cc command and piping it into the input of a second grep . The second grep prints only the lines that contain at least one digit. You can also pipe data to and from fi les. To do this, you use the redirection read more..

  • Page - 463

    TRY IT OUT Determining Your Memory by Redirecting Data 1. Open a Terminal window in the Terminal application. 2. Enter the following command: man system_profiler 3. Skim the information provided until you think you understand what the system_profiler command does. You can use the spacebar to move read more..

  • Page - 464

    442 ❘ CHAPTER 12 THE BASH SHELL 7. Exit Nano again by pressing Control - X. 8. Use the grep command to read the sysoutput.tmp fi le, and extract the sizes of the RAM modules, like this: grep -e 'Size: [0-9]' < sysoutput.tmp You should see something similar to the following: Macintosh:~ read more..

  • Page - 465

    14. Enter the following long command to duplicate the result of steps 1 through 12 while avoiding temporary fi les: system_profiler SPMemoryDataType | grep -e 'Size: [0-9]' | awk '{print $2}' | perl -e '$sum=0; while( < > ) { $sum+=$_; } print "$sum\n";' Again, allow the command to be wrapped by Bash; do not type a return until read more..

  • Page - 466

    444 ❘ CHAPTER 12 THE BASH SHELL To affi rm that the current directory did change, you can check the value of the PWD environment variable or use the pwd command, which prints the path of the current working directory as shown here: Macintosh:/Library/Frameworks sample$ echo $PWD /Library/Frameworks Macintosh:/Library/Frameworks sample$ read more..

  • Page - 467

    Navigating a fi le system is also about knowing what you can navigate to. In Finder, you are automatically presented with a list of available fi les and folders whenever you open a folder. In Bash, this is not the case; you have to enter a command to list the contents of a directory. The command in question is ls . If read more..

  • Page - 468

    446 ❘ CHAPTER 12 THE BASH SHELL The preceding example also lists other useful information, such as the fi le owner, which is root for both fi les in this case; the group of the fi le, which is wheel for both fi les; the size of the fi le in bytes, which is 3,346 bytes for access_log and read more..

  • Page - 469

    Other forms of paths are also possible, of course. Here is an example where a fi le is moved from the user ’ s Desktop folder into the Documents folder and renamed at the same time: mv ~/Desktop/project.doc ~/Documents/lastproject.doc The fi le originally called project.doc is not only moved to another directory, but read more..

  • Page - 470

    448 ❘ CHAPTER 12 THE BASH SHELL This copies the directory sourcedir in the Desktop folder, plus all its contents, into a new directory called sourcedir in the Documents folder. If you want to rename the copied directory, you can simply do this: cp -r ~/Desktop/sourcedir ~/Documents/destdir The copy is now called read more..

  • Page - 471

    mkdir only makes a new subdirectory of an existing directory unless you supply the - p option, in which case it also generates any non - existing intermediate directories. So the preceding command could be made to succeed by changing it to this: mkdir -p /Users/demo/Desktop/newdir/otherdir File Permissions All the commands discussed so read more..

  • Page - 472

    450 ❘ CHAPTER 12 THE BASH SHELL The permissions applying to the owner of the fi le are in places 2 – 4, which are r - x in this example. The fi rst of these three characters indicates whether the owner has read permission, allowing the contents of the fi le to be examined or copied, for example. A letter read more..

  • Page - 473

    This changes the owner of the fi le given as the second argument to user terry . The group of the fi le is left unchanged. NOTE root is known as the superuser and can do anything, regardless of permissions. If you are an administrator on your Mac, you can carry out commands as if you are the superuser using the sudo read more..

  • Page - 474

    452 ❘ CHAPTER 12 THE BASH SHELL Globbing If you want to perform a command for several fi les, it can become tedious typing full names and paths. The Bash shell allows you to take some shortcuts, using pattern matching within fi lenames and paths. This is known in the world of shell scripting as globbing . To use read more..

  • Page - 475

    If you want to limit the number of possible characters matched, you can enter the allowed characters in square braces, like this: ls blah[01] This would match blah0 or blah1 , but not blah2 , for example. You can add as many characters between the braces as you like — any of them can match. You can use various read more..

  • Page - 476

    454 ❘ CHAPTER 12 THE BASH SHELL TRY IT OUT Interacting with the File System 1. Open the Terminal window in the Terminal application. 2. Change to the /usr/bin directory and list all commands that contain gnu . Macintosh:~ sample$ cd /usr/bin Macintosh:/usr/bin sample$ ls *gnu* gnuattach read more..

  • Page - 477

    9. List full details of the gnutar command again. Notice how the permissions, owner, and group have changed. Macintosh:~/Desktop/somecommands sample$ ls -l gnutar -rwxr-xr-x 1 demo demo 991552 Sep 10 14:29 gnutar 10. Move down one directory to the Desktop directory and remove the somecommands directory. Answer read more..

  • Page - 478

    456 ❘ CHAPTER 12 THE BASH SHELL Metadata is data about data. It includes information such as a fi le ’ s name, the date it was created, the type of data it contains, and much more. If you want to know what metadata is associated with a particular fi le, you can use the mdls command to fi nd out, read more..

  • Page - 479

    There are also some traditional Unix tools that can help you locate fi les and directories by name. One of the easiest ways to fi nd paths containing a given string is to use the locate command. For example, to fi nd all paths containing the string NSApplication.h , you could issue the following command: read more..

  • Page - 480

    458 ❘ CHAPTER 12 THE BASH SHELL You can also carry out commands on the fi les you locate with find . For this, you use the - exec option, which runs a command that you provide, like this: find . -name rubbish -exec rm {} \; This command fi nds fi les called rubbish in the current working directory or read more..

  • Page - 481

    But you can make your message a bit more fl exible by including variables and other special Bash characters. Consider the following example: Macintosh:~/Desktop sample$ touch Cupertino Macintosh:~/Desktop sample$ GREETING=Hello Macintosh:~/Desktop sample$ echo $GREETING Cuper* ! Hello Cupertino ! The touch command simply updates the timestamp of the fi read more..

  • Page - 482

    460 ❘ CHAPTER 12 THE BASH SHELL grep can also be used with special pattern - matching strings called regular expressions . You can think of regular expressions as being similar to globbing, but do not confuse the two: although the characters used for pattern - matching in globs and regular expressions are often the same, read more..

  • Page - 483

    PATTERN DESCRIPTION EX AMPLE DOES MATCH DOESN ’ T MATCH (...) Used to group characters together. char(xyz)*blah charblah charxyzblah charxyzxyzblah charxblah charxyblah | Allows two diff erent expressions to match. char(x|yz)+blah charxblah charyzblah charxxblah charxyzblah read more..

  • Page - 484

    462 ❘ CHAPTER 12 THE BASH SHELL The resulting text is written to standard output. The fi rst argument to sed , which is enclosed in single quotations, is an editing command; it tells sed what text substitution to make. A substitution command takes the form s/.../.../g , with the regular expression between the fi rst read more..

  • Page - 485

    h2 { color: #778fbd; font-size: 18px; font-family: "Lucida Grande", Arial, sans-serif; font-weight: normal; margin: 0.83em 0 0; } h3 { color: #666; font-size: 60px; font-family: "Lucida Grande", Arial, sans-serif; font-weight: bold; text-align: center; read more..

  • Page - 486

    464 ❘ CHAPTER 12 THE BASH SHELL WARNING Many background processes are daemons . Daemons run continuously, and are often started when the system boots up. They typically listen for requests on a network port and act on them when they are received, perhaps starting up other programs. If you want to see what sort of daemons are running read more..

  • Page - 487

    The sleep command simply pauses for the time you give as an argument, which in this case is 10 seconds. The & has been used to put the command into the background. When you do this, the PID of the subprocess is printed, which is 18700 in this example. When the ps command is issued, the read more..

  • Page - 488

    466 ❘ CHAPTER 12 THE BASH SHELL Macintosh:~ sample$ ps PID TTY TIME CMD 17963 ttys000 0:00.06 -bash The sleep process is set to sleep for 3,600 seconds, or one hour. Instead of waiting for it to exit by itself, the kill command is used with the option - 9 and the PID read more..

  • Page - 489

    COMMAND PURPOSE diskutil Command - line equivalent of the Disk Utility application; can be used to check and repair disks and permissions, and erase and partition disks. hdiutil Creates, mounts, and manipulates disk images. installer The command - line interface to the Installer application; used to install read more..

  • Page - 490

    468 ❘ CHAPTER 12 THE BASH SHELL COMMAND PURPOSE netstat Used to get detailed information about the network that the computer is attached to. nice/renice Used to set or change the priority of a running process so that the kernel allots more or less CPU time to it. sftp Secure version of read more..

  • Page - 491

    #!/bin/bash cd ~/Desktop/ touch blah mkdir blahdir mv blah blahdir The script simply contains the same commands that were entered at the interactive prompt. The only difference is the fi rst line, which is called a shebang . A shebang begins with the characters #! , and ends with a path. It tells the shell that is running the script read more..

  • Page - 492

    470 ❘ CHAPTER 12 THE BASH SHELL Running this script results in the following output: 1 Shell Street 2 Shell Street The ADDRESS variable is initially assigned to the string ‘ 1 Shell Street ’ . The quotation marks are important; without them, the ADDRESS variable would be assigned only to 1 , and the read more..

  • Page - 493

    for indexes 0 , 1 , and 10 . In the echo statement, the value for index 2 is requested. No value has been assigned for index 2 , but it does not result in an error; instead, the value is simply an empty string. Only the values of the other three array entries actually appear in the printed output. When you access the read more..

  • Page - 494

    472 ❘ CHAPTER 12 THE BASH SHELL Apart from the variables that you defi ne yourself, the Bash shell defi nes a number of useful variables. For example, the process identifi er of the shell running the script is given by $$ . You can use this when naming fi les to avoid overwriting output from other runs, as in the read more..

  • Page - 495

    The second mkdir command causes an error, because the directory already exists. The exit code of the successful command is 0 , and that of the unsuccessful operation is 1 , as you can see from the following script output: Exit code of mkdir was 0 mkdir: tempdir5224: File exists Exit code of mkdir was 1 Quoting Several different types read more..

  • Page - 496

    474 ❘ CHAPTER 12 THE BASH SHELL A backslash preceding a character escapes any special meaning that that character has. It applies not only to variables, as demonstrated here, but to any characters that have special meaning to the shell. Another type of quotation mark that is used often in shell programming is the backtick . read more..

  • Page - 497

    This if command may seem confusing at fi rst, because languages such as C and Java behave in an opposite manner: the if block is executed when the condition is non - zero or true , and the else block is executed when the condition is 0 or false . This difference comes about because Bash treats an exit value read more..

  • Page - 498

    476 ❘ CHAPTER 12 THE BASH SHELL The assignment of the variables to various strings at the beginning is fairly straightforward, except for VAR2 . You may be wondering why double quotation marks have been used around the value $VAR1 on the right side of the assignment. If you don ’ t do this, the shell will expand $VAR1 read more..

  • Page - 499

    This can also be written as follows: if [ -e ~/Desktop/tempfi le ] then echo tempfile exists fi The test command takes an option used to determine the type of test to be performed for the fi le given. In this case, the - e indicates that the existence of the fi le is being tested. If the fi read more..

  • Page - 500

    478 ❘ CHAPTER 12 THE BASH SHELL Looping Loops allow you to perform a series of commands repetitively, without having to duplicate them. The while loop continues until the exit status of a command is no longer 0 . For example, here is a while loop that has a fi xed number of iterations: let i=0 while (( $i < read more..

  • Page - 501

    the output is as follows: 1 2 3 4 In this example, the while tests how many input arguments are left, which is given by the shell variable $# . When there are none, the while loop exits. On each iteration, the command shift removes one input parameter — the one in the $1 variable — and read more..

  • Page - 502

    480 ❘ CHAPTER 12 THE BASH SHELL A useful variation on this loop involves leaving out the in part of the loop. When you do this, the for loop iterates over the input arguments, as demonstrated by this script: #!/bin/bash for name do echo $name done Inserting this in a fi le called , and read more..

  • Page - 503

    As with scripts, functions can also take arguments. And arguments in functions are also accessed using the shell variables $1 , $2 , $3 , and so forth. Here is a more general function than ChangeToDesktopAndList : function ChangeToDirAndList() { cd "$1" ls $2 } ChangeToDirAndList ~/Desktop -l read more..

  • Page - 504

    482 ❘ CHAPTER 12 THE BASH SHELL 3. Create a new fi le with Nano called as follows: nano 4. Enter the following script with Nano in the fi le: #!/bin/bash # Check exit status in $?. # If non-zero, print it, along with the message in $1. read more..

  • Page - 505

    8. Check that the fi les larger than 5MB that reside in temp_dir and its subdirectories have been compressed by the gzip command and have the .gz extension. 9. Remove the temp_dir directory when you are ready. rm -r temp_dir How It Works The script begins with a read more..

  • Page - 506

    484 ❘ CHAPTER 12 THE BASH SHELL directory of the search. (Note that double quotes have been used to ensure that any spaces in the directory path are not misinterpreted.) The fi rst option passed to find is – size +5000000c . This means that find should ignore any fi le smaller than 5,000,000 read more..

  • Page - 507

    In the next chapter, you learn how to work with AppleScript and the AppleScriptObjC bridge. AppleScript is quite different from Bash in that it is generally used for scripting applications with a GUI rather than Unix commands. Before proceeding, however, try the exercises that follow to test your understanding of the material covered in this read more..

  • Page - 508

    486 ❘ CHAPTER 12 THE BASH SHELL WHAT YOU LEARNED IN THIS CHAPTER Command - Line Interface (CLI) an interface based on textual commands rather than on - screen graphics Shell a program that interprets textual commands and can launch programs and execute scripts Bash the default shell on Mac read more..

  • Page - 509

    13 AppleScript and AppleScriptObjC WHAT YOU WILL LEARN IN THIS CHAPTER : The diff erent ways you can use AppleScript scripts, and the tools you can use to create them The basics of the AppleScript language How to script applications such as Finder, iPhoto, and QuickTime How to develop complete applications with the AppleScriptObjC read more..

  • Page - 510

    488 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC APPLESCRIPT This section introduces you to the AppleScript language and the many ways it can be utilized. AppleScript scripts have access to the internals of running applications and can issue commands or request data. By extracting data from one application and feeding it into another, you can read more..

  • Page - 511

    3. Click the Compile toolbar button and note the changes in the script. 4. Click the Run toolbar button. A Finder window should appear, displaying the Applications folder. 5. Choose File ➪ Open Dictionary. In the panel that appears, select StandardAdditions.osax in the table and then click the Choose button. read more..

  • Page - 512

    490 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC NOTE AppleScript applications can also be referred to as applets. Scriptable and Recordable Applications Not all applications are scriptable . A scriptable application is one that can be accessed from an AppleScript. Many applications are not scriptable because the developers did not read more..

  • Page - 513

    WARNING The ideas behind OSA are shared by other more recently developed messaging protocols such as SOAP and XML - RPC. The latter are built on top of the eXtensible Markup Language ( XML ) and are used primarily for Web Services. Web Services allow communication between computers via the HTTP protocol, which is the protocol upon read more..

  • Page - 514

    492 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC When you use set , you are actually creating a shallow copy of some data, meaning that the variable you assign shares the data with any other variable assigned to the same data. If you want to make a deep copy, in which the data is actually duplicated before being assigned to read more..

  • Page - 515

    AppleScript ’ s string manipulations are relatively primitive when compared to a language such as Python, but you can perform basic operations. You join strings in AppleScript using the concatenation operator & : set address to "18 Hills Hoist Lane, " & "Berryhappy" The variable address is assigned the string value read more..

  • Page - 516

    494 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC value. Recognizing the differences between properties and elements is important because you need to use them in distinctive ways with AppleScript. Setting entries of a list after it has been created is also possible: set someList to {"one", "two", "three"} set item 2 of someList read more..

  • Page - 517

    This actually creates a new record by combining the old friends_ages record with the literal record containing ages for jack and jill . The newly formed record is then assigned to friends_age . Unlike the list type, a record doesn ’ t have an element called items because the entries in a record read more..

  • Page - 518

    496 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC In the following Try It Out, you build up experience with the data types discussed in this section by storing information about a fi ctional group of friends. TRY IT OUT Working with Data 1. Open AppleScript Editor and enter the following in a script window: read more..

  • Page - 519

    How It Works The script defi nes records for three different individuals. A record can contain any data types; in this case, each record contains a variety: a date , two string s, and a list . It is also perfectly acceptable to embed one record within another. The rest of the exercise centers on accessing the stored read more..

  • Page - 520

    498 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC Here is a simple handler that adds two numbers together and returns the result. A call is made to the handler to add one and one: on addTwoNums(firstNum, secondNum) return firstNum + secondNum end addTwoNums addTwoNums(1, 1) — return value is 2 The read more..

  • Page - 521

    above below from out of against beneath instead of over apart from beside into thru around between of under aside from by on at for onto The of read more..

  • Page - 522

    500 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC For example, arguments with simple types such as real , integer , and string are effectively passed - by - value . If you change the value of a parameter corresponding to a simple - typed argu- ment, the original argument remains unaffected. If you think about read more..

  • Page - 523

    it is special; usually, if you write a handler that has no parameters, you need to include empty parentheses in the defi nition of the handler. Control Statements Control statements relate to the fl ow of execution of a script and include conditional branching and looping, among other things. AppleScript provides the usual constructions for read more..

  • Page - 524

    502 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC Each condition is tested in order, beginning with the condition after if , and proceeding to each else if condition. The block of code following the fi rst condition that evaluates true is executed, and all others are skipped. If no condition is true , the else read more..

  • Page - 525

    set x to 0 repeat while x < 100 set x to x + 1 end repeat display dialog x as string or this: set x to 0 repeat until x = 100 set x to x + 1 end repeat display dialog x as string In each of these examples, the condition supplied read more..

  • Page - 526

    504 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC The fi nal form of repeat allows you to iterate through the items in a list . For example, the following loop sums items: set sum to 0 repeat with x in {10, 9, 8, 7} set sum to sum + x end repeat display dialog read more..

  • Page - 527

    tell blocks can also be nested, with each block targeting a different property. For example, imagine that you wanted to get the path to the fi rst photo in your iPhoto library. Here is how you could do it: tell application "iPhoto" tell photo library album set first_photo to item 1 in photos read more..

  • Page - 528

    506 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC In this case, punctuation is taken into account, and the strings are not equal. If you run the script, a dialog will be displayed to that effect. Exception Handling Most modern languages provide some form of exception handling . Exception handling gives you a mechanism for treating read more..

  • Page - 529

    When you do this, control jumps to the on error command of the enclosing try , even if that try block is at a higher level of the script. For example, if an error is thrown from inside a handler, control can jump out of the handler if that is where the enclosing try block is located. The try block is read more..

  • Page - 530

    508 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC ("" & ¬ stock_symbol) -- Download XML with embedded quote tell application "URL Access Scripting" set read more..

  • Page - 531

    archive_stock_price("IBM") archive_stock_price("MSFT") Code Snippet MacOSXProg ch13/Stocks.scpt 3. Compile the script by clicking the Compile button to make sure it was entered correctly. 4. Run the script by clicking the Run button. You need to be connected to the Internet for the script to work. 5. In read more..

  • Page - 532

    510 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC set download_url to ¬ ("" & ¬ stock_symbol) -- Download XML with embedded quote tell application "URL read more..

  • Page - 533

    First, a path to a fi le is built up. The fi le is in the repository folder and has the same name as the stock symbol. In the try block, the open for access command is used to open the fi le for writing. It returns a fi le reference number, which is used to refer to the fi le in other commands. If read more..

  • Page - 534

    512 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC OPERATOR DESCRIPTION EX AMPLE RESULT () Parentheses. Overrides operator precedence, forcing a diff erent evaluation order. (1 + 1) * 2 4 = , is , is equal to Equality comparison operator. true read more..

  • Page - 535

    OPERATOR DESCRIPTION EX AMPLE RESULT or Logical OR operator. true if either the left or the right boolean expression is true . false only if both expressions are false. 1 > 2 or 1 > 0 true not Logical NOT operator. Has the value false if read more..

  • Page - 536

    514 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC You can also concatenate types that are not the same. In this case, implicit coercion is used to convert the types of the operands such that they can be joined. For example, here are some cases where implicit coercion is needed: 1 & 2 & 3 read more..

  • Page - 537

    The rules for record s are similar. contains can compare only two record s; because no other type can be coerced to a record , you can use the operator only with explicitly created record s. Note that when testing for containment of one record in another, it is suffi cient that all key - value pairs are found read more..

  • Page - 538

    516 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC This example fi rst stores the id of a person from the Address Book application called “ Erik the Viking ” . It then sets the middle name for Erik, using the id to access the person . The expression in parentheses retrieves the person corresponding to read more..

  • Page - 539

    The where keyword causes each track element in the play_list variable to be tested. Whenever the artist property of the track begins with the text Bruce , the track is added to a list , which is returned after all track s have been considered. You can use whose in place of where read more..

  • Page - 540

    518 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC Scripts and Objects You have seen properties and elements used throughout this chapter, but you haven ’ t yet seen how they are created. A property can be created in a script, as in: property greeting:"Good Morning" display dialog greeting -- Displays "Good Morning" set read more..

  • Page - 541

    display dialog "Version: " & my version end displayDetails on run my displayDetails() end run end script This script object has a single property, version , and two handlers, displayDetails and run . run was discussed earlier; it is a read more..

  • Page - 542

    520 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC made to the object inside the handler still apply after the handler has returned. Here is the next part of the example, which is a handler that displays details of an OperatingSystem script object: -- Handler to display an OperatingSystem on displayOperatingSystem(os) os's read more..

  • Page - 543

    Classes This discussion of different types of objects leads nicely into a discussion of classes . A class is a type in AppleScript. Earlier in the chapter, the term data type was frequently used, but the more correct terminology is class. You can use the class property of an object to determine its class: script Classy end read more..

  • Page - 544

    522 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC AppleScript scripts can also be run from shells such as Bash (see Chapter 12). The osascript command, which can be found in the /usr/bin directory, allows you to do this. You can run a script or execute a single command. To run a script fi le, you needn ’ t do more than read more..

  • Page - 545

    "How many photos do you want to include in the slideshow?" ¬ buttons {"OK"} default answer 10 default button 1 set dialog_result to result set number_of_photos to (text returned of dialog_result) as integer if read more..

  • Page - 546

    524 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC display_error_message(msg) end try end run Two different handlers are called to request information from the user. The prompt_for_number_ of_photos _in_show handler requests that the user enter a positive integer representing the number of photos that should be extracted from read more..

  • Page - 547

    The value entered by the user is retrieved using the result keyword, which always holds the value of the last command executed. result has been used in this example to make the code slightly more legible, but it would also be completely acceptable to combine the display dialog and set commands into a single line, read more..

  • Page - 548

    526 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC TRY IT OUT Finishing Off Slideshow Maker 1. Open the Slideshow Maker script in AppleScript Editor and modify the run handler as follows: on run try copy Photo_Archive to photo_arch set photo_arch's archive_folder_name to "Test read more..

  • Page - 549

    end add_photo_to_archive on delete_archive() if archive_folder is not false then delete archive_folder end delete_archive end script on add_photos_from_album given Photo_Archive:the_archive, ¬ album:the_album, number_of_photos:number_of_photos tell read more..

  • Page - 550

    528 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC How It Works This script is by the far the most involved you have seen up to this point in the chapter. You may want to read through it several times to better understand how it works. After the user has been prompted for the number of photos in the slideshow and an iPhoto read more..

  • Page - 551

    The original_photo_paths property is a list used to store the paths of the photos in the archive before they were copied. This is used to avoid copying the same photo more than once into the archive. The archive_folder_name was set in the run handler and is simply a name for the folder used to store the photos. read more..

  • Page - 552

    530 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC The add_photo_to_archive handler has one parameter, which is an object of the class photo from the application iPhoto. The fi rst line of add_photo_to_archive requests iPhoto to get the path to the photo . An if block checks if this photo path has already read more..

  • Page - 553

    to the archive. The result of the add_photo_to_archive handler is checked after each call; if it is true , indicating the photo was successfully added to the archive, the counter is incremented. The last handler in the script uses QuickTime Player 7 to open the photos in the archive folder as an image sequence: on read more..

  • Page - 554

    532 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC In the next section, you learn about the facilities in Xcode and Interface Builder for writing AppleScript applications, as well as how to use the AppleScriptObjC bridge. Several Try It Out examples demonstrate how to write complete applications with AppleScript and take advantage of its greatest read more..

  • Page - 555

    Objective - C classes are directly accessible in AppleScript and have the same name when used in AppleScript as they do in Objective - C. An AppleScript script can even inherit from an Objective - C class: script Converter property parent : class "NSObject" ... end script In this example, by setting the parent read more..

  • Page - 556

    534 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC If you choose to create a standard application, and follow the instructions, you end up with an AppleScriptObjC project. This project initially includes a number of fi les that form the basis of any AppleScriptObjC application. Some of these fi les are summarized in the following read more..

  • Page - 557

    with a self - contained application bundle in your build directory that can be run either from inside Xcode, or by double - clicking it in the Finder. Unfortunately, when you are working on an AppleScript fi le in Xcode and do a complete build, the error messages you get are not very useful. One way to get better errors is to run the read more..

  • Page - 558

    536 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC With AppleScriptObjC, you set up your interface in exactly the same way an Objective - C programmer does, connecting outlets and selecting actions for targets in Interface Builder. The same skills you learned in Chapter 4 for Objective - C can be used when building AppleScript applications. An read more..

  • Page - 559

    TRY IT OUT Creating the Piles of Pictures User Interface 1. Start up Xcode and choose File ➪ New Project. When presented with the New Project panel, select Application from the Mac OS X section in the source list on the left, then select Cocoa - AppleScript Application from the top pane on the right. Make sure read more..

  • Page - 560

    538 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC 5. Drag an NSBox to the left of the window and resize it to fi t. Set the Title Pos. option of the box in the Inspector to None, so that the title is not displayed. Drag an NSTableView , and position it as shown inside the box. Select the read more..

  • Page - 561

    the Size pop - up button. In the Attributes tab, which is on the far left, enter 0.0 and 1.0 for the Minimum and Maximum values, respectively. Drag a Label from the Cocoa palette in the Library into the box next to the slider and edit it to read Photo Scaling: . 10. Prepare to adjust the Window settings by selecting it in read more..

  • Page - 562

    540 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC How It Works Most of this assignment simply involves laying out a user interface with Interface Builder and should not be particularly new to you. If you have read Chapter 4, which covers Interface Builder in detail, you should not fi nd any of this too challenging. What you probably read more..

  • Page - 563

    property posterImage : missing value -- Launching on applicationDidFinishLaunching_(notification) my setControlDefaults() my setupTable() end applicationDidFinishLaunching_ on setControlDefaults() widthFormCell's setIntegerValue_(1704) read more..

  • Page - 564

    542 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC repeat with row from 0 to numberOfAlbums - 1 if albumTableView's isRowSelected_(row) then set selectedAlbumName to item (row + 1) in albumNames tell application "iPhoto" to get album selectedAlbumName read more..

  • Page - 565

    -- Destination rect in poster image set s to {|width|:scaledWidth, height:scaledHeight} set o to {x:originX, y:originY} set destRect to {|size|:s, origin:o} -- Source rect of current image set srcRect to {|size|:{|width| of imgSize as number, ¬ read more..

  • Page - 566

    544 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC iPhoto, draw them on a new image taking full advantage of Cocoa and Quartz, and export the resulting image to a fi le. The script begins by declaring some properties: property NSSavePanel : class "NSSavePanel" property NSImage : class "NSImage" property NSFileHandlingPanelOKButton : 1 property read more..

  • Page - 567

    heightFormCell's setIntegerValue_(2304) numberOfPhotosFormCell's setIntegerValue_(50) end setControlDefaults on setupTable() tell application "iPhoto" to set my albumNames to name of albums tell albumTableView to reloadData() end setupTable read more..

  • Page - 568

    546 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC imageData's writeToURL_atomically_(|url|, false) end savePoster_ This handler gets a save panel by calling the NSSavePanel class method savePanel , and sets it up to create TIFF fi les. The runModal method puts the panel on - screen. After the read more..

  • Page - 569

    made, allowing the main thread to continue executing. After the delay has past, the method passed in via the selector argument is invoked. If the second argument is non - nil , it is passed to the method. The performSelector:withObject:afterDelay: method is very common in Objective - C programs. It allows tasks to be postponed for read more..

  • Page - 570

    548 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC set originX to (random number from -scaledWidth to ¬ (|width| of posterSize as number)) set originY to (random number from -scaledHeight to ¬ (height of posterSize as number)) read more..

  • Page - 571

    end if end repeat return theAlbums end getSelectedAlbums A repeat loop iterates over the rows in the table, and a call to the table view ’ s isRowSelected_ method is used to determine whether the corresponding album should be included. If an album name has been read more..

  • Page - 572

    550 ❘ CHAPTER 13 APPLESCRIPT AND APPLESCRIPTOBJC EXERCISES 1. Modify the script you completed in the fi fth Try It Out example, “ Finishing Off Slideshow Maker, ” so that the user is prompted for the duration of each slide. Make sure you handle invalid user input appropriately. 2. The Piles read more..

  • Page - 573

    WHAT YOU LEARNED IN THIS CHAPTER AppleScript AppleScript is an English - like language that appeals to non - programmers and is designed for scripting graphical Mac OS X applications. AppleScript Editor AppleScript Editor is a tool located in /Applications/Utilities that can be used to edit and run AppleScript scripts. read more..

  • Page - 574

    CH013.indd 552 12/12/09 1:50:48 PM read more..

  • Page - 575

    14 JavaScript, Dashboard, and Dashcode WHAT YOU WILL LEARN IN THIS CHAPTER: The basics of the JavaScript scripting language How to write Dashboard widgets with JavaScript, Cascading Style Sheets (CSS), and HTML How to use WebKit CSS Animations to make visually stunning web pages and widgets How to develop a web client read more..

  • Page - 576

    554 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE The last few years, Apple has also started to embrace JavaScript. The WebKit framework, which is the basis of the Safari web browser, but also Dashboard and the iTunes Music Store are leading the way in terms of JavaScript runtime performance. Apple has also introduced Dashcode, a tool that read more..

  • Page - 577

    This imports the fi le CoolEffects.js and executes the JavaScript in it. The script tag usually appears in the head section of an HTML fi le, but this is not a requirement. The script tag is also used if you want to embed a short JavaScript script directly into an HTML fi le: < html > read more..

  • Page - 578

    556 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE Another very common collection is one that stores key - value pairs. In Objective - C this is called a dictionary, and in AppleScript it is a record. Whatever the term, most languages have such a collection type, but not JavaScript . . . at least not an obvious one. JavaScript read more..

  • Page - 579

    This example shows two different types of for loops: the traditional C variety that ranges over integers, and a second type that ranges over the contents of an array. The fi rst loop fi lls the array with integer values, and the second one displays alerts with the value of each element in the array. The if statement read more..

  • Page - 580

    558 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE NOTE JavaScript ’ s functions are actually very similar to blocks in the C language, which you can read about in Chapter 6. That pretty much covers the basics of the JavaScript language. It is small, yet fl exible. But that is not the whole story, because one of the read more..

  • Page - 581

    function updateText( obj ) { obj.innerHTML = "Yes, this is text. I concur."; } < /script > < /head > < span id="fi rstpara" > This is some text. < /span > < br / > < span style="color:white; background-color:gray;" onclick="updateText( document.getElementById('fi read more..

  • Page - 582

    560 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE Before fi nishing this short section on JavaScript, it is worth mentioning a very powerful tool for working with the language: Safari. Apple ’ s browser has hidden features targeted at web site and widget developers. To turn on these features, open the Safari preference pane, and read more..

  • Page - 583

    A widget bundle must include a number of different fi les, including the following: A main HTML fi le A PNG fi le for the widget bar icon A PNG fi le for the default image of the widget, which is displayed during loading An Info.plist property list fi le that includes metadata that describes various aspects of read more..

  • Page - 584

    562 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE if (window.widget) { widget.onshow = onshow; widget.onhide = onhide; } // Called when widget is loaded function setup() { setBallPosition(); } // Called when dashboard is shown function onshow() { } read more..

  • Page - 585

    < script type='text/javascript' src='DashBall.js' charset='utf-8' > < /script > < /head > < body onload='setup();' > < img src='Default.png' / > < img id='ball' src='TennisBall.png' / > < /body > < /html > code snippet read more..

  • Page - 586

    564 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE 5. Use a drawing or painting program to create the graphics fi les for DashBall, and save them in the DashBall folder. All fi les should be in PNG format. Use Figure 14 - 1 as a reference for how the graphics should look. The following table gives details of each read more..

  • Page - 587

    Here is a table describing the entries in the Info.plist fi le of DashBall: DICTIONARY KEY TYPE DESCRIPTION AllowMultipleInstances Boolean Whether or not a user is allowed to create more than one instance of the widget on - screen. For DashBall, this is allowed. CFBundleIdentifier read more..

  • Page - 588

    566 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE The fi rst block indicates that the body of the widget ’ s HTML page should have a margin with a width of 0 . The second block refers to the image representing the tennis ball. The position property is set to absolute , which means the ball ’ s position can be read more..

  • Page - 589

    widget.onhide = onhide; } widget is created by Dashboard and can be used to interact with Dashboard and the rest of the operating system. For example, you can use widget ’ s system method to run shell commands and other programs. The preceding code uses an if statement to check whether the widget read more..

  • Page - 590

    568 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE page, is passed a string identifi er for the object sought. The identifi er itself is set in the HTML fi le using the id property; in DashBall, the id property of the img tag corresponding to the ball ’ s image was set to ball . The read more..

  • Page - 591 = setInterval("updateBall()", theTimer.step); } // Called when dashboard is shown function onshow() { if ( ! ) = setInterval("updateBall()", theTimer.step); } // Called when dashboard is hidden function onhide() { clearInterval(; read more..

  • Page - 592

    570 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE ballCoordsAtHit.x = ball.x; ballCoordsAtHit.y = ball.y; } function finishHit() { if ( hitting ) { ball.velocityX += 2 * (event.x - hitCoords.x - (ball.x - ballCoordsAtHit.x)); ball.velocityY += 2 * read more..

  • Page - 593

    opacity: 0; -webkit-transform: scale(2); } } .powtext { font: 26px "Lucida Grande"; font-weight: bold; color: white; position: absolute; opacity:0; -webkit-animation-duration: 0.5s; -webkit-animation-timing-function: ease-in; } code snippet MacOSXProg read more..

  • Page - 594

    572 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE .powtext { font: 26px "Lucida Grande"; font-weight: bold; color: white; position: absolute; opacity:0; -webkit-animation-duration: 0.5s; -webkit-animation-timing-function: ease-in; } This CSS code sets a number of attributes of the text, including its read more..

  • Page - 595

    100% { opacity: 0; -webkit-transform: scale(2); } } To trigger the animations and react to the user hitting the ball, two attributes were added to the existing img element used to represent the ball ’ s image in the DashBall.html fi le: < img id='ball' src='TennisBall.png' read more..

  • Page - 596

    574 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE (ball.y - ballCoordsAtHit.y)); } var pow = document.getElementById("pow"); = ball.y; = ball.x; = '1.0'; = 'spinin'; if ( powTimerId ) clearTimeout(powTimerId); read more..

  • Page - 597

    The return value of the function is an identifi er for the timer. It gets stored in the powTimerId variable. The identifi er can be passed to the clearTimeout function to cancel the timer; an example of this can also be found in finishHit , where any previously created timer that has yet to fi re is cancelled before a new read more..

  • Page - 598

    576 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE Hopefully, the DashBall example has shown you that: JavaScript is a language with a Java - like syntax. JavaScript is closely coupled to HTML and CSS via the document object model (DOM). Dashboard widgets are not much more than dynamic web pages. Dashboard widgets are read more..

  • Page - 599

    Dashcode is actually a bit more than just a development environment, because it includes an entire JavaScript framework that adds standard widgets such as buttons and list views to your toolkit. The Dashcode JavaScript framework is built in an object - oriented manner, much as the Cocoa frameworks (see Chapter 8), and can be extended in read more..

  • Page - 600

    578 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE TRY IT OUT Laying Out the Flick It! Interface 1. Launch Dashcode from the /Developer/Applications folder. In the project template sheet that appears, select Safari on the left, and the Browser application type on the right. Look for the label Develop for and read more..

  • Page - 601

    6. Select the fi rst row of the list on the left. To do this, you have to click it somewhere outside the Title fi eld. In the Inspector, choose the Metrics tab (third) and set the Height to 60px. 7. Now select the Title text fi eld in the fi rst row of the list on the left of the canvas. In the read more..

  • Page - 602

    580 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE 9. Return to the canvas and resize the fi rst Title text fi eld by dragging the resizing handle on the left in the middle toward the right. Also drag the fi eld downward so that it is centered. 10. In the Library panel, select the Parts tab and read more..

  • Page - 603

    15. Drag an Image part from the Parts section of the Library panel into the bottom pane on the right of the canvas. Open the Metrics tab in the Inspector, and choose Absolute from the Layout pop - up button. Set the struts and springs in the Autoresize section as shown in Figure 14 - 12. This allows the image to resize read more..

  • Page - 604

    582 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE How It Works This Try It Out has been largely an exercise in laying out a user interface. If you have any experience with Interface Builder, it will probably seem very familiar. It is quite repetitive when you understand how the interface tools work. The Browser template was used read more..

  • Page - 605

    When clicked, the More button is intended to take you to the page that corresponds to the photo shown. Most of the attributes you changed should be self - explanatory. Size of text, alignment, and color need no explanation. But the Metrics tab of the Inspector may need some clarifi cation, particularly if you have never used read more..

  • Page - 606

    584 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE FIGURE 14-14 4. Locate the media:thumbnail section of the data source outline and open it. Using the same technique as in step 3, drag from the url to the thumbnail image to the left of the Title fi eld in the fi rst row of the list. Choose read more..

  • Page - 607

    8. Scroll to the bottom of the data source outline. Drag from hasSelection to the main image, and choose visible from the menu. Repeat this for the Photographer text fi eld. Finally, drag again, this time from hasSelection to the More button, but choose enabled rather than visible from read more..

  • Page - 608

    586 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE function openPhotoPage(event) { var dataSource = dashcode.getDataSource("itemsList"); var link = dataSource.valueForKeyPath("");; } 12. Save the project and click the Run toolbar item to test it. Notice how the elements in the detail read more..

  • Page - 609

    Sometimes the data you are binding to is not quite in the right form. A good example of this would be a control that should be displayed when there is no selection. You can ’ t just bind to the hasSelection node, because that will cause the control to be visible when there is a selection. Dashcode offers value transformers to read more..

  • Page - 610

    588 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE var dataSource = dashcode.getDataSource("itemsList"); var link = dataSource.valueForKeyPath("");; } This code shows you how you can access a data source object from JavaScript. The getDataSource method of the global dashcode read more..

  • Page - 611

    One thing that is easy to forget when creating Dashcode applications is that they can only work with data from your own web domain. In that sense, the previous Flickr example is just a nice exercise — only Flickr could actually deploy the app on the Web, because only Flickr has access to the domain. You can only read more..

  • Page - 612

    590 ❘ CHAPTER 14 JAVASCRIPT, DASHBOARD, AND DASHCODE WHAT YOU LEARNED IN THIS CHAPTER HTML Hypertext markup language, a format used to structure web pages JavaScript A scripting language designed to run in a web browser, which can be used to make web pages dynamic CSS Cascading style sheets, a standard read more..

  • Page - 613

    Answers to Exercises CHAPTER 1 Exercise 1 Solution The fi rst two apropos commands return far too much information to be useful. The third command, apropos “ copy file ” returns a reasonable amount of information. Macintosh:~ sample$ apropos "copy file" CpMac(1), /usr/bin/CpMac(1) - copy files preserving metadata and forks File::Copy(3pm) read more..

  • Page - 614

    592 ❘ APPENDIX A ANSWERS TO EXERCISES 2. Choose the Time Profi ler template. Instruments confi gures your document with the Time Profi ler instrument. 3. Click the Record button in the toolbar. This brings up an open panel where you can specify which program you want to start along with other options. 4. read more..

  • Page - 615

    Answers to Exercises ❘ 593 Exercise 2 Solution You can use man - a intro to list all the intro man pages. To get a complete list of all the sections, you could simply make note of the sections yourself as they appear in the pages. You could also use man - k intro to list all the man pages that read more..

  • Page - 616

    594 ❘ APPENDIX A ANSWERS TO EXERCISES FUNCTION MAN PAGE printf “ 3 printf ” scanf “ scanf ” or “ 3 scanf ” pow “ pow ” or “ 3 pow ” Exercise 2 Solution 1. Change the instances of int in Calculate.h to double . This read more..

  • Page - 617

    Answers to Exercises ❘ 595 2. Add the following case entries to the switch statement. Here is the fi nal switch statement: case '/': result = a / b; break; case '\\': result = (int)a / (int)b; read more..

  • Page - 618

    596 ❘ APPENDIX A ANSWERS TO EXERCISES CHAPTER 4 Exercise 1 Solution 1. Change all the labels so that they are pinned to the upper - left corner. The Autosizing control should look similar to the one shown in Figure A - 2. 2. Change all the text fi elds so that they are pinned to the upper edge of read more..

  • Page - 619

    Answers to Exercises ❘ 597 7. Use the guides to position the label a comfortable distance from the upper - left edge of the Tab view. Hold down the Option key and move the mouse over the Tab view to verify the label ’ s position. The top and left edges should be 20 pixels from the left edge of the Tab view, and 30 read more..

  • Page - 620

    598 ❘ APPENDIX A ANSWERS TO EXERCISES 24. Resize the window horizontally so there are only 20 pixels between the Tab view and the window edge. Leave plenty of space below the Tab view to add buttons. 25. Drag a Push button from the Library to your window and use the guides to position it below and to the right of the read more..

  • Page - 621

    Answers to Exercises ❘ 599 the project.pbxproj < username > . < username > .mode1v3 e. The current bundle version of the AppKit framework has been C throughout the Mac OS X releases to date. Note that the version is a single English letter. Exercise 2 Solution a. defaults domains b. defaults - read more..

  • Page - 622

    600 ❘ APPENDIX A ANSWERS TO EXERCISES const char *inpPath = argv[fi leIndex]; // Open fi le FILE *inpFile; inpFile = fopen(inpPath, “r”); // Loop over lines in the input fi le, until there // are none left read more..

  • Page - 623

    Answers to Exercises ❘ 601 if ( strcmp( person- > name, name ) == 0 ) { // Found Person, so delete DeallocPerson(person); // Reduce number of persons in address book. // Also move the last person to the read more..

  • Page - 624

    602 ❘ APPENDIX A ANSWERS TO EXERCISES ProcessSaveRequest(controller); break; case 'q': ProcessSaveRequest(controller); shouldStop = 1; break; default: printf("You entered an invalid read more..

  • Page - 625

    Answers to Exercises ❘ 603 [NSDictionary dictionaryWithObjectsAndKeys: @"CD", @"Type", [NSNumber numberWithInt:3], @"LengthInMinutes", @"Lounge Room", read more..

  • Page - 626

    604 ❘ APPENDIX A ANSWERS TO EXERCISES The writeToFile:atomically: method can be used to write Foundation classes such as NSArray , NSDictionary , and NSString to a fi le in property list format. The property list format is a structured XML format, as you would see if you opened the fi le in a text editor. read more..

  • Page - 627

    Answers to Exercises ❘ 605 [NSString stringWithFormat:@"Address for %@ was removed", name]); } @end 5. While in the Commands.m fi le, modify the initialize method of the Command class as highlighted here: +(void)initialize { commandClasses = [[NSArray read more..

  • Page - 628

    606 ❘ APPENDIX A ANSWERS TO EXERCISES 3. Build the interface shown in Figure A - 6. You can fi nd the Color Well control in Interface Builder ’ s Library. 4. In Xcode, create fi les for an Objective - C class named Color . 5. In Interface Builder, drag an Object item from the Library read more..

  • Page - 629

    Answers to Exercises ❘ 607 @"blue", nil]; keyPaths = [keyPaths setByAddingObjectsFromSet:dependentKeys]; } return keyPaths; } read more..

  • Page - 630

    608 ❘ APPENDIX A ANSWERS TO EXERCISES 3. Replace the “ Your document contents here ” label with a text view from the Library. 4. Resize the text view to fi ll the window, and make the view resizable using the Size Inspector. 5. Click near the top of the scroll view area to select read more..

  • Page - 631

    Answers to Exercises ❘ 609 } - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **) outError { NSString *string = [[NSString alloc] initWithData:data encoding: NSMacOSRomanStringEncoding]; self.stringValue = string; [string release]; return YES; } read more..

  • Page - 632

    610 ❘ APPENDIX A ANSWERS TO EXERCISES CHAPTER 10 Exercise 1 Solution 1. In Xcode, add the following instance variable to SlideShowWindowController.h : IBOutlet NSTableView *mTableView; 2. Switch to SlideShowWindowController.m and add a tableDoubleClick: method declaration to SlideShowWindowController ’ s read more..

  • Page - 633

    Answers to Exercises ❘ 611 the NSDocumentController to open a fi le at a specifi c path or URL. If the application is capable of displaying the fi le, NSDocumentController creates a document for that fi le and, if necessary, displays its window on - screen. 5. Save your changes to SlideShowWindowController.m read more..

  • Page - 634

    612 ❘ APPENDIX A ANSWERS TO EXERCISES 3. Synthesize the fi leName accessor like this: @synthesize URLKeyPath = mURLKeyPath; @synthesize fi leName = mFileName; 4. Add code in drawRect: to draw the fi lename in the lower - right corner of the screen, as shown in the following: - (void)drawRect:(NSRect)rect { read more..

  • Page - 635

    Answers to Exercises ❘ 613 // remove backgroundColor observer [userDefaults removeObserver:self forKeyPath:@"backgroundColor"]; [mSlidesController removeObserver:self forKeyPath:@"selectedObjects"]; [super dealloc]; } 7. Change observeValueForKeyPath:ofObject:change:context: to handle selection changes as read more..

  • Page - 636

    614 ❘ APPENDIX A ANSWERS TO EXERCISES 4. Open Slide.h and add an imageBookmark property beside the imageURL property as follows: @property (nonatomic, retain) id imageURL; @property (nonatomic, retain) id imageBookmark; 5. Switch to Slide.m and change the Slide implementation to the following code: read more..

  • Page - 637

    Answers to Exercises ❘ 615 6. Save your changes and then build and run Slide Master. You can still create and save docu- ments just as before. Now if you move or rename your source images, Slide Master keeps track of them. CHAPTER 11 Exercise 1 Solution Backing up fi les and directories is easily achieved using a standard read more..

  • Page - 638

    616 ❘ APPENDIX A ANSWERS TO EXERCISES 4. Issue the following find command to locate fi les with the extension txt that reside in your home directory or a subdirectory thereof. The command copies each fi le found to the backup directory. fi nd ~ -name *.txt -exec cp {} ~/Desktop/TextFilesBackup \; The globbing read more..

  • Page - 639

    Answers to Exercises ❘ 617 # Confi guration variables FILE_EXT=txt BACKUP_DIR=~/Backups # Create backup directory if necessary if [ -e "$BACKUP_DIR" ]; then # Make sure the backup directory is actually a directory if [ ! -d "$BACKUP_DIR" ]; then StopWithError read more..

  • Page - 640

    618 ❘ APPENDIX A ANSWERS TO EXERCISES WARNING This script takes no account of multiple fi les with the same name. If more than one fi le shares a name, only one of the fi les will appear in the archive; the others will be overwritten. You need to improve the script if you want to archive multiple fi les with the same name. read more..

  • Page - 641

    Answers to Exercises ❘ 619 create_image_sequence_from_folder(photo_arch's archive_folder, ¬ slide_duration) tell photo_arch to delete_archive() on error msg display_error_message(msg) end try end run Exercise 2 Solution Begin by adding a try block to the read more..

  • Page - 642

    620 ❘ APPENDIX A ANSWERS TO EXERCISES property NSFileHandlingPanelOKButton : 1 property NSCompositeSourceOver : 2 property NSWarningAlertStyle : 0 In the getSelectedAlbums handler, add a check to ensure that at least one album has been selected. on getSelectedAlbums() set theAlbums to {} set numberOfAlbums to length of my albumNames read more..

  • Page - 643

    Answers to Exercises ❘ 621 The new code uses a repeat loop to iterate over the albums passed in. The number of photos in each album is retrieved using the count command, and if it is non - zero, the atLeastOnePhoto variable is set to true and the loop exits. If the atLeastOnePhoto read more..

  • Page - 644

    622 ❘ APPENDIX A ANSWERS TO EXERCISES The random number is added to the scalingFactor variable. Because this could potentially result in a scaling factor greater than 1 or less than 0, two if statements check the value of scalingFactor and adjust it if necessary, so that it ends up in the range 0.0 to 1.0. To read more..

  • Page - 645

    Answers to Exercises ❘ 623 body { margin: 0; } img.ball { position: absolute; } 2. In the DashBall.html fi le, make these changes: <html> <head> <style type=”text/css”> @import “DashBall.css”; </style> <script type=’text/javascript’ src=’DashBall.js’ read more..

  • Page - 646

    624 ❘ APPENDIX A ANSWERS TO EXERCISES radius:13.0, imageId:”ball1” }; // Physics var frictionFactor = 0.9; var elasticityFactor = 0.95; // Timers var theTimer = {step:100}; var powTimerId = 0; var splatTimerId = 0; // Variables for hitting var hitting = false; var hitCoords = new Object(); var ballCoordsAtHit = new Object(); if (window.widget) { read more..

  • Page - 647

    Answers to Exercises ❘ 625 function dot(vector1, vector2) { return vector1.x*vector2.x + vector1.y*vector2.y; } function unitVector(vector) { var length = distanceBetweenPoints({x:0,y:0}, vector); return {x:vector.x/length, y:vector.y/length}; } // Ball functions function setBallPosition(ball) { var ballImage = document.getElementById(ball.imageId); read more..

  • Page - 648

    626 ❘ APPENDIX A ANSWERS TO EXERCISES balls[j].velocityY += adjustment.y; // Move balls apart so that they are not overlapping var overlap = balls[i].radius + balls[j].radius - separation; balls[i].x read more..

  • Page - 649

    Answers to Exercises ❘ 627 function finishHit(ballIndex) { var ball = balls[ballIndex]; if ( hitting ) { ball.velocityX += 2 * (event.x - hitCoords.x - (ball.x - ballCoordsAtHit.x)); ball.velocityY += 2 * (event.y - hitCoords.y - (ball.y - read more..

  • Page - 650

    628 ❘ APPENDIX A ANSWERS TO EXERCISES Exercise 2 Solution 1. Launch Dashcode. In the project template sheet, select Safari on the left and the Browser application type on the right. Uncheck the Mobile Safari option next to the Develop For label. Click the Choose button. 2. Choose Save from the File menu, and save read more..

  • Page - 651

    Answers to Exercises ❘ 629 6. Open the Customize data section of the Workfl ow Steps pane, and click the Data Sources button. Select dataSource in the Data Sources list that appears. 7. Enter the URL http://stackoverfl in the URL fi eld at the bottom on the right, and press Return. read more..

  • Page - 652

    bapp01.indd 630 12/12/09 2:04:02 PM read more..

  • Page - 653

    Developer Resources A number of useful developer resources are available to Mac OS X programmers. These include web sites, mailing lists, and other resources. This appendix provides information about these resources. WEB SITES Apple Developer Connection ( You can fi nd a wealth of Mac OS X programming information at Apple Developer read more..

  • Page - 654

    632 ❘ APPENDIX B DEVELOPER RESOURCES MacTech ( MacTech provides a ton of information aimed at the Mac OS X programmer, including Macintosh news, development articles and tutorials, and sample code. You will fi nd a wide variety of programming content on MacTech, including information for both Carbon and Cocoa programmers. The Omni read more..

  • Page - 655

    633 INDEX Symbols !=, 476 $ Bash, 394 PATH, 430 $$, 472 $?, 472, 475 $@, 472 %@, 268 &, 15 7 AppleScript, 493 strings, 399 variables, 185 *, 460 <, 4 62 AppleScript, 511 dereferencing, 158 Desktop, 452 pointers, 157 */, 156 +, 460 AppleScript, 511 JavaScript, 556 / AppleScript, 511 fi nd, 437 /*, 156 <, 4 14, 440 *, 462 AppleScript, 512 cat, 459 ==, 476 read more..

  • Page - 656

    634 add:, 356 addObserver:forKeyPath: options:context:, 384 address-of operator, 157 addWindowController:, 325 ADT (Abstract Data Type), 210, 268 Ajax (Asynchronous JavaScript and XML), 417 album, 525 alert windows, 103 alloc, 244 Alloc..., 210 allocation, 253 AllowMultipleInstances, 565 American National Standards Institute (ANSI), 146 ancestors, 244 and, AppleScript, 512 animation, read more..

  • Page - 657

    635 autoreleasing, 26 Autoresize, 583 Autosizing, 111, 112, 596 availableData, 269 awakeFromInsert, 372 awk, 407, 461 B background commands, 436–437 processes, 463–464 backgroundColor, 559 backtick, 474 backtrace, 25 ~/Backups, 617 Bash, 390–396 $, 394 ~, 430 conditional branching, 474 confi guration, 429–433 directories, 446–449 ditto, 615 fi le system, 443–446 read more..

  • Page - 658

    636 CFBundleExecutable, 120 CFBundleGet InfoString, 121 CFBundle IconFile, 121 CFBundle Identifi er, 141, 565 CFBundleName, 121 CFBundlePackageType, 121 CFBundleShort VersionString, 565 CFBundleSignature, 121 CFBundleVersion, 121 chaining, 245 ChangeToDesktop AndList, 480–481 char, 180 char*, 180, 232 stringWithCString: encoding, 240 characters, C, 179–184 chat room, CocoaDev, 632 CheckExitStatus, 483 child read more..

  • Page - 659

    637 conceptual documentation, 40–43 conditional branching, 501–502 Bash, 474 C, 163–168 if, 474, 557 JavaScript, 557 confi gurePersistentStore CoordinatorForURL: ofType: modelConfi guration: storeOptions:error:, 361 Connections Inspector, 297 considering, 505 const, 167 const char *, 91 constructors. See initializers contains, 514–515 Content, 122 Contents, 120 contiguous memory, read more..

  • Page - 660

    638 descendents, 244 description, 268–269 NSString, 239 descriptionWith CalendarFormat: timeZone:locale:, 87 designed initializer, 254–255 Desktop, 444 *, 452 cd, 454 gnu, 455 ls, 474 sourcedir, 448 destdir, 448 destination path, 446 DetachVolume, 395 Developer Documentation, 39–40 Developer Technical Support, 50 developer tools, 23–51 ADC, 46–50 documentation, 39–46 mailing read more..

  • Page - 661

    639 fclose, 188 fence-post bugs, 171 fgetc, 189 fgets, 189, 192 fi , 474 FILE, 188, 240 fi le, 409 fi le(s) Bash, 446–449 Xcode, 58–63 fi le descriptor, 440 File menu, 102 fi le mode, 445 fi le path, 7 fi le permissions, 449–451 fi le system, Bash, 443–446 fi leExistsAtPath:, 274 fi leExt, 415 fi leHandleWith StandardInput, read more..

  • Page - 662

    640 Groups & Fi les, 62 GUI. See graphical user interface gunzip, 467 gutter, 68 gzip, 467, 484 H -h, 466 \H, 430 \h, 430 handlers AppleScript, 497–501 end, 498 hard coding, 197 hasSelection, 586–587 hdiutil, 393–394, 467 head, 555 header fi les, 57, 146, 206 compilers, 207 heaps, 196–197 Height, 565 Height, windows, 111 HFS+, 12 hidePow, 574 hitCoords, read more..

  • Page - 663

    641 Interface Builder, 98 Key Equiv, 106 Installer, PackageMaker, 33 instance methods, 235 OOP, 405 instance variables, 230 dealloc, 263 declarations, 232 @synthesize, 265 tagRegEx, 415 instances, 292 instanceVar, 245 instantiation, Objective-C, 253–257 instruments, 25–26 int, 150 main, 147 rand, 174 integer, 491 integers, 150 interaction, Bash, 426 interactive login shell, read more..

  • Page - 664

    642 line continuation symbol, 205 linked lists, 197–198 linkers, 74 linking, 74 List, 199 list, 504, 521 ListNode, 198 lists, 398 literals, 150 load script, 521 localizations, 117, 602 localized resources, 122–123 locate, 457 long int, 150 long list, 10 loops for, 170–171 AppleScript, 502–504 C, 168–174 commands, 478–480 JavaScript, 556–557 read more..

  • Page - 665

    643 moveimage, 420 mv, 447 MVC. See Model-View-Controller MyDocument, 349–351 N ++n, 218 n++, 218 \n, 149, 185 {n}, 460 -name, 437 <name>, 398, 399 _name_, 410 named parameters, 499 name_offset, 399 naming conventions, 242, 252–253 Nano, 428–429 navigation bar, 68 netstat, 467 /Network/Library/ Preferences, 141 new, 416 newDate, 262 newFromFolderWith OpenPanel, 369 read more..

  • Page - 666

    644 NSKeyedArchiver, 342, 343, 384 NSKeyedUnarchiver, 384 NSKeyValueObserving OptionNew, 384 NSLog, 239 NSMainNibFile, 121 NSManagedObject, 344, 376 NSManagedObjectContext, 355 NSMutableArray, 493 NSMutableDictionary, 273, 275 Command, 284 NSDictionary, 275 NSObjectController, 304 NSMutableString, 246 NSString, 275 printUserOptions, 282 NSNotFound, 240 NSNumber, 378 NSFileHandle, 342 NSObject, 231–232, 243 read more..

  • Page - 667

    645 Objective-C, 17, 92, 229–290 accessor methods, 261–288 actions, 292, 536 AppleScript, 531–533 C, 145 class, 231–234 Cocoa, 145, 238 Core Data, 342–343 data hiding, 240–242 dot notation, 266 index, 545 instantiation, 253–257 memory, 257–261 messaging, 246–247 methods, 234–240 naming conventions, 242, 252–253 objects, 231–234 OOP, read more..

  • Page - 668

    646 path(s) (continued) which, 435 path_helper, 429 PDF. See Portable Document Format performance scripting languages, 401 tools, 24–31 Perl, 390, 421 Ruby, 410–411, 414 permissions, fi le mode, 445 persistence, 217 Peters, Tim, 400 PHP, 391, 422 PID, 464 pipes, 392, 438 Pixie, 31, 34 pmset, 467 pointers *, 157 arithmetic, 157 C, 156–163 read more..

  • Page - 669

    647 QuickTime movies, 5–6 QuickTime Player, 16 /Applications/Utilities, 527 launch, 531 Snow Leopard, 527 QuickTime X, 16 QuitCommand, 283 quotation marks JavaScript, 556 shells, 473–474 strings, 185 R R, 464 -r, 477 RAM (random access memory), 4 rand, int, 174 RAND_MAX, 174 fl oat, 174 randNum, 173 fl oating-point numbers, 174 random access memory (RAM), 4 read more..

  • Page - 670

    648 Script Editor, 31, 35–36 scriptable, applications, 490 scriptfi, 469 scripting bridge, 396, 487 scripting languages, 389–424. See also specifi c languages performance, 401 scripts AppleScript, 518–520 Bash, 391, 426, 468–469 functions, 480–481 objects, 518–520 OOP, 518 shells, 38 scrollable, NSImageView, 316–318 SDKs (Software Development Kits), 49 read more..

  • Page - 671

    649 Step Out, 84 Step Over, 84 store script, 521 str, 405 strcat, 182 strcmp, 182, 218 strcpy, 181–182 string, 405 variables, 476 string(s) &, 39 9 AppleScript, 492–493 C, 179–184 functions, 182 immutable, 492 NULL, 183 quotation marks, 185 raw, 405, 407–408 String Commands Suite, 510 stringByAppendingPath Component, 603 stringByTrimming CharactersInSet, 269 read more..

  • Page - 672

    650 textFieldChanged:, 302 this, 421, 559 DOM, 558 Thompson, Ken, 146 Thread States, 26, 28–29 threads, 28–29 throw, 506 TIME, 464 Time Profi ler, 26, 27–28, 30 Title, 629 title, 629 /tmp, 457 to one relationship, 343 to path, 509 To-Many relationships, 343, 370 weakness of, 361 top, 36, 39, 421 touch, 458 transient objects, Core Data, 372–376 read more..

  • Page - 673

    651 widget onhide, 567 onshow, 567 widgets, 418 bundles, 560–561 Quartz, 575 Width, 565 Width, windows, 111 window editor, Interface Builder, 107 windowDidLoad, 381 NSWindowController, 320, 372 windowNibName, 324–325 windows Height, 111 Interface Builder, 102–112 Minimum Size, 111 Quartz Compositor, 13 resize, 108–112 struts, 111–112 Width, 111 with properties, 399 read more..

  • Page - 674

    badvert.indd 652 12/12/09 2:06:03 PM read more..

  • Page - 675

    Related Wrox Books Beginning iPhone SDK Programming with Objective-C ISBN: 9780470500972 Learning to develop iPhone applications doesn’t need to be an overwhelming undertaking. This book provides an easy-to-follow, example- driven introduction to the fundamentals of the Apple iPhone SDK and offers you a clear understanding of how things are done read more..

  • Page - 676

    $39.99 USA $47.99 CAN The Mac OS X Snow Leopard system comes with everything you need in its complete set of development tools and resources. However, finding where to begin can be challenging. This book serves as an ideal start- ing point for programming on the Mac OS X Snow Leopard platform. Step-by-step instructions walk you through the details of each featured read more..

Write Your Review