Home > Articles > Programming > Mac and iOS Programming

📄 Contents

  1. Planning the App
  2. Starting a New iPhone Project
  3. One More Thing
  4. Summary
This chapter is from the book

This chapter is from the book

Starting a New iPhone Project

Start by creating a new Xcode project, selecting FileNewProject... (arrowcmd.jpgN). Select Application under iOS, and from the array of application types, select Master-Detail Application. Passer Rating follows the common pattern of presenting a progression of lists and detail views, under a navigation bar that provides a “breadcrumb” trail back up the tree. The Master-Detail Application template is a skeleton for such an app. Click Next. (For more on Xcode’s project templates, see Appendix C, “Project and Target Templates.”)

The next panel in the New Project assistant lets you name the project Passer Rating. That much is obvious. The next item is Company Identifier. Every application in the iOS universe has a string that uniquely identifies it. The app needs one. The way to ensure uniqueness is to select a name that’s unique for you (ordinarily the product name) and then to prefix an inverse-dns string. I own the wt9t.com domain, so I’d fill in com.wt9t.

Xcode generates an identifier for you and displays it just under the company ID: com.wt9t.Passer-Rating.

Next is Class Prefix. This is a string that will be prepended to the class names and associated files that the project template creates for you. If this isn’t brief, you’ll end up with unwieldy names, so try PR.

Device Family determines whether the template should include UI setups for iPhone, iPad, or both. Select iPhone.

There are four more options. Take two of them:

  • Use Core Data: Core Data is Cocoa’s object-persistence and relational framework, which is handy for keeping the database organized. The project template will add a number of convenient housekeeping methods for getting a Core Data-based application running.
  • Include Unit Tests: Unit testing, the practice of automatically exercising your code to assure yourself that it works, is an important technique in modern software development. Chapter 13, “Unit Testing,” covers unit testing in detail, but if Xcode’s going to set it up from the start, you’re going to take it up.

The other two, Use Storyboard and Use Automatic Reference Counting, take advantage of features introduced in iOS 5. Storyboard enables you to design not only the user interface for your app, but also how it transitions from view to view as the user navigates through it (see Chapter 15). Automatic Reference Counting (ARC) takes care of memory management in a transparent and reliable way. (It’s available in iOS 4.3 but not fully functional.) Both are great features, but you need to target iOS 4.3.

When I get to a Mac version of Passer Rating in Part III, “Xcode for Mac OS X,” I’ll talk about ARC. For details on reference-counted memory management, see Appendix A, “Objective-C.”

Click Next. You get a get-file sheet to select a directory to receive the project. Pick something convenient, such as your Desktop directory; that’s where Xcode will put the new Passer Rating project directory. And because Chapter 7, “Version Control,” sold you on it, check Create local git repository for this project. Click Create and look at the project Xcode has set up for you.

Target Editor

The Passer Rating project consists of two targets: “Passer Rating,” which produces the app, and “Passer RatingTests,” which will contain the application test suite. Xcode now shows you the Target editor. (Click the Passer Rating project item at the top of the Project navigator to bring it up yourself.) It provides an interface for the basic settings that identify your project—its identifier, target environment, orientations, and the front-end images (icons, startup screen) that are the face UIKit puts on your app.

