Hour 13. Xcode-Supported Languages


What You’ll Learn in This Hour:

The strengths and weaknesses of different language options under Xcode

How to choose and use the right language

How to add third-party language templates to Xcode


Xcode ships with built-in support for projects written in C, C++, Objective-C, and AppleScript. However, you might want to use one of the many other available programming languages, and it is quite convenient to stick with one development environment for all your programming projects. Thankfully, although Xcode has clearly been optimized for Apple’s Objective-C programming language, it is also easily extendable for other programming languages. In fact, if you can provide Xcode with an external program that understands your favorite language and does the right thing when handed a file containing code in it, you can adapt Xcode to any language that can be written in a text file.

This hour provides an overview of the built-in languages and some other popular languages that Xcode can be used for, such as Perl, Python, and Ruby. You also learn how to install and use third-party language templates that can extend Xcode capabilities, and you learn how to adapt external build components if these are not already easily available.


By the Way

Why might you want to use anything other than Objective-C? As good as Objective-C is, most languages have specific tasks for which they’re particularly well suited. Objective-C happens to be particularly well suited for many Cocoa and general OS X tasks due to the underlying libraries, but it is a fairly general-purpose language. Other languages are particularly well suited for graphics programming, processing text files, and doing math. Still others are particularly good for quick and easily adaptable utilities for the command line, for interfacing with databases, or for generating web content.



By the Way

Sometimes the decision to use a different language stems from the availability of existing code. Millions of lines of scientific algorithms were written in Fortran, and if you can use them instead of rewriting them, you can save years of development effort. The same goes for business algorithms and Pascal (or COBOL). I hope I never, ever, have to write another line of COBOL in my life; but if you need to, Xcode can do that, too.


Choosing the Right Language

The right language for solving a problem depends on of a number of things (for example, the language’s base capabilities, your familiarity with it, and the preexisting code or libraries that are available to perform specific tasks). The right language for processing a text file and extracting simple strings that match a pattern is unlikely to be the same as the language that’s right for writing a video game, and neither is probably the right language for constructing a web interface to a database.

If you’re familiar with (or fluent in) only a single language, you’re stuck using that language as a hammer, with every programming project necessarily looking like a nail to you. Most people get good enough with that big hammer that they can work well enough this way for years, despite the accompanying frustration and inefficiency. Take the time to learn the capabilities of different languages, find out what libraries are already written for it to handle complex tasks, and spend some time working with the one that seems most appropriate for each project you undertake. The effort and time you invest in learning new languages will be quickly repaid when you start realizing that you can write in just five lines (with one of your shiny new languages) the five pages you would have had to write to solve a problem with your big old hammer.


By the Way

Xcode syntax checking and Xcode support for compiling and debugging in a language are independent of each other. Xcode actually knows at least a little bit about the syntax of a large number of languages (and even beyond languages, formal formats for text files). For example, Xcode understands HTML syntax, but has no idea what to do with it. This means that out of the box you could use it for editing HTML files and get syntax highlighting and other convenient editing features, but you could not do anything with the HTML pages you edit in it.

If you configure an external build system project, however, you can explain to Xcode that it should use Safari to display the HTML. Figures 13.1 and 13.2 show the build system configuration and the result of running a project containing an HTML file and an image using this configuration. You’ll learn more about how to configure external build system components later in this hour.


Image

Figure 13.1. A build system configuration that uses Safari to display an HTML page.

Image

Figure 13.2. The result of using this configuration to run a project containing an HTML file and an image.

As mentioned previously, you can use Xcode for languages that it does not natively support (including those already installed in the system, such as Perl, Python, and Ruby). In addition, you can download other languages and use Xcode for them. As long as the language is installed on your system, you can use Xcode to build your project.

Built-In Languages

C

C is, quite likely, the most important programming language in existence. It is the language on which UNIX was built, on which the Internet was built, and on which countless end-user applications have been developed for the past 30+ years. Your Mac, Linux, the Internet, none of them would be the same without C. (Microsoft probably even uses it somewhere.) When they weren’t programming in Assembler, or directly in machine code, the gods programmed in C. Compared to other modern languages, C is much less forgiving, much more terse, and generally much more ill tempered. However, it is about as close to programming on the bare metal as you can get while still using a well-supported language with good library support for everything from numeric calculations to graphics.

