Home > Articles > Programming > Mac and iOS Programming

This chapter is from the book

Hello World

Just to get oriented, I’m going to start with the simplest imaginable example project—so simple, you won’t have to do much coding at all.

A New Project

Click the Create a new Xcode project link. Xcode opens an empty Workspace window, and drops the New Project assistant sheet in front of it (see Figure 2.2). Select OS X→Application from the list at left, and then the Command Line Tool template from the icons that appear at right. Click Next.

Figure 2.2

Figure 2.2 The New Project assistant leads you through the creation of an Xcode project. First, you specify the kind of product you want to produce.

The next panel (Figure 2.3) asks for the name of the project and the kind of command-line tool you want.

Figure 2.3

Figure 2.3 The Options panel of the New Project assistant lets you identify the product and what support it needs from system libraries.

  1. Type Hello World in the Product Name field. This will be used as the name of the project and its principal product.
  2. Xcode should have filled the Organization Name in for you, from your “me” card in the Address Book. If you listed a company for yourself, that’s what will be in the field; otherwise, it’s your personal name. Xcode will use this as the name of the copyright holder for all new files.
  3. Virtually all executable objects in the OS X and iOS world have unique reverse-DNS-style identifiers that are used to uniquely identify them. The Company Identifier is the leading portion of those reverse-DNS names, to be used by every product of this project. For this example, I used com.wt9t.
  4. By default, Xcode infers the unique Bundle Identifier from the company identifier and the name of the product. You’ll see later how to change this if you have to.
  5. The Type popup prompts Xcode on how to fill in the system libraries the tool will use. This is just a plain old C program, with no need for C++ or Apple-specific support, so choose C.

Finally, a put-file sheet appears, so you can select a directory to put the project into. For this example, select your Desktop. One more thing—uncheck the box labeled Create local git repository for this project. Source control (Chapter 7, “Version Control”) is a Good Thing, but let’s not deal with it in this trivial example. Click Create.

If you look on your Desktop, you’ll find that Xcode has created a folder named Hello World. The project name you specified is used in several places.

  • It’s the name of the project directory that contains your project files.
  • It’s the name of the project document (Hello World.xcodeproj) itself.
  • It’s the name of the product—in this case a command-line tool named Hello World.
  • It’s the name of the target that builds the product. I’ll get into the concept of a target later; for now, think of it as the set of files that go into a product, and a specification of how it is built.
  • It’s the name of the target’s directory inside the project’s directory.
  • Suitably modified, it’s the name of the man-file template for the tool (Hello World.1).

When you’ve made your choices, Xcode unmasks the workspace for the Hello World project (Figure 2.4). Don’t look at it too closely just yet. Xcode starts you off with a view of the settings that control how Hello World is to be built. This is useful information, but for now, it’s just details.

Figure 2.4

Figure 2.4 Once set up, the Hello World project window fills in with a list of source files and a display of the options that control how the application will be built.

More interesting is the program code itself. The left column of the window is called the Navigator area. Find main.c in the list, and click it (see Figure 2.5). The Editor area, which fills most of the window, now displays the contents of main.c. This is the code for the canonical simplest-possible program, known as “Hello, World.”

Figure 2.5

Figure 2.5 Clicking the name of an editable file in the Project navigator displays its contents in the Editor area.

The Navigator area displays many different things in the course of development—it’s not just a file listing. It can display analyses, searches, and build logs. Which list you see often depends on what Xcode wants to show you; you can make the choice yourself by clicking the tiny icons in the bar at the top of the Navigator area. Hovering the mouse pointer over them will show you the names of the various views.

As this book goes on, you’ll meet all of them. For now, you care only about the “Project” navigator, the file list Xcode starts you out with. Feel free to click the other icons, but to keep up with this example, be sure to return to the Project navigator, as shown in Figure 2.5.

Quieting Xcode Down

But first.

Xcode is a toolset that contains everything its creators could think of to provide a powerful, helpful environment for writing iOS and OS X applications. Often, you barely need to begin a task, and Xcode will offer to finish it for you. It will usually be right. I use these features all the time. I recommend them.