The Summary tab comes in three sections:

  • iOS Application Target shows the application identifier; Xcode lets you edit the prefix, but you’re stuck with Passer-Rating until you change the product name. You can set a version number (the release version, without markers for alpha or beta status; those confuse Xcode’s packaging process) and a build number (which is where you’d mark prerelease status). And you designate a target (iPhone, iPad, or both) and the “deployment target” (the lowest verson of iOS the app can run on). Xcode obligingly sets this to the latest version Apple sells, but for Passer Rating, set it to 4.3.

    Selecting the software development kit (SDK) is as important as the deployment target, even though the setting is in the Build Settings tab and not Info. This selects the libraries and headers for the highest version of the OS for which you are developing. If the SDK is set for a later version than the deployment target (it must never be set earlier), the features of the later OS are available, but linked “weakly,” so your code can determine at run time whether the features are actually available before trying to use them.

  • iPhone/iPod Deployment Info enables you to set the app icons and the launch images (the static PNG the OS shows the user while the app starts up). Also, you have your choice of the orientations you support, presented as a toggle button for the ones you can handle. This sets the most orientations the app will tolerate; your individual views may be more restrictive. You can ignore the Main Interface combo box; it tells the OS the NIB file (I’ll get to them soon) that specifies your initial UI. For the master-detail app template, you’re set up with code that creates the initial UI, and there’s no need for a NIB to specify the details. Leave this (and Main Storyboard) blank.

    If you select iPad with the Devices pop-up, you get an “iPad Deployment Info” section, laid out for iPad resources, instead. And if you select Universal, you get both sections.

  • Linked Frameworks and Libraries is an editable list of objects that Passer Rating links to: UIKit, Foundation, and Core Data. No need to change it.
  • Entitlements sets up options for compatibility with iCloud and shared access to the cryptographic keychain. You probably don’t need those things, and by the time you do, you’ll know what these settings mean. I won’t be covering entitlements.

The Summary tab is just a front end for the more comprehensive settings under the Info tab, which in turn is a specialized editor for the Info.plist file. Chapter 21, “Bundles and Packages,” covers the contents of Info.plist exhaustively, but it will be quite some time before you need to change anything.

Copyright, Again

If you browse through the source files, you can see that Xcode has once again used __MyCompanyName__ as the copyright holder (unless you set a company name in your card in the Address Book application). This has already been covered in the “__MyCompanyName__” sidebar in Chapter 7. Again, you have two tasks:

  • Make sure Xcode doesn’t repeat the mistake in this project. Do this by exposing the Utility area (click the right segment of the View control) and its File (first tab) inspector, selecting the project (top line) in the Project navigator, and filling in the Organization field.
  • Correct the existing files with a projectwide search and replace. This will be your first look at the Search navigator.
    1. Click the third tab (a magnifying glass) in the Navigator area. You see a text field labeled Find.
    2. Type __MyCompanyName__ in the field; a menu pops up offering you options for the search, but the defaults (in-project, containing, match case) will do fine. See Figure 8.3, top.
      Figure 8.3

      Figure 8.3. Expose the Search navigator to start a projectwide search and replace. (Top) Type the search string in the field; Xcode offers some common search options, but simply typing the string and pressing Return usually works. (Middle) When you press Return the navigator fills with every file that contains the string, showing each match in context. Selecting a match puts it into the Editor area. (Bottom) Use the Find/Replace pop-up to expose the replacement field. Type in your replacement string and click Replace All to make the change in all files.

    3. Press Return. The list under the search field fills with references to every file in which __MyCompanyName__ appears, with subentries showing the found text in context. If you click one, the editor area displays the file, highlighting the match. Refer to Figure 8.3, middle.
    4. The Search navigator’s Find label is a pop-up menu; switch it to Replace to expose the replacement field.
    5. The magnifying glass icon in the search field is a drop-down menu containing your search history. The first item, Show Find Options, lets you customize the search: literal or regular-expression; restrictions on partial-or whole-word searches; whether it’s case-sensitive; and whether it extends to included frameworks.
    6. Type Fritz Anderson in the replacement field and click Replace All. You have to do the projectwide search first, or the replace buttons won’t be enabled—Xcode forces you to look at what you’re changing.

Figure 8.3 shows the whole process.

At this point, Xcode offers to take a snapshot of your project. Snapshots are a supplement to version control; they copy the state of the project into a disk image before you make wholesale changes. Snapshots aren’t a replacement for version control or backups—think of them as providing a mass “undo” that doesn’t break your workflow as much as a commit would. Look for your snapshot history in the Projects panel of the Organizer (WindowOrganizer, arrowcmd.jpg2). From there, you can “Export” the contents of a snapshot to a new directory.

The first snapshot takes a few moments, but after that, they’re cheap, so click Enable.