C doesn’t hold your hand. If you write an assignment statement that reads the value of an integer and you accidentally give it a variable holding a string rather than an integer to read from, C is happy to assume that you know exactly what you’re doing and grabs the memory contents from the string and interprets them as though they had been stored as an integer. If you try to store a 4-byte value in a 1-byte container, C happily stores the first byte in the target and the next 3 bytes over the top of whatever happened to be in memory after that location. If you’re not extremely careful about how you write your code, C will bite you. And although that kind of behavior sounds a lot like a misfeature, it is also some of the stuff that has made C so powerful and pervasive over the years. If you know what you’re doing, you can store a pile of different variables containing arbitrary data in memory and then dance around that memory accessing it and writing to it using pure pointer math, without ever referencing the variables directly. Because C operates just barely above the assembly/machine-code level, you can make optimizations such as aligning array storage so that it fits the physical indexing and addressing schema of the RAM in your machine. If speed is important, these kinds of tweaks can speed memory access up by an order of magnitude.


Did You Know?

Learn C. Unless you really need to squeeze every last bit of performance out of your machine, you are unlikely to actually need to use it on a regular basis, but the skills and discipline you develop will significantly improve your programming in practically any other language. It will also prove useful if you need to glue together C++ code, with which the Internet is riddled, and Objective-C code. As the lowest-common-denominator (but better standardized than either), C is better at talking to both of these higher-level languages than either are at talking to each other.

The canonical reference book for C is The C Programming Language, although most programmers know it only by the names of its authors, Kernighan and Ritchie. Although not a particularly long book, it is such a definitive reference that much of the standard C language functionality was designed so that it worked the way that this book says it should, rather than the book being written to match the language. Get it. It’s good.



By the Way: Best Uses

C is best used for programs that require speed or brute strength or those that require intricate memory manipulations. C is particularly ill suited for processing text, but it handles large volumes of binary data effortlessly.


C++

C++ was one of two early attempts to bring the concept of object-oriented programming to the C language. It is powerful, but in many respects is overly complex. Although the entire C language was defined and stabilized at only a few pages of parser code quite early in its life, C++ has undergone several rather convulsive revisions, the most recent occurring in 2011. This complexity has not prevented it from being used for an amazing variety of software, and in fact has probably facilitated C++’s application to the wide range of tasks where it has been used. However, it is a source of some annoyance for many programmers; after all, it is reasonably easy to begin to program in C++, but quite difficult to master it sufficiently to be sure that one has chosen the best solution from the options available.

One of the most controversial features of C++ is that it lets you get away with things that it probably should not. C++ can deal with both the procedural and object oriented. In fact, it can deal with both paradigms in the same code, in the same project. This mixing and matching is great if you’re writing for yourself and just need something that works. You can attack the problem in whatever fashion fits your thinking at the moment. It is a real problem for maintenance and reuse, though, because it is often quite difficult to tell what’s going on without a deep study of the code.


Did You Know?

Get a C++ book. Unless you plan to develop cross-platform applications that need to compile on Linux and other UNIX platforms, you are probably going to be doing more of your real-work programming in Apple’s preferred Objective-C. You want to be able to reference C++ constructs and occasionally tweak code that you collect from open source repositories or other C++ developers, so a good reference to the language is going to prove really helpful, but you probably do not need to invest the effort to actually master the language. The definitive reference for C++ is The C++ Programming Language by Bjarne Stroustrup.



By the Way: Best Uses

C++ is best used for large programs that require many interrelated, cooperating parts. Its multiple-inheritance object model enables quite sophisticated class development, but its complexity means that it is poorly suited for small or infrequent programming tasks where a programmer might not develop and maintain mastery.

If you need to make pre-existing C++ code work in an Objective-C project, look into Objective-C++, which is compiler front-end that enables you to combine C++ and Objective-C syntax in the same file.


