Build rules apply only to the Compile Sources and BuildResourceManager Resources build phases.
Build rules specify how particular types of files are processed inCompile Sources build phases and specify which tool is used toprocess files in Build ResourceManager Resources build phases. Forexample, a build rule may indicate that all C source files beprocessed with the GCC compiler. Each build rule consists of acondition and an action. The condition determines whether a sourcefile is processed with the associated action. Usually, thecondition specifies a file type.
Xcode provides default build rules that process C-based files,assembly files, Rez files, and so on. You can add rules to processother types of file to each target. You can see the build rules ineffect for a target in the Rules pane of the Target Info window.Build rules are processed in the order they appear in the Rulespane.
There are two types of build rules:
Target-specific build rules can specify files that the system buildrules do not directly address, and can override the existing systembuild rules.
A build rule’s action typically specifies the tool or compiler touse when processing files that meet the givencondition.Butyou can also specify a build-rule script. The default interpreteris
When processing a source file, Xcode evaluates the build rules fromtop to bottom and chooses the first one whose condition matches thesource file being processed. Because custom build rules appearabove the built-in system rules, the custom build rules canoverride the system build rules.
Create a build rule:
To define a build rule’s condition, choose a file type from theProcess pop-up menu. You can also define rules that match arbitraryfile names by choosing “Source files with names matching:” from theProcess pop-up menu, and specifying a filename pattern in the textfield that appears. This field accepts file name substitution (orglobbing), accepting the same kinds of file patterns that you canuse in a command shell editor. For example, to match all fileswhose names start with a capital letter and end witha
You define the build rule’s action by choosing one of the availablecompilers from the “using” pop-up menu. Xcode provides a number ofbuilt-in compilers to choose from. Alternatively, you can define acustom script for processing files that meet the build rule’scondition.
When processing a source file in the target, Xcodeevaluates the build rules from top to bottom and chooses the firstone whose condition matches the source file being processed. Forthis reason, you should put the most specific build rules above themore general ones. For example, a rule that matches only C++ filesshould appear above a rule that matches all C-like files—that is,C, C++, Objective-C, and Objective-C++ files.
To reorder a custom rule, drag it from itsbackground.Systemrules cannot be reordered.
Create a build rule script:
Instead of choosing one of Xcode’s built-incompilers to process the files specified by a build rule’scondition, you can create a custom script to process thosefiles.
To create a custom script for a build rule,choose:
You can enter your script in the text field thatappears, or you can store your script as a separate file in yourproject and invoke it from the text field using itsproject-relative path. In this case, you are actually defining aone-line build rule script that calls the script in yourproject.
In addition to defining the script, you also need totell Xcode the paths of any output files that the script produces.Enter the path to each separate output file that is produced by thescript in the “with output files” table below the script textfield. For each file, create a row by clicking the plus (+) button.In this row, specify either the full (absolute) path or theproject-relative path to the file. You can use any of theenvironment variables.
Environment variables for build rulescripts:
For example, suppose that you need to define a buildrule to process files with theextension
Note the use of parentheses in this example. Theoutput-files specification uses the standard Xcode syntax foraccessing build settings. Your custom script, however, must usestandard shell syntax to access any environment variablescorresponding to Xcode build settings.
Xcode runs build rule scripts with the currentworking directory set to the project directory. Thisbehavior
A build setting in Xcode has two parts: The name and thespecification. The
The build system consults the value of build settings as itgenerates tool invocations. For example, to generate profiling codefor all the source files compiled with GCC, you turn on theGenerate Debug Symbols (
Build setting values may come from a number of sources at buildtime. Xcode stores build setting specifications in dictionariesspread across several layers. Typically, you are most interested inthe
In addition to build settings, you canset
Build setting names start with a letter or underscore character;the remaining characters can be letters, underscore characters, ornumbers. The Xcode application doesn’t allow you to define buildsettings whose names don’t follow this convention. Because buildsetting names are case sensitive,
The value of a build setting is determined by evaluating the buildsetting specification. A build setting specification can be a valuesuch as a string, number, and so forth, or it can reference thevalue of other build settings.
To reference a build setting value in a build settingspecification, use the name of the build setting surrounded byparentheses and prefixed by the dollar-sign character ($). Forexample, the specification of a build setting that refers to thevalue of the Product Name build setting could be similarto
In addition to the build settings provided by Xcode, you canadd
The following list describes some circumstances in which you mayneed to add user-defined build settings to a project:
24.Predefined build configurations
A debug build of a product may include debugging information toassist you in fixing bugs. However, this extra information canconsume valuable space in a user’s system. A debug build shouldcontain only the code necessary to run the application.
Some build settings tell Xcode to add debugging information to anexecutable or specify whether to optimize its execution speed.Other build settings turn on features such as Fix and Continue,which are useful only during debugging.
All Xcode project and target templates include two buildconfigurations, the Debug build configuration and the Release buildconfiguration. By default, the Debug build configuration turns onFix and Continue, and debug-symbol generation, among others, whileturning off code optimization. The Release build configurationturns off Fix and Continue. The code-optimization level is set toits highest by default, through the Optimization Level(
The Link Binary With Libraries build phase in Xcode projects linksframeworks and libraries with object files to produce a binaryfile. Source files that use code in a framework or a library mustinclude a reference to the appropriate programming interfacecontained in them.
The binary file (or image) a targetproduces can be of one of these types:
The Mach-O Type (MACH_O_TYPE) buildsetting allows you to specify the type of binary a target produces.By default, this build setting is set to the appropriate valuedepending on the target’s type.
26.Reduce build times
Xcode offers a number of features you can take advantage of todecrease build time for your project.
(1) Using a Precompiled Prefix Header
A precompiled header is a file inthe intermediate form used by the compiler to compile a sourcefile. Using precompiled headers, you can significantly reduce theamount of time spent building your product. Often, many of thesource code files in a target include a subset of common system andproject headers. For example, each source file in a Cocoaapplication typically includes the
You can significantly reduce build time by providing a prefixheader that includes the set of common headers used by all or mostof the source code files in your target and by having Xcodeprecompile that prefix header.If you have indicated that Xcodeshould do so, Xcode precompiles the prefix header when you buildthe target. Xcode then includes that precompiled header file foreach of the target's source files. The contents of the prefixheader are compiled only once, resulting in faster compilation ofeach source file. Furthermore, subsequent builds of the target canuse that same precompiled header, provided that nothing in theprefix header or any of the files on which it depends has changed.Each target can have only one prefix header.
When Xcode compiles your prefixheader, it generates a variant for each C language dialect used byyour source files; it stores these in the folder specified bythe
Precompiled headers can be reused across targets and projects.Targets that share the same prefix header and common compilersettings will automatically share the same precompiled header.
Xcode automatically regenerates the precompiled header whenever theprefix header, or any of the files it depends on are changed, soyou don't need to manually maintain the precompiled header.
To take advantage of precompiledheaders in Xcode, you must first create a prefix header. Create aheader file containing any common
Do not include in the prefix header anything that changesfrequently. Xcode recompiles your precompiled header file when theprefix header, or any of the headers it includes, change. Each timethe precompiled header changes, all of the files in the target mustbe recompiled. This can be an expensive operation for largeprojects.
Because the compiler includes theprefix header file before compiling each source file in the target,the contents of the prefix header must be compatible with each ofthe C language dialects used in the target. For example, if yourtarget uses Cocoa and contains both Objective-C and C source files,the prefix header needs to include the appropriate guard macros tomake it compatible with both language dialects, similar to theexample shown here:
Once you have created the prefixheader, you need to set up your target to precompile that header.To do this, you must provide values for the two build settingsdescribed here. You can edit these build settings in the Build paneof the target inspector or Info window. The settings you need tochange are:
You must provide values for these settings in each target that usesa precompiled prefix header, even if those targets use the sameprefix header.
By default, Xcode precompiles a version of the header for eachC-like language used by the target (C, C++, Objective-C, orObjective-C++). The
Xcode compiles your prefix headerwhenever it fails to find a matching precompiled header binary inthe shared precompiled header location. As described earlier inthis chapter, Xcode automatically rebuilds your precompiled prefixheader if you make changes to the prefix file or to any files itincludes. Xcode also recompiles your prefix header if you makechanges to your target's build settings that affect the compileroptions used to build the target's files.
You can also force Xcode to rebuild your precompiled header by:
By default, cleaning a target removes the precompiled header forthat target—whether or not Xcode initially generated theprecompiled header binary as part of building that target. Becauserebuilding precompiled headers can be time consuming, you may wantto clean an individual target without discarding the precompiledheader binaries for that target if you are sharing precompiledheaders across many targets in multiple projects. When you initiatea clean, Xcode displays a dialog that lets you choose whether topreserve precompiled headers. To keep precompiled headers, deselectthe Also Remove Precompiled Headers option. By default, this optionis enabled.
(2) Predictive Compilation
Predictive compilation is a featureintroduced to reduce the time required to compile single filechanges and speed up the edit–compile–debug cycle of softwaredevelopment. If you have predictive compilation enabled for yourproject, Xcode begins compiling the files required to build thecurrent target even before you tell Xcode to build.
Predictive compilation uses the information that Xcode maintainsabout the build state of targets that use the native build system.Xcode keeps the graph of all files involved in the build and theirdependencies, as well as a list of files that require updating. Atany point in time, Xcode knows which of the files used in buildinga target’s product are out of date and what actions are required tobring those files up to date. A file can be updated when all of theother files on which it depends are up to date. As files becomeavailable for processing, Xcode begins to update them in thebackground, even as you edit your project.
Xcode will even begin compiling asource code file while you are editing it. Xcode begins reading inand parsing headers, making progress compiling the file even beforeyou initiate a build. When you do choose to save and build thefile, much of the work has already been done.
Until you explicitly initiate a build, Xcode does not commit any ofthe output files to their standard location in the file system.When you indicate that you are done editing, by invoking one of thebuild commands, Xcode decides whether to keep or discard the outputfiles that it has generated in the background. If none of thechanges made subsequent to its generation affect the content of afile, Xcode commits the file to its intended location in the filesystem. Otherwise, Xcode discards its results and regenerates theoutput file.
You can turn on predictivecompilation by selecting “Use Predictive Compilation” option in theBuilding pane of the Xcode Preferences window.Predictive compilation works only with GCC 4.0or later and native targets. All predictive compilation is donelocally on your computer, regardless of whether you havedistributed builds enabled. On slower machines, enabling predictivecompilation may interfere with Xcode performance duringediting.
(3) Distributing builds amongmultiple computers
Building a product involves several tasks. Some tasks, such ascompiling precompiled headers and linking a binary, can beperformed effectively only by the computer that hosts a build.However, the main task performed in a build—compiling sourcefiles—can be carried out in parallel by several computers. Buildsthat use several computers to compile source files are knownas
27. Dynamic Library(Shared Library) in iOS
Distributing libraries in a developer-friendly manner is tricky.You need to include not only the library itself, but also anypublic include files, resources, scripts etc.
Apple's solution to this problem is frameworks, which are basicallyfolders that follow a standard structure to include everythingrequired to use a library. Unfortunately, in disallowingdynamically linked libraries in iOS, Apple also removed static iOSframework creation functionality in XCode.
Xcode is still technically capable of building frameworks for iOS,and with a little tweaking it can be re-enabled.
Static frameworks are perfectly acceptable for packaging codeintended for the app store. Despite appearances, it's just a staticlibrary at the core.
(1) Installing the Template System
To install, run the
Now restart Xcode and you'll see
To uninstall, run the
(2) Creating an iOS Framework Project\
There will be two folders in the buildlocation:
If your framework has only code, and no resources (like images,scripts, xibs, core data momd files, etc), you candistribute
If you have included resources in your framework,you
Why is an embedded framework necessary? Because XCode won't lookinside static frameworks to find resources, so if you distribute(your framework).framework, none of its resources will be visibleor usable.
An embedded framework is simply an extra wrapper around aframework, containing symbolic links to the framework's resources.Doing this makes Xcode happy-warm-and-fuzzy because it can finallysee the resources.
iOS frameworks are basically the same as regular dynamic Mac OS Xframeworks, except they are statically linked.
To add a framework to your project, simply drag it into yourproject. When including headers from your framework, remember touse angle bracket syntax rather than quotes.
For example, with framework "MyFramework":
30. Grouping files
(1)Grouping files into static groups
In the Groups & Files list, static groups look likefolders, but don’t have to correspond to folders on the filesystem. You can instead arrange files into groups that make senseto you while working on them in Xcode. For example, in a projectcontaining multiple targets, your project could store all the nibfiles in one folder and all the implementation files in anotherfolder on the file system. And in the Groups &Files list, you could group the files according to target; that is,the nib files and implementation files for target A would be in onegroup, the nib files and implementation files for target B would bein another group, and so on. A group doesn’t affect how a target isbuilt.
Creating a Static Group
You can create a static group in any of the following ways:
Adding Files to a Group
You can add files to a group at any time by dragging the file iconsto the group’s folder in the Groups & Files list. Aline appears to indicate where you are moving the files. Xcodeautomatically expands groups as you drag items to them.
When you remove a group from your project, you can choose whetherto remove the files in that group from the project or simplyungroup the files.
(2)Using smart groups
Smart groups are also represented by folder icons in the Groups& Files list; however, they are colored purple todistinguish them from static groups. As mentioned earlier, smartgroups group files that adhere to a common pattern or rule. Forexample, you could define a smart group to collect allimplementation files ending in
Creating a Smart Group
To create a smart group, choose Project > New SmartGroup. Then choose one of the following options:
Xcode adds a smart group of the selected type to your project andbrings up the Smart Group Info window, which allows you toconfigure the group. Xcode provides templates for each type ofsmart group; it uses these templates to configure new smart groupswith a default set of options. For example, the default SimpleFilter Smart Group collects all fileswith
Configuring a Smart Group
To configure a smart group, select the group in the Groups& Files list and open the Smart Group Infowindow,
Here is what the Smart Group Info window contains:
31. Saving frequently accessed locations
In any project, there are locations that you find yourselfaccessing again and again: files that you edit frequently, headersthat you browse, even smart groups that you use often. Xcode letsyou save locations that you access frequently and provides ways foryou to jump to these locations.
To add an item to the favorites bar, simply drag it to thefavorites bar in the project window. You can save any of the samelocations you can bookmark, including files, documentation, URLs,and so forth. In addition, you can add smart groups and staticgroups to the favorites bar. The Groups & Fileslist can get quite long as you reveal the contents of more and moregroups, scrolling the items at the bottom of the list out of view.You can add groups—including any of the built-in smart groups—tothe favorites bar to quickly jump to that group in the Groups& Files list.
To reorder items in the favorites bar, drag them to the desiredlocation; dragging an item off of the favorites bar removes theitem from the favorites bar. To rename an item in the favoritesbar, Option-click the item and type the new name. This changes thename of the entry in the favorites bar; it does not affect the nameof the actual item that the entry represents.
To open a saved location, click it in the favorites bar. If theitem in the favorites bar is a container, such as a group orfolder, it is a pop-up menu that you use to navigate through thecontents. Each of the items in the favorites bar serves as a proxyfor the actual item. Thus, Control-clicking the item brings up theitem shortcut menu, which allows you to perform operationsappropriate for the selected item.
Another way that Xcode lets you navigate your project and provideeasy access to the information you need is with bookmarks. If youhave files or locations in your project that you access often, youcan bookmark them and return to those locations at any time simplyby opening the bookmark.
To create a bookmark, select the location you want to bookmark andchoose Edit > Add to Bookmarks.
Xcode automatically names some bookmarks. For items such assymbols, Xcode prompts you for the name of the bookmark; you canenter a name to help you remember which location the bookmarkindicates, or you can use the name Xcode assigns. You can bookmarkproject files, documentation, URLs, and so forth.
32. Add comments to project items
To help you keep track of your project contents, you can writecomments and associate them with any of the items in your project.Xcode remembers these comments across sessions. In this way, youcan document your project and its components, keep design notes, ortrack improvements you still wish to make. This is especiallyuseful if you are working with large or complex projects that havemany pieces, or if you are working with a team of developers andhave multiple people modifying the project.
For example, imagine a large project containing targets that builda suite of applications, a framework used by each of thoseapplications, a command-line tool for debugging, and a handful ofplug-ins for the applications. With such a large number of targetsit might be hard to keep track of exactly what each of the productscreated by those targets does. To make it easier to remember whateach of them does, you could add a short description of the productthat it creates to the target’s comments. This also aids others whomay be working on the project with you; if they can read thecomments, they can quickly get up to speed with the project andeasily learn about changes made by other members of the developmentteam.
To add comments to a project item:
You can add commentsto any project item except smart groups, including projects,targets, files, and executables. You can view comments you haveadded to project items in the detail view and you can search thecontent of those comments using the search field. If the Commentscolumn is not already visible, use the shortcut menu of the detailview header to display it.
Open files byfilename or symbol name
There may be timeswhen you need to open a file whose location you don’t know or wantto open the file that defines a particular symbol, such as avariable, method, or class. To assist you in those occasions, Xcodeprovides the
To open a file quickly:
34. Documentation Access
(1)Using quick help
It is a window thatopens inline and contains the reference documentation for only onesymbol. It provides an unobtrusive way to consult API referencewithout using the Documentation window. However, when you need todelve deeper into the reference, the Documentation window is just aclick away. You can open Quick Help from within the Xcode texteditor.
To open Quick Help:
The top portion always contains the following:
The Documentation window lets youview HTML-based documents about Apple tools and technologies andsearch through developer documentation that includes API reference,programming guides, tutorials, technical articles, and sample code.You can also view third-party documentation. The window offers anumber of features that help you get the most out of thedocumentation Apple provides.
To open the Documentation window, choose Help >Developer Documentation.
The first time you open the Documentation window, it opens to theXcode Quick Start page, shown below
(2)Setting documentation preferences
The Documentation Sets group in Documentation preferences lists, bypublisher, the documentation sets that are:
You can customize what you see in Quick Help and the order of thecontent that appears.
To control which fields are displayed in Quick Help:
To change the order in which content appears in Quick Help:
To ensure that fonts always use a minimum size
35. Base SDK and Deployment Target
You can use features from system versions laterthan the deployment target—up to and including the OS versionyou've selected as your base SDK—but you must check for theavailability of new features.
The figure describes a project with a deployment target of Mac OS Xv10.4 and a base SDK of Mac OS X v10.6. (The version numbers in thefigure represent all releases of that version, including systemupdates.)
In this example, the software can freely use any features from MacOS X v10.0 through the newest update of version 10.4. It canconditionally take advantage of features from Mac OS X v10.5 and10.6, after ensuring that each such feature is available.
The effects of these settings at compile time and run time are asfollows. If your code uses a symbol:
Always check to see if you are using deprecatedAPIs; though still available, deprecated APIs are not guaranteed tobe available in the future. The compiler warns you about thepresence of deprecated APIs in your code.
Before using any symbol introduced in a version of iOS or Mac OS Xthat is later than your deployment target, check whether the symbolis available. If the symbol is not available, provide an alternatecode path.
(1)Using weakly linked classes in iOS
If your Xcode project uses weakly linkedclasses, you must ensure the availability of those classes at runtime before using them. Attempting to use an unavailable class maygenerate a runtime binding error from the dynamic linker, which mayterminate the corresponding process.
Xcode projects that use a base SDK of iOS 4.2 or later should usethe
This works because if a weakly linked class is not available,sending a message to it is like sending a messageto
To use the
In Mac OS X (and in iOS projects that do notmeet the set of conditions just listed), you cannot usethe
(2)Using weakly linked methods,fucktions, andsymbols
If your project uses weakly linked methods,functions, or external symbols, you must ensure their availabilityat run time before using them. If you attempt to use an unavailableitem, the dynamic linker may generate a runtime binding error andterminate the corresponding process.
Suppose you set the base SDK in your Xcode project to iOS 4.0. Thisallows your code to use features in that version of the operatingsystem when running in that version. Suppose also that you wantyour software to run in iOS 3.1, even though it cannot use thenewer features in that version of the OS. Allow this by setting thedeployment target to the earlier version of the operatingsystem.
In Objective-C, the
Check the availability of an Objective-C property by passing thegetter method name (which is the same as the property name)to
To determine if a weakly linked C function isavailable, use the fact that the linker sets the address ofunavailable functions to
Check the availability of an external (
(3)Weak linking to an entire framework
If you are using a recently added framework—onethat became available after your deployment target—you mustexplicitly weak link to the framework itself. For example, say youwant to link to the Accelerate framework, first available in iOS4.0, to use its features on systems in which they’re available. Inaddition, say you set your deployment target to iOS 3.1.3, allowingusers of that version of iOS to use your app without the newfeatures. In this example, you must weak link to the Accelerateframework.
When using a framework that
(4)Conditionally compiling for different SDKs