At last, you are rewarded with all instances of __MyCompanyName__ replaced with “Fritz Anderson.” If you switch back to the Project navigator, you see that all the changed files’ icons are dark, meaning they have unsaved changes. If you save them all (FileSave All, ctrlpull.jpgS—you must hold the Option key down to see it in the menu), the “M” version-control badge will appear next to all of them. Now would be a good time to commit a revision to the repository.

The project template you chose for Passer Rating includes a lot:

  • Frameworks: The Frameworks group contains UIKit, Foundation, CoreData, and SenTestingKit (which is used only by the unit-test target). They provide links into the iOS system software, and Passer Rating won’t run without them. If you open the Build Phases tab of the Project editor, for the Passer Rating target, you’ll find the frameworks in the Link Binary with Libraries phase.
  • Class PRAppDelegate: The application is represented by an object of class UIApplication, which you should never need to subclass or replace. True to the delegation pattern used throughout Cocoa, all the unique behavior of the application comes through the methods of a delegate object, which the application object calls into. PRAppDelegate is declared as a subclass of NSObject and an implementor of the UIApplicationDelegate protocol. The template for the implementation (.m) file contains a good starter for managing the application life cycle, including setting up the Core Data database.
  • Class PRMasterViewController: This is, as the name says, the controller for the bottom-level view of Passer Rating, which the design says is a table of passer names and ratings. Because navigation-based applications almost always start with a table, the template makes PRMasterViewController a subclass of UITableViewController, which is suited for running a table view. The implementation file includes skeletons of the methods you need to fill the table in. It also provides an instance of NSFetchedResultsController, which does a lot to help link tables to Core Data data stores.
  • Class PRDetailViewController: The controller for the next layer of Passer Rating, the one that is seen when the user taps a passer’s name. The template can’t be sure what you’ll be doing with PRDetailViewController, so it declares it to be an instance of the more-generic UIViewController.
  • Passer_Rating.xcdatamodeld: Core Data isn’t a full-service relational database (although it uses the SQLite database library internally), but if it were, the Data Model file would be the equivalent of an SQL schema. It defines the entities (think “tables”) that hold the data, and the attributes (think “columns”) those entities have. Xcode provides a graphical editor for data models.
  • In the Supporting Files group, Passer_Rating-Info.plist: This is the source file that yields an Info.plist file to be embedded in the application. It provides basic information on what the application can do, what data it can handle, and how it is presented to the user in the Home screen. Some of that information is presented to the user as text, so its content is merged with the application’s InfoPlist.strings for the user’s language. (Chapter 20, “Localization and Autolayout,” covers localization in Mac OS X, but most of the concepts apply to iOS, as well.)
  • Miscellaneous source files: main.m is the standard container for the main() function where the program starts; you usually won’t change it. Passer Rating-Prefix.pch contains common initialization for the compiler.
  • XIB files: XIB files are editable files that will be compiled into NIB files and installed in the application. They are archives, mainly of user-interface objects. PRMasterViewController.xib contains the UITableView for the root view and links it to the PRMasterViewController that runs the table. PRDetailViewController.xib is a more generic layout that does the same for PRDetailViewController.
  • The “Passer RatingTests” target has a class file and Info.plist support similar to the app target’s.

Xcode’s template for the project also includes a panoply of build settings, specifying how Passer Rating is to be compiled, linked, and organized.

The project is fully functional, as far as it goes—run it: ProductRun(cmd.jpgR). Xcode builds the app, and in a few seconds, the iOS Simulator starts and launches Passer Rating. Out-of-the-box, the app is the iOS/Core Data equivalent to “Hello World.” It shows an empty table under a navigation bar with Edit and + buttons. Tapping the + button adds a row with the current date and time; tapping the new entry pushes the “detail” view into view; the Edit button in the root list (or swiping across a row) lets you delete rows. You can close and reopen the app to find that the rows you added are still there. See Figure 8.4.

Figure 8.4

Figure 8.4. The skeletal code that comes with the Core Data + Master-Detail Application project template is enough to produce an app that can run in the iOS Simulator. It can add rows to its table, and, as shown here, respond to the Edit button by offering to delete rows.

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