Objective-C

Objective-C was the other early attempt to objectify C, but it stayed largely hidden from public view until it was adopted as the platform for building the NeXT operating system. Now it is Apple’s workhorse object-oriented language. Its syntax differs slightly from the C++ syntax, with C++ tending toward slightly more “talky” and Objective-C tending toward slightly more terse.

Originally inspired by the object messaging model from SmallTalk, Objective-C lacks a number of the complex class-inheritance mechanisms that are present in C++, and it omits some classical object-oriented paradigms, such as class variables, private methods, and operator overloading. C++-style namespaces are also missing. In return, Objective-C implements its object model using messages and adds reflectivity (or introspection)—that is, the ability for a program to observe and modify itself, which enables numerous convenient features that are not possible with languages that strictly segregate executable code and data. For example, Objective-C enables the creation of weakly typed objects that can be queried at runtime to determine what messages they can respond to, enabling a single class definition to operate across a plethora of data types without needing masses of per-case code.

The power of messages combined with reflectivity should not be mistaken to be as simple as those two words appear. Instead of calling functions or calling methods, Objective-C sends messages. This is not just a semantic distinction. If your program that “calls functions” tries to call a function that does not exist, the program has no idea what to do next. The function it is supposed to be running in is not there, so it breaks. If Objective-C sends a message, and nothing is listening, well, the message gets lost, but unless you’ve decided to trap that behavior and act on it, that’s no reason to bring everything to a screeching halt. The message paradigm and the associated code-is-data reflectivity allow Objective-C programs to defer to runtime many decisions that would have to be compiled-in in C++ or C. Learning to take advantage of this flexibility takes some unlearning for old C/C++ programmers, and a bit of time to sink in, but once mastered, it enables code elegance that cannot be accomplished in many other languages.


Did You Know?

You need Objective-C books, and to use Objective-C productively on the Mac or iOS device, Cocoa books. There’s no way around it. Hour 2, “Just Enough Objective-C and Cocoa,” introduces you to the language; but for complex projects, you should invest in a book or two.

Unfortunately, because Apple is both the primary developer and primary user of Objective-C, there are few original, definitive works such as are available for C and C++. The best current reference is Aaron Hillegass’s Objective-C Programming: The Big Nerd Ranch Guide.

You can also read through Apple’s documentation, starting with: http://developer.apple.com/library/mac/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html.

And more good resources are available from http://cocoadevcentral.com/d/learn_objectivec/ - where you can also learn a bit about the Cocoa libraries, which are almost inextricably linked with Objective-C on Apple systems.



By the Way: Best Uses

Objective-C is an almost absolute requirement for Cocoa programming, and is clearly the preferred choice for development under OS X. Implemented as a lightweight layer on top of C, it has most of C’s strengths, while providing useful frameworks that make things like text processing less painful.


AppleScript

AppleScript is Apple’s ridiculously useful but incredibly poorly promoted scripting language, useful for everything from renaming a bunch of files in a directory to tying together numerous large commercial applications into a single-click workflow for processing data. AppleScript has access to many components of the Cocoa user interface (for example, file-picking dialogs) and to any functionality that any Mac application exposes through an Apple Events interface.

AppleScript enables users to construct a script that, for example, can ask for a directory, collect the files from the directory, launch Photoshop and apply croppings and preprogrammed manipulations and filters to each of the files, change their resolutions to a standard size, make thumbnails of all of them, create an HTML page containing the thumbnails and link it to the modified versions, and finally package the whole thing up and upload it to deploy on a web server. As a scripting language, all of this functionality can be developed incrementally, and because the “work” is done by external applications, all you really need to put in the AppleScript is the smarts necessary to talk to the applications and pass the results around between them.