You’re going to turn them all off.

Automatic completions and indentations and code decorations and code fixes are great, once you know what’s going on, but an automaton that snatches your work out of your hands, however helpfully, is straight out of The Sorcerer’s Apprentice. Better to start with what you want to do; once you’re confident of what that is, then you have the discretion and control to direct Xcode as it helps you.

So you’re going to damp Xcode down a bit. You’ll do all of this in Xcode’s Preferences window, which you can summon with Xcode→Preferences. . . (Imagecomma). The Preferences window is divided into panels, which you select with the icons at the top of the window.

To start, make sure the General panel is visible. Under Issues, uncheck Show live issues.

Next, select the Text Editing panel, which has two tabs. Select the Editing tab, and uncheck Show: Code folding ribbon, and all the options under Code completion:.

In the Indentation tab, turn off Line wrapping: Wrap lines to editor width and the Syntax-aware indenting section.

Now Xcode will mostly stay out of your way as you explore.

Building and Running

The program in main.c would run as is, but we have to trick Xcode into keeping its output on the screen long enough to see it. Add a few lines after the printf call so it looks like this:

int main(int argc, const char * argv[])

{



    // insert code here...

    printf("Hello, World!\n");



    /******************************************

     *  Pause, so the console doesn't disappear

     ******************************************/

    char     dummy[128];

    fgets(dummy,  sizeof(dummy), stdin);



    return 0;

}

Now we can run it. Select Product→Run (cmd.jpgR).

In the ordinary course, Xcode would then build and run Hello World. However, if this is the first time you’ve run any application, there is a security problem: Running an app from Xcode puts it under the observation of a debugger, which will have access to the internal data and running state of the app. Crossing process boundaries like that is technically a security breach, and you have to authorize it.

Xcode posts an alert, Enable Developer Mode on this Mac?. It explains that you could be asked for an administrator’s password every time you run the debugger (“Developer Tools Access needs to take control of another process. . . ”), or, with Developer Mode, you could do the authorization once and forget about it. Click Enable, enter an administrator’s credentials, and carry on.

With authorization taken care of, a heads-up window (“bezel”) appears almost instantly, to tell you “Build Succeeded.” (If Xcode is in the background, a notification banner will appear saying the build succeeded, and identifying the project and product involved.)

So. What happened?

Hello World is a console application; it just writes out some text without putting up any windows. Xcode captures the console of the apps it runs in the Debug area, which popped into view when you ran the program (Figure 2.6). The Debug area includes a console view on the right. It says Hello, World! (Figure 2.7).

Figure 2.6

Figure 2.6 The View selector in the toolbar shows and hides the Navigator, Debug, and Utility areas (left to right) of the project window. Clicking a button so it is highlighted exposes the corresponding area. Here, the Navigator and Debug areas are selected.

Figure 2.7

Figure 2.7 Opening the Debug area after running Hello World shows the eponymous output.

Click in the console to make it ready for text input, and press the Return key. Hello World exits, and the Debug area closes.

The Real Thing

What Xcode just produced for you is a real, executable application, not a simulation. To prove it, open the Terminal application (you’ll find it at /Applications/Utilities/Terminal, and you’d be well advised to add Terminal to your Dock). In Xcode, find the Hello World product in the Project navigator by clicking the disclosure triangle next to the Products folder icon. Drag the Hello World icon into the Terminal window, switch to Terminal, and press the Return key. (The path to a file deep in a directory for build products is remarkably long, but Terminal takes care of the necessary escaping.) “Hello, World!” appears.

If you want access to the executable file itself, select it in the Project navigator, then File→Show in Finder—also available in the contextual menu you get by right-clicking the Hello World icon. A window will open in the Finder showing you the file.

You’re done! You can close the Workspace window (File→Close Project, cmd-2.jpgW) or quit Xcode entirely (Xcode→Quit Xcode, cmd.jpgQ).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020