Although the ever-present AppleScript Editor application is limited to building fairly simple scripts that are entirely self-contained, Xcode enables the development of integrated AppleScript/Objective-C/Cocoa applications, letting you leverage the strength of each environment to deal with the tasks in which it excels. It currently seems easiest to retrieve the AppleScript dictionary from a program using the AppleScript Editor, as shown in Figure 13.3. After you’ve identified the features you want to use in your Cocoa-AppleScript application, you can create a project in Xcode (Cocoa-AppleScript Application, under the Applications group) and add your AppleScript calls. The default project that’s created by the template is a little less helpful than many of Apple’s other default templates, in that it does not call your attention to the correct wrapper section for adding your code with a commented block and appropriate message receiver.

Image

Figure 13.3. Using the AppleScript Editor to retrieve the AppleScript dictionary from a program.

To get started, you can try adding a listener method for applicationDidFinishLaunching between the demarcated initialization and cleanup blocks. Figure 13.4 shows a simple example that opens a Finder dialog for you to pick a folder and then sends the files in the folder off to Photoshop to build them into a contact sheet. Because the point of using the Cocoa-AppleScript mechanism was to leverage the Cocoa features, you probably actually want to build some interface functionality in to the NIB file and catch messages from that, instead of running straight from the launch as this example does.

Image

Figure 13.4. AppleScript can accomplish complex behaviors (such as prompting user input through a file-browser dialog and such as feeding entire folders of files through an application-processing pipeline) with very few lines of code.


Did You Know?

Although AppleScript is enormously useful, it seems like Apple and the application vendors both enjoy fiddling with it enough that what works today often needs tweaked tomorrow. The tweaks usually are not too difficult, but given the frequency of changes to the application interfaces, and seemingly to Apple’s end of things as well, you are better off using the documentation on your system than relying on any printed reference. Between the developer documentation available in Xcode and the documentation every application provides through its AppleScript dictionary, you should be good to go.



By the Way: Best Uses

AppleScript is application glue. It is best used for coordinating and connecting functions from the Finder and other OS X applications. It has severely limited functionality for any type of data processing or manipulation within itself.


Java

Java is the darling of the modern and trendy object-oriented programming crowd, and as an incredibly verbose language with numerous features to protect the programmer from carelessness, it generally annoys old-school C programmers to no end, while simultaneously amusing more modern programmers who think the C programmers are silly for liking to walk uphill to school, both ways.

Java has the quite interesting feature that, at least theoretically, you can write your application once in Java and then run it, without modification, on any platform that has a Java Virtual Machine (JVM). There is, admittedly, some performance penalty induced by the requirement that the JVM has to sit between the program and your real hardware, but the intention is that the extreme portability of the language makes the performance hit worth it. The intentions and theories are, perhaps, a bit optimistic. Practically every Java application you can find on the Internet is distributed with special versions for each operating system because things are not quite identical enough. Practically every Java application also feels like it is running on a machine that is 10 years older than the rest of the software on your system.

Originally envisioned as a way to deploy software interfaces over a network (actually not the Internet), Java was quickly adopted as a way to deliver write-once, run-anywhere software from a web server and run it within a web browser. As such, it has a significantly enhanced set of security features to help prevent a malicious remote server from negatively affecting a client computer that is running its code. Some of these security features also induce impediments that are peculiar to Java. For example, the JVM operates in a restricted memory region, and it is entirely possible (and quite common) for Java programs to run out of memory within the JVM, even though the computer’s RAM is mostly free. Java was also quickly adopted as the object-oriented training language of preference for a great many university computer science programs. This has fostered the development of quite a large library of utility applications written in Java, so it is a useful language to have around for the purpose of avoiding reinventing the wheel. Unfortunately, this is also probably a significant factor in the dismal performance of many Java applications, as many of the programmers who have worked in the language are still at the stage in their careers where paradigm overrides practicality and so they write like they were taught, instead of using the “dirty tricks” that experienced programmers use to squeeze performance out of code.


Did You Know?

Even Apple doesn’t think you should use Xcode for Java projects. It is “supported,” but not well. Apple recommends Eclipse (http://www.eclipse.org/), NetBeans (http://www.netbeans.org/), or JetBrains IntelliJ IDEA (http://www.jetbrains.com/idea/) as better IDEs for large Java projects.



By the Way: Best Uses

Java is best used for developing small cross-platform applications, especially those that run within web browsers. It places severe limitations on program memory, and its performance might cause users to feel that their machines are sluggish.


Perl

Perl is Larry Wall’s Pathologically Eclectic Rubbish Lister (or, Practical Extraction and Report Language, if you prefer). Its overwhelmingly most significant feature is its treatment of regular expressions. Regular expressions are a way of describing patterns in strings and the allowable variation in the patterns. If you’re familiar with wildcards at the command line, you’re familiar with a very primitive form of regular expression. The type of regular expressions that Perl supports can model much more complex patterns in data.

Combined with a C-like syntax for general utility programming, Perl makes for a very convenient language for processing text files, finding patterns within them, and acting on the pieces of the patterns. For example, a Perl program to read an HTML document and extract all the links to image files would, if you were feeling verbose, take three lines of code. If you wanted to download all the image files, as well, that would add one more. Perl’s regular expression engine is so powerful that it is even possible to (easily) write a regular expression to grade math problems. And it only takes three lines!

Don’t believe me? Put the following code in a file named grademath.pl and make the file executable. (Kudos to Tim Conrow of comp.misc.lang.perl for pointing me to this solution more than a decade ago.)

#!/usr/bin/perl
use re “eval” 
print $ARGV[0] =~ m@(d+)s*([+*%-])s*(d+)s*=s*(??{eval "$1 $2 $3"})@ ? 
                                                      "pass " : "fail ";

Run it from the command line like this:

ray% ./grademath.pl "6 + 5 = 19"
fail
ray% ./grademath.pl "6 + 5 = 11"
pass
ray% ./grademath.pl "3 * 9 = 27"
pass

Perl’s great strength, its regular expression engine, is also probably its greatest weakness. In addition to complex regular expressions looking much like the result of your cat taking a nap on your keyboard, if you spend much time working in Perl, everything starts to look like a problem to be beaten with a clever application of regular expressions. A surprising lot of tasks can be addressed that way, but sometimes it is good to take a step back and see whether that graphical adventure game you’re writing might be better written in something that doesn’t believe that the whole world is made of text.


Did You Know?

Xcode supports Perl syntax highlighting, but because Perl is an interpreted rather than compiled language, there’s nothing to “build” for a Perl script. You could, if you wanted, set up an external build system rule to run the script from the command line when you click Run. However, Perl scripts are more often useful from the command line, with data piped in or with files and arguments provided at a shell prompt.

Get yourself a copy of the Camel book, otherwise known as Programming Perl. It is the definitive reference and will ease you on your way to appreciating the wonders of regular expressions.



By the Way: Best Uses

Perl is ideally suited for processing textual data, breaking it into manageable chunks, and manipulating those chunks. It is not a particularly high-performance language, but the rapidity with which sophisticated processing procedures can be developed often more than offsets what Perl lacks in speed. Perl is almost never the right language for working with binary data.


Adding Support for Other Languages

In addition to being useful for languages that are “all there” but that just need special consideration in the way that their projects are set up, such as Perl, Xcode can be extended using third-party add-ons. These add-ons can supplement Xcode capabilities with anything from additional templates and appropriately customized build settings to completely new compilers for languages that the default Xcode is not even aware of. Two of the most popular languages supported by third-party add-ons for Xcode are Python and Ruby. Add-ons for other languages, such as Fortran and COBOL, are available, but functional updates to them usually lag considerably behind Xcode releases.

Python

Python is one of a new breed of languages that manage to combine quite high-level language constructs and direct execution without (obvious) compilation with significant performance. Python is object oriented without being too talky, and has both a large following of loyal users and an amazing collection of utility libraries.

Among Python’s other admirable traits, complex math (in both senses of the word) is quite easy to implement. Matrices, for example, can be first-class objects, letting you write canonical algebraic notation to perform matrix manipulation, instead of requiring that you write two pages of nested for loops, as would be required in C-derived languages. This flexibility is a result of the ease of extending Python’s default classes and overloading Python operators.

Python’s syntax is generally C-like, with some notable exceptions, the most significant of which is that it does not use any type of block delimiter to demarcate the code blocks under the control of, for example, conditional expressions. Instead, Python uses indentation. Whether this is a good thing or a bad thing is the subject of an ongoing battle of epic proportions in online discussion groups. Regardless of whether it is good or bad, however, this feature of Python absolutely requires a Python-aware editor for development.

Xcode understands Python syntax as shipped, but can additionally be extended by the inclusion of useful project templates. Available from https://github.com/chenhaiteng/Python-Project-Template-for-Xcode-4, these templates provide preconfigured default projects for both the Apple-provided system Python and for MacPython (http://wiki.python.org/moin/MacPython) if you have that version installed. Both templates available at the link can be installed in either ~/Library/Developer/Xcode/Templates/ for your personal use, or in /Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/Project Templates/Mac/Other/ to make them available systemwide. When selected as an Other project type for a new project, both configure an external build system build, with most of the required trivia filled in.


Did You Know?

That bit of fine print that flashed by when you were clicking through to create your Python project after installing these templates said that you needed to edit the build scheme to run your script and that there were instructions in a ReadMe file in the Supporting Files directory.

The brief summary is that you need to select Edit Scheme from the Product menu, and then edit the properties for the Run phase. Under the Info tab, the Executable needs to be set to the same Python path as is configured for the external build system. The Debugger should be set to None. Under the Arguments tab, turn on Base Expansions for your target, and add a new item to Arguments Passed on Launch. Fill this argument in with $(SOURCE_ROOT)/ targetname/ followed by the name of the Python file that should be executed when you click Run.


By the Way: Best Uses

Python is extremely well suited for use in scientific and mathematical applications, especially those where its SciPy and NumPy libraries bring in highly optimized solutions to common mathematical tasks. Fortran programmers are likely to find Python appealing. In other contexts where libraries are available to support a given task, Python’s implementations tend to be quite good. Python’s lack of block delimiters make it nightmarish to use if the code is transported back and forth between different developers with editors that mix tabs and spaces.


Ruby

Ruby is another modern, high-performance, high-level language. Like Python, it has a dedicated following of loyal users and a number of useful libraries. It is also an object-oriented language, although it is simultaneously more thoroughly object oriented in its general approach and less pushy about being object oriented in actual use.

Like Objective-C, Ruby is reflective, enabling dynamic metaprogramming and modification at runtime. Unlike Python, which supports private methods that are truly private, Ruby exposes every class method to running programs, enabling full subclassing of any class, and thereby overriding and replacement of class methods.

In Ruby, everything is an object. Everything. Classes are objects, variables are objects, even (what look like static) numbers are objects. Combined with reflection, this means that you can do things like ask the number 5 what methods it supports. Seriously. If you put the command 5.public_methods; in a Ruby file, what you’re doing is asking the numeral 5 what methods it understands. And if you really want, you can extend the methods and teach 5 new tricks.

Another significant feature of Ruby, although it sounds silly to say, is that Ruby somehow inspires the creation of clean code. Where Perl frequently looks like random noise, and Python starts to all run together with its lack of block delimiters, Ruby code just somehow looks neat and tidy. I have no idea why, but I’m not the only person to have observed this. Give it a try, and I bet you’ll agree with me.

Xcode understands Ruby syntax as shipped, but it can also be extended to support full Cocoa-Ruby application types by adding a (semi) third-party add-on. This particular add-on is a bit peculiar because Apple actually supports its development and ships its framework with Lion, but for some reason they currently make the shipped version of the framework private, thereby disabling Xcode software builds against it. By installing the MacRuby package available from http://www.macruby.org/, you give yourself not only a usable Cocoa-Ruby framework, but also add a new Cocoa-Ruby application type to Xcode’s list of application projects that you can create. Like the Cocoa-AppleScript project, the default Cocoa-Ruby project creates a Ruby-powered Cocoa application underlying a NIB-based UI.


Did You Know?

You should study Ruby for a bit to see whether some of its unique features might be magic bullets to solve your programming problems. Although far too varied to begin to detail here, Ruby provides access to some very powerful programming constructs, with surprisingly simple invocation. For example, it is quite easy to tie a Ruby program to a SQL database, such that whenever you manipulate variables in the program it changes values in the database, and vice versa. It is also quite easy to pass chunks of code around as anonymous functions, to let other bits of code execute them elsewhere. This might not sound like it is very useful, but when you manage to wrap your head around the idea, it opens up whole new worlds for code cleanliness and clarity.

If you like Python, there is a good chance you won’t like Ruby. If you like Ruby, there is a good chance you won’t like Python. Try them both, and then stick with the one you find most comfortable.



By the Way: Best Uses

Ruby is well suited for numerous general-programming tasks, and with its Cocoa interface, you can use it to develop high-quality OS X applications. Where Ruby libraries fit a particular task, they tend to be quite well thought out and well written (like with Python).


Other “Unsupported” Languages

The configuration and build steps for the Perl and Python languages are prototypical of what you must do to use Xcode for development in any language that it does not natively know how to compile. As demonstrated by this hour’s very first example, using Xcode on HTML, “running” what you’ve written doesn’t even have to mean running it in the sense of executing it as a program. As long as you can configure the external build system with an appropriate build tool and arguments, and configure the scheme executable and arguments correctly, Xcode really can become a code-editing and code-maintenance tool from which you can automatically deliver your project files into any external application.

Summary

This hour covered the general characteristics and flavor of the main languages supported by Xcode and some other languages that can be supported either through the external build system paradigm or through the addition of third-party components. You learned some of the strengths and weaknesses of each language and the types of uses that each is best suited for. Keep these in mind when you reach Hour 15, “Putting It All Together: Building a Mac OS Application,” and start to think about putting everything into practice to build a complete working application.

The language you choose should be guided by both the capabilities and suitability of the language for the task at hand and by how comfortable you are in the language (or how interested you are in learning it). You can complete nearly any programming task with practically any programming language, although the effort required will probably differ significantly. Most people, however, will gladly take a lot of fun learning over a little bit of drudgery.

Q&A

Q. Do the external build system build tool and the scheme run executable really have to be the same?

A. No. These actually serve two different purposes. The build tool is actually intended to transform your files into something that’s ready to run, and the executable in the Run component of the scheme is what’s supposed to be used to run your program after it has been built. This difference is somewhat nonobvious in these examples because the external build system has been used on scripting languages that are executed directly, rather than “built” before running.

Q. Are these all the languages that can be used in Xcode?

A. Heavens no. They aren’t even all the ones that Xcode knows syntax for.

Q. Is JavaScript the same thing as Java?

A. Not even close. JavaScript is a completely different language that uses some of the same keywords as Java. It was originally intended as a lightweight, quick-to-implement scripting language for adding in-web-browser functionality. Exactly why it was renamed from LiveScript to JavaScript remains shrouded in some controversy, but the naming has certainly caused some confusion. And yes, Xcode knows JavaScript syntax, too.

Workshop

Quiz

1. What are the best references for learning about Objective-C?

2. Order the languages discussed from slowest to fastest in terms of how quickly they could multiply every element in a matrix by 2.

3. Which language will cause you the most headaches if you’re careless?

Answers

1. Apple’s developer and online documentation.

2. This is a trick question. For a straightforward implementation, the order is AppleScript or Java, Perl, Python and Ruby tied, C++, Objective-C, and C. However, remember that Python has some real smarts built around things like matrices as first-class objects. This lets you write A*2 to multiply matrix A by scalar 2. The underlying implementation can split that task across cores, so this can yield speeds far beyond what C’s closer-to-the-metal implementation can do looping iteratively through the whole matrix on one CPU core.

3. C, or perhaps Perl, depending on your version of careless. C causes headaches because it is unrelentingly literal. Perl causes headaches because it is overly helpful but not overly careful itself.

Activities

1. Update the template for the Cocoa-AppleScript project so that it includes default cases to catch applicationDidFinishLaunching and awakeFromNib messages.

2. Build a new external build system project that supports sh/bash shell scripts. This will prove useful to you when you start building more-complex projects where some steps of the build process require running a script to move or modify files within the project.

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

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