xcode相关的一些知识(一)

1.修改xcode下键盘的一些快捷键
  1. Choose Xcode > Preferences.

  2. Select Key Bindings, which letsyou change the keyboard shortcuts for actions accessible throughmenu items or the keyboard, such as paging through a document ormoving the cursor. You can choose a predefined set of keyboardshortcuts for menu items and other tasks, or you can create yourown set. 
2.添加breakpoint的action

Normally, Xcode just stops the execution of the program when itencounters a breakpoint. By specifying breakpoint actions, you makeXcode perform other actions, such as logging output to theconsole.

To add a breakpoint action to the breakpoint you added earlier:

  1. Choose Run > Show > Breakpoints.Xcode displays the Breakpoints window.

  2. In the detail view in the Breakpoints window, click the triangle tothe left of the breakpoint you added earlier.

  3. Click the add (+) button that appears below the breakpoint.

  4. From the pop-up menu that appears in the line below the breakpoint,choose Sound.

  5. From the second pop-up menu, choose the sound you want Xcode toplay when it reaches that breakpoint.

  6. Now when execution reaches the breakpoint, Xcode plays a sound inaddition to stopping the program.

3.在xcode的Groups&Files列表中,有一项Excutables,Excutables是什么?

After you’ve successfully built a product, you need to test it tomake sure that it works. When it comes time to run or debug yourproduct, you use an executable environment to tell Xcode how to doso. An executableenvironment tells Xcode what program tolaunch when you run or debug from within Xcode and how to launchthe program. The executable environment lets you tell Xcode whatcommand-line arguments to pass, what environment variables to set,what debugger to use, and so forth.

If you are building a product that can be run on its own—anapplication, command-line tool, and so forth—Xcode automaticallysets the default executable to the target’s product. However, ifyou have a product such as a plug-in or framework, you must createan executable environment to specify a program to run and test yourproduct with.

Even if your product generates an executable that can run on itsown, you may want to customize the executable environment tospecify command-line arguments for Xcode to pass to the program onlaunch, environment variables to set, and so forth.

A project can contain any number of executables. There is not aone-to-one correspondence between targets and executables, althoughXcode automatically creates an executable environment for eachtarget that creates a product that can be run on its own. You can,however, define multiple executable environments to use to test theproduct of a single target under different circumstances.

4.修改product的location Each time you create a project, Xcode sets the build locations forthat project to the default build locations specified in theBuilding pane of Xcode preferences. You can, however, overridethese default build locations on a per-project basis. By takingadvantage of this feature, you can choose default build locationsthat works best for most of your projects, and specify otherdefault build locations for individual projects asneeded.
 

  1. In the Groups & Files list of the project window,select the project group and then click the Info button in thetoolbar.

  2. Click General to see the current build location.

  3. Change the location of the build products by selecting “Customlocation”, clicking Choose, and navigating to a location.

5.什么是project root?
在project info->General中,有一个叫做Roots的属性。
projectroot is a directory containing a projectpackage (xcodeproj文件), source files, and other project files.Simple projects have a single project root. Complex projects, madeup of two or more projects that share products or resources, cancontain multiple project roots. Each project root has its own SCMconfiguration, which allows you to work on projects made up ofmultiple projects with subprojects stored in different SCMrepositories.
6.什么是Project format?
在project info->General,有一个 Projectformat. Projectformat s pecifiesthe Xcode release with which the project must remaincompatible. 
You may work in a team in which some team members may need to usean Xcode release different from the one you use; for example, somedevelopers may need to use Xcode 2.4 while you may want to useXcode 3.2 to take advantage of features that are not available inearlier releases. If you use Xcode 3.2 to work on the same projectsthat an Xcode 2.4 user also works on, you have to make sure thatyou don’t use Xcode 3.2 features on those projects; otherwise, yourXcode 2.4–using colleague may have trouble working on or evenopening the projects. Whenyou choose a project format that doesn’t support the projectconfiguration (for example, when a build setting isn’t supported bythe chosen format), Xcode notifies you of theincompatibility . Toview the details of the incompatibility, click the Show Conflictsbutton (this button is available only when there’s at least oneconflict). Youhave two options for solving these conflicts:
  • Change the project format to one that supports the feature that’scausing the conflict.

    Other developers working on the same project must use a release ofXcode that supports the same project format.

  • Change the project configuration so that it doesn’t use the featurethat’s causing the conflict.

7.什么是Organization name?
在projectinfo->General->Organizationname. Specifies name of the organizationto which copyright is attributed in header files created for theproject.
In XCode 4, open up your project. Select the top-most item in theProject Navigator (MyProjectName, 1 target, iOS SDK 4.3 -- orwhatever). Open up the file inspector(View->Utilities). In the Project Document section,you should see an "Organization" line. Edit that, and new filesthat you create will display the new organizationname.
8.什么是Parallel target builds?
在projectinfo->General->Parallel targetbuilds. Specifies whether to buildindependent targets in parallel. 

Normally the build system builds a target’s dependenciessequentially; such builds are called sequential target builds).That is, each dependency’s build process is completed beforestarting the build process for another dependency.

To shorten the build process, the build system can take advantageof parallel target builds. With parallel target builds, the buildsystem builds target dependencies in parallel instead of one at atime.

The only build phase that the build system carries out in parallelis Compile Sources. All other build phases are performed linearly.This means that before and after the Compile Sources build phase,the build system processes a target’s dependenciessequentially.

Before activating parallel target builds for a project, ensure thatthe targets to be built in parallel do not have dependencies(direct or indirect) on each other. An example of an indirectdependency is a target that uses a source file generated during thebuild process of another target. With sequential target builds,this hidden dependency may be avoided by building the target thatgenerates the source file first. However, with parallel targetbuilds, the order in which the targets are built is undetermined,which may produce successful and unsuccessful builds of the sametarget with no changes made to it.

9.什么是Code Sense Index?
在project info->General中,Allows youto rebuild the symbol index.

Symbol Indexing makes it simple to find and view information aboutyour code and to gain easy access to project symbols. A project’ssymbol index maintains detailed information about the code in yourproject and in libraries used by your project; this information isstored in a project index. Using this project index, Xcode providessupport for features such as the following:

  • Code completion. Code completion, assistsyou in writing code by providing completion suggestions from withinthe editor. Code completion uses the stored information about thesymbols, as well as the contextual information from your sourcecode, to offer a list of classes, methods, functions, or otherappropriate symbols for the code you are working on.

  • Class browser. Using the class browser,you can view the classes in your project and its includedframeworks. From the class browser, you can easily accessdeclarations, source code, and documentation for these classes andtheir members. 

  • Project Symbol smart group. The ProjectSymbol smart group allows you to view all of the symbols in yourproject directly in the project window. You can search thesesymbols or sort them according to type or name to quickly find thesymbols you need. The Project Symbols smart group also gives youeasy access to a symbol’s definition. 

  •  

    Searching. Xcodeoffers numerous ways to search for symbols and other information inyour project. For instance, you can perform a projectwide searchfor symbol definitions, or you can select an identifier in aneditor window and jump to its definition. 

Xcode creates the a project’s symbol index the first time you opena project. Thereafter, the index is updated in the background asyou make changes to your project. Indexing occurs on a backgroundthread, to keep it from interfering with other operations in Xcode.The index can be completely rebuilt, if necessary, by opening theGeneral pane in the Project Info window and clicking the RebuildCode Sense Index button.

Indexing is enabled by default. You can disable indexing for allprojects that you open. To do so, choose Xcode >Preferences, click Code Sense, and deselect the “Enable for allprojects” option in the Indexing section.

Note that if you turn off indexing, you will be unable to use thosefeatures that rely on the project index, such as code completion,the class browser, and the other features mentioned in thissection. You can specify whether Xcode includes a particular filein the project index using the “Include in index” checkbox in theFile Info window.

10.Files in project

For each source file included in a project, Xcode tracks fileattributes, such as the name and type, as well as otherinformation. Below shows theinformation that Xcode tracks for source files.

  Asource file

In the illustration, the name isthe file-system name for the file. The filetype identifies the file as being one ofseveral classifications (source file, image file, text file, and soon.) Depending on the file type, Xcode stores additionalinformation about the file, such as the file encoding, type of lineendings, and so forth.

The path tothe file specifies the file-system location for the file.The pathtype —which you can modify—indicates howXcode stores the path; that is, whether it is absolute or relativeto the project directory or another location. Youcan view and edit these file attributes in the File Infowindow.

The project lets you pull together all of the files and otherinformation required to build a set of related software products.Within a project, you use a target to specify the files needed foran individual product. The files can reside at any location in yourfile system; they do not need to be placed in your projectfolder.

when y ouwant to add files or folders to your project, justd ragthe icons for the files or folders from the Finder to the projectwindow Groups & Files list,then  Xcodedisplays a dialog:

Here is what the dialog contains:

  • The “Copy items into destination group’s folder (if needed)” optioncontrols whether or not the files are copied into your projectfolder on disk. If you select this option, Xcode copies over anyfiles that are not already present in the project folder. If theproject folder contains subfolders for groups, then the files arecopied into the appropriate subfolder.

  • The Reference Type menu specifies how the location of the file isstored. Xcode stores the location, or path, foreach file, framework, and folder in a project. Xcode uses this pathto locate the item. Xcode can store this as an absolute path orrelative to another file-system location. You choose the way that agiven file, framework, or folder is referenced when you add it tothe project. You can also change the reference type for an item inthe File Info window. Xcode supports the following referencestyles, each of which is available in the Reference Type menu:

    • Relative to Enclosing Group. The path isrelative to the folder associated with the file’sgroup(group的意思是工程中的上层文件夹,比如Classes和Other Sources). If the file isnot in a group or the group has no associated folder, the path isrelative to the project’s folder. This is the default setting forfiles in your project’s folder.

    • Relative to Project. The path is relativeto the project’s folder, regardless of whether the file is in agroup with an associated folder.

    • Relative to Build Product. The path isrelative to the folder that contains the project’s build products.This reference style is the default for items that are created byone of the project’s targets.

    • Relative to . The path isrelative to a user-defined source path. You can define a sourcepath in the Source Trees pane of Xcode preferences. Note that thisreference type is not available to you until you have defined atleast one source tree.

    • Absolute Path. The path is absolute fromthe root directory (/). This is useful in a limited set ofcircumstances, when you want to locate a file at a particular path.In most cases, you should use a relative path; absolute paths arefragile and break easily when you move projects betweencomputers.

    If a file is inside your project folder or its build folder(created by Xcode when it creates a new project), use one of thefirst three reference styles.

    If Xcode can’t find a file, folder, or framework at the path storedfor it in the project, Xcode displays the item in red in theproject window.                                                                                 Note thatthis menu does not contain any source paths until you have definedone or more source trees in Source Trees preferences . After youhave defined a source path, it appears at the bottom of theReference Type menu and you can choose it for the files and foldersyou add.A sourcetree is a root path that can be used todefine a common location for target outputs. A source tree definesa name and a location on the local file system. When you add filesand folders to your project, you can specify their locationrelative to any source tree defined for your computer. Xcode storesthe file reference relative to this source tree. Any users who havethe same source tree defined are able to work on the same projectseamlessly, provided that the file also exists at the source treelocation on their computers.

    Source trees let you keep common resources in locations other thanthe project folder of an individual project and still transferprojects back and forth between team members and their variouscomputers without breaking the project’s file references. This isparticularly useful if you have a set of common files or resourcesthat are used in a number of projects and therefore cannot live inthe project folder. Everyone working on a common project shouldhave the same source trees defined; even though the locationsassigned to those source trees may differ, the names must be thesame in order for Xcode to locate the necessary files and materialson the developer’s computer.

    The source trees that you define are available to all yourprojects; that is, Xcode supports CodeWarrior-style global sourcetrees. Because source trees are stored for each user, if you havemultiple developers using a single computer, you will have todefine the source trees for each user, even though the location forthose source trees is the same. After you have defined a sourcetree, it is available to you from the Add Files dialog to use whenadding file, folder, and framework references to yourproject. You can edit source trees in Source Treespreferences. To open this pane, choose Xcode >Preferences and click Source Trees. To add a source tree, click theplus (+) button beneath the source tree table. Xcode adds an entryin the table. Add the following information to the entry:

    • Setting Name is the name of the sourcetree. This name must be the same for all users who wish to use thissame source tree to refer to common files.

    • Display Name is the name that Xcode showsfor the source tree in dialogs, Info windows, and anywhere else thesource tree is used in the user interface. For example, this is thename used in the Path Type menu of the File Info window.

    • Path is the full path to the files andother resources located using this source tree on the user’ssystem. This path may vary from computer to computer, and from userto user.

    To delete a source tree, select the source tree in the table andclick the minus (-) button. To edit a source tree, double-click theentry for the source tree in the appropriate table column and typethe new text.

  • The Text Encoding menu specifies the encoding for the file orfiles. 

    The file encoding of a file defines the character set that Xcodeuses to display and save a file. If you type a character that isn’tin the file’s encoding, Xcode asks whether you want to change theencoding. Xcode uses the default single-byte string encoding orUnicode if the file contains double-byte characters.

    To change the file encoding for one or more files:

    1. Select the files and open a File Info window.

    2. In the General pane, choose the desired file encoding from the FileEncoding pop-up menu.

      Generally Unicode (UTF-8) is best for source files and Unicode(UTF-16) is best for .strings files.

  • The Add To Targets group allows you to add the file to one or moreof the targets currently defined in your project. If the checkboxnext to a target name is checked, the file is added to that targetwhen it is added to the project. When you add a file to a target,that file is built when the target is built. You can specify whichfiles are included in a target at any time; this option allows youto add the file to your project and to any necessary targets in onestep.

 

The remaining options apply only if the selection of files to addto the project includes one or more folders. Xcode can add foldersin two ways, as a group or by folder reference.

  • Group. Xcode recursively creates groupsfor the folder and its subfolders. Each of the files in thesefolders is added to the project and is placed in the group for theappropriate folder. If you choose to copy the files into theproject’s folder, Xcode duplicates the folder hierarchy. If youmove a file to the folder outside of Xcode, Xcode does not add thefile to the project.

    To add a folder as a group, select “Recursively create groups forany added folders.”

  • Folder Reference. Xcode adds the folderitself to the project but not its contents. This is useful if youneed to manipulate the folder as a whole but not the individualitems within it. One example is a folder of help files that youedit outside of Xcode and that you want Xcode to move into theapplication’s Resources folder when you build the application.

    To add a folder as a folder reference, select “Create FolderReferences for any added folders.”

Each of your project’s targets specifies the frameworks andlibraries against which its source files are linked. You can linkagainst standard libraries or external libraries. Standardlibraries or frameworks are those provided by the active SDK.External libraries or frameworks are those not provided by theactive SDK.

To add a library to a target:

  1. Open the Info window for the appropriate target and clickGeneral.

    The Linked Libraries list in the General pane lists the librariesagainst which Xcode links the target’s source files.

  2. Click the Add (+) button below the Linked Libraries list.

  3. Choose the library to add.

    To add a standard library, choose the library from the dialog.

    The dialog displays libraries and frameworks that belong to thetarget’s Base SDK build setting, which is normally defined at theproject level in the General pane of the Project Infowindow.

    To add an external library, click Add Other.

    After choosing an external library, Xcode presents the same optionsdescribed in adding Files and groups. Thefollowing options apply to external libraries:

    • The Reference Type menu in the dialog specifies how the location ofthe framework is stored.

    • The Add to Targets group box allows you to add the library to oneor more of the targets currently defined in your project. If thecheckbox next to a target name is checked, the library is alsoincluded in that target when it is added to the project.

    • The Text Encoding menu specifies the encoding used for the files ina framework. 

     When using external libraries, you must ensureXcode can locate the appropriate headers using the Header SearchPaths build setting(貌似同时也要设置Library SearchPaths成该外部库的路径).  Allheaders in your project are automatically accessible to your sourcecode. You can also specify additional search paths at which to findheaders using the Header Search Paths (HEADER_SEARCH_PATHS)build setting.  Notethat you do not have to add headers to your target to include themin your source code. You should add header files to your target—aspart of the Copy Header Files build phase—only if they are embeddedin your product, as with a framework. Bydefault, Xcode searches user paths before system paths. This meansthat, by default, your project headers have precedence over systemheaders. Thus, if your project defines a header filenamed String.h,source code in your project thatincludes String.h incorporatesyour project’s version of the header, not the system version. Youcan override this behavior by turning off the Always Search UserPaths (ALWAYS_SEARCH_USER_PATHS)build setting. WhenAlways Search User Paths is inactive, project headers can beincorporated into translation units only by surrounding the headerfilename with quotation marks. (A translationunit is a single source file with itsimported/included files). (A translation unit is a source file withits imported/included header files.) Forexample, #include"String.h" incorporatesthe String.h headerfile defined in the project into generated translation unit.Furthermore, system headers can be incorporated into translationunits only by surrounding the header filename with angle brackets.For example, #include incorporatesthe String.h systemheader file into the generated translation unit.

    Xcode defines a number of build settings for specifying generalsearch paths for files and frameworks used by targets in yourproject. These build settings are:

    • Header Search Paths (HEADER_SEARCH_PATHS)

      This is a list of paths to folders to be searched by the compilerfor included or imported header files when compiling C,Objective-C, C++, or Objective-C++ source files.

    • Library Search Paths (LIBRARY_SEARCH_PATHS)

      This is a list of paths to folders to be searched by the linker forstatic and dynamic libraries used by the product.

    • Framework Search Paths (FRAMEWORK_SEARCH_PATHS)

      This is a list of paths to folders containing frameworks to besearched by the compiler for both included or imported header fileswhen compiling C, Objective-C, C++, or Objective-C++, and by thelinker for frameworks used by the product.

    • Rez Search Paths (REZ_SEARCH_PATHS)

      This is a list of paths to search for files included by CarbonResource Manager resources and compiled with the Rez tool.

    Xcode supports recursive searchpaths. For each path that you enter in one of these search pathbuild settings, you can specify that Xcode search the directory atthat path, as well as any subdirectories that directorycontains.

     

    Xcode performs a breadth-first search of the directory structure atthe search path, following any symbolic links. Xcode searcheslocations in the order in which they appear in the search pathstable, from top to bottom. It stops when it finds the firstmatching item, so if you have multiple files or libraries of thesame name at the locations specified by a set of search paths,Xcode uses the first one it finds.

    Note that adding very deep directory structures to a list ofrecursive search paths can increase your project’s build time. Themaximum number of paths that Xcode expands a single recursivesearch path to is 1024.

    4. Choose whether the library is required or optional.

    Required libraries must be present on the host computer for theproduct to load. Optional or weak-linked libraries may or may notbe present for the product to load; however, before accessing anyof the library’s symbols at runtime, you must ensure that theoptional library is present on the host.

     

    In addition to file, framework, and folder references, Xcodeprojects can contain a cross-project reference; that is, they canrefer to another project outside of the current one. It is notalways feasible or desirable to keep all related targets andproducts in a single project. However, you may still need toreference targets or products that reside in a different project.For example, you may have several applications that rely on acommon framework that resides in a different project. In this case,you can add a reference to the project containing the framework tothe project containing the application. This reference, calleda cross-projectreference, lets you access the targets and products of thereferenced project from your current project.

    To create a reference to another project, choose Project> Add to Project and select the project package(the .xcodeproj filepackage) of the project you wish to reference. (You may also dragthe project group in the Groups & Files list ofanother project or a project package in the Finder to the currentproject’s project group.) Xcode adds a reference to the sourcegroup for your current project, visible in the Groups& Files list. The project reference is identifiedby the Xcode project icon. Clicking the disclosure triangle next tothe project reference shows the product references that the otherproject contains. These product references can be added to targetsin the current project.

    You can relate targets in the current project to targets in thereferenced project by creating a target dependency. You can add adependency on a target in the referenced project in the same waythat you would add a dependency to a target within the sameproject.

    For projects that use cross-project references, you should use acommon build location; doing so ensures that Xcode canautomatically locate products created by targets in thoseprojects.

    cross-project reference的例子:

    一个是产生静态库的工程A,另一个是需要使用静态库的工程B。

    将静态库的Xcode项目加入到当前项目,


    右击Targets下本项目,添加到静态库项目的关联。


    在项目下,扩展静态库项目,拖动xxxx.a到Targets下的Link Binary WithLibraries。


    这样你就可以从当前项目下,双击静态库的项目来打开和修改静态库的代码了。

    11.What's the Xcode Cache?

     

    Xcode places its persistent caches in a secure location in yourfile system. You can get to this location usingthe getconf command:

     

    > cd `getconf DARWIN_USER_CACHE_DIR`
    

    This location is known as .

    If the Xcode cache grows too much, you can delete it using theEmpty Caches command. Keep in mind that the Xcode cache may includeprecompiled headers for your projects, and building those projectsmay take longer after the cache has been emptied.

    To empty the Xcode persistent cache, choose Xcode >Empty Caches.

    12.Search text in a file

    To search for text in a file that you have open in the editor,choose Edit > Find > Find.

    You can ust RegularExpression to searche for text matching the regularexpression in the search field.Xcode uses the ICU library forregular expression matching (see http://icu-project.org/userguide).

    There is an option named Wraparound. Select this option to search thewhole file; otherwise, Xcode searches from the current location ofthe insertion point to the end of the file.

    13.Search in a project

     

    When replacing text using regularexpressions, instead of the dollar ($)sign to specify references to capture-group text, use the slash(\)character.

    For example, to specify capture group 0 in the replacement text,use \0,not $0.

    14.View the symbols in your project

     When you select the Project Symbols group for aproject, you get a view about all your symbols inyour project.

    15.View your class hierarchy in the class browser

    If you are programming in an object-oriented language, you can viewthe class hierarchy of your project using the Xcode class browser.To open the class browser, choose Project > ClassBrowser. You can also open the class browser by selecting a symbolin the Project Symbols smart group and choosing View> Reveal in Class Browser. 

    16.Per-File Compiler Flags

     

    The build system provides facilitiesfor customizing the build process of source files of particulartypes. It includes the Other C Flags (OTHER_CFLAGS),Other C++ Flags (OTHER_CPLUSPLUSFLAGS),Other Warning Flags (WARNING_CFLAGS),and Preprocessor Macros (GCC_PREPROCESSOR_DEFINITIONS)build settings, among many others, to customize the invocation ofthe compiler when processing C-based source files. However,sometimes it’s necessary to specify compiler flags for particularfiles. For example, in a project that treats warnings as errors ingeneral, you may have a set of cross-platform source files whosewarnings you want the compiler to ignore.

    To view the compiler flags for a file:

    1. Select the source file in the Groups & Fileslist.

    2. Choose File > Get Info to open the File Infowindow.

    3. Display the Build pane .


    TheBuild pane of the File Info window is available only for filescontaining source code.

    In the Additional Compiler Flags for Target field, you can enterany compiler flags you want to assign to the file. Use spaces toseparate flags.

    You can use multiple selection to assign compiler flags to a subsetof the files in a target.

    For each target that a file belongs to, Xcode maintains a separatelist of compiler flags assigned to the file. To specify compilerflags for use with a file when it is built as part of a particulartarget, select the file from the appropriate build phase in thattarget and open the File Info window, as described earlier. If youopen an Info window for the same file from any other group in theproject window, Xcode assumes you want to assign compiler flags tothe file in the active target; thus, the Build pane is availableonly if the file is part of the active target.The build systemdoesn’t validate the flags you add; that is, it doesn’t testwhether the compiler actually supports the options you add, and itdoesn’t investigate whether the options you add conflict with theones it generates. If you add a group of compiler options for afile that produce build errors or warnings, you should remove allthe options you added and add them back one at a time, making surethe file compiles after you add each option, to determine whichoption is not supported. You should also consult the tool’sdocumentation to learn about possible conflicts.The additionalcompiler options specified for a file are always used when the fileis processed as part of a build.You can use file compiler optionsto negate compiler options generated by the build system. Forexample, you may have turned on the Unused Variables build settingfor your target, but want to deactivate unused-variable warningsfor only one of the target’s source files.

    To negate the effect of a build setting on a particularfile:

    1. Clean and build the target to ensure there are no build errors orwarnings.

    2. Using the build-setting descriptions in the Build pane of theproject or target Info window, determine the compiler option thatcorresponds to the build setting in question.

    3.Addthe negative form of the compiler option, by prepending itwith -Wno-,to the compiler flags of the file whose build-setting effect youwant to suppress. For example, to negatethe -Wunused-variable compileroption (which the build system generates when Unused Variables isturned on), add -Wno-unused-variable tothe file’s compiler options. 4.Buildthe product. If there are build errors, the compiler option justadded may not be supported by the compiler.
    17.Build atarget
    The first time you build a target, the build system creates all theintermediate files, such as object files, needed to build theproduct. In subsequent builds of the same target, the build systemprocesses only the files that have changed since the target’sprevious build. For example, if the only change to the target sincethe last time it was built was a minor edit to a single source codefile, the build system recompiles that file and relinks the objectfiles to create the finished product. That is, changes to thecontents of the file and changes to build settings that affect theway a source file is built cause the build system to rebuild thefile. Ifyou want to force Xcode to rebuild a build file the next time youbuild the target, you can touch the file, to mark it as changed.Similarly, if Xcode has marked the file as needing to be rebuilt,but you know you haven't made any substantive changes to the file,you can untouch the file; the build system does not rebuild thefile the next time the target is built. To touch or untouch a file,click in the build status column (indicated by the hammer icon)next to that file in the detail view. If a checkmark appears inthis column, the file is rebuilt the next time you build a targetto which it belongs. Keep in mind that this feature does not workwith all build systems.
    18.Build with xcodebuild

    In addition to building your product from the Xcode application,you can use xcodebuild tobuild a target from the command line. Building from the commandline gives you additional flexibility compared to building fromwithin the Xcode application that may be useful in certaincircumstances. For example, using xcodebuild,you can create a script that automatically builds your product at aspecific time.

    The xcodebuild toolreads your .xcodeproj projectpackage and uses the target information it finds there to build aproduct.

    To build a target using xcodebuild,use the cd commandto change to your project’s directory and invokethe xcodebuild commandwith the appropriate options. The project’s directory contains yourproject’s .xcodeproj bundle.For example, if your project is in ~me/Projects/MyProj,enter cd~me/Projects/MyProj.


    19.Manage targets

    When you create a project from one of the Xcode project templates,Xcode automatically creates a target for you. If, however, yourproject needs to contain more than one target—usually because youare creating more than one product—you can also add targets to anexisting project.If you are adding targets to your project,chances are you’ve already made a number of decisions about producttype, programming language, and framework. Xcode provides a numberof targettemplates to support your choices. Theselection of target templates is similar to the selection ofproject templates. The target specifies the target’s product type,a list of default build phases, and default definitions for somebuild settings. A target template typically includes all buildsettings and build phases required to build an instance of thespecified product. Unlike the project templates provided by Xcode,the target templates do not specify any default files; you must addfiles to the target yourself.

     

    To create a target and add it to anexisting project:

    1. Choose Project> New Target.

      Xcode displays the New Target assistant, which lets you choose froma number of possible target templates. Each target templatecorresponds to a particular type of product, such as an applicationor loadable bundle.

    2. Select one of the templates and click Next.

    3. Enter the name of the target.

      If more than one project is open, you can choose which project toadd the target to from the Add to Project pop-up menu.

    4. Click Finish.

      Xcode creates a target configured for the specified product type.Xcode also creates a reference to the target’s product and placesit in your project, although the product does not exist on the filesystem until you build the target.

     

    In addition to some targettemplates, Xcode defines a handful of target templates that do notnecessarily correspond to a particular product type. These targetsare known as specialtargets and can be used to:

    • Build a group of targets together

    • Copy files to a specific file system location

    • Build a product using an external build system

    • Run a shell script

    These are the special target types:

    • AggregateTarget

      Xcode defines a special type of target that lets you build a groupof targets at once, even if those targets do not depend on eachother. An aggregate target has no associated product and no buildrules. Instead, an aggregate target depends on each of the targetsyou want to build together. For example, you may have a group ofproducts that you want to build together. You would create anaggregate target and make it depend on each of the product targets.To build all the products, just build the aggregate target.

      An aggregate target may contain a custom Run Script build phase ora Copy Files build phase, but it cannot contain any other buildphases. Any build settings that the aggregate target contains arenot interpreted but are passed to the build phases that the targetcontains.

    • CopyFiles Target

      A Copy Files target is an aggregate target that contains only onebuild phase, a Copy Files build phase. Building a Copy Files targetsimply copies the associated files to the specified destination inthe file system. Copy Files targets are useful if you have custombuild steps that require files that are not specific to any othertargets to be copied. While Copy Files build phases allow you toadd a step to the build process for a single target that copiesfiles in that target, a Copy Files target lets you copy files thatare not specific to any one target. For example, if your projecthas several targets that require the same files to be installed ata particular location, you can use a Copy Files target to copy thefiles, and make each of the other targets depend upon the CopyFiles target. 

    • ExternalTarget

      Xcode allows you to create targets that do not use the native Xcodebuild system but instead use an external build tool that youspecify. For example, if you have an existing project with amakefile, you can use an external target torun make andbuild the product.

      An external target creates a product but does not contain buildphases. Instead, it calls a build tool in a directory. With anexternal target, you can take full advantage of the Xcode texteditor, class browser, and source-level debugger. However, manyXcode features—such as Fix and Continue—rely on the buildinformation maintained by Xcode for targets using the native buildsystem. As a result, these are not available to an external target.Furthermore, you must maintain your custom build system yourself.For instance, if you need to add files to an external target builtusing make,you must edit the makefile yourself. 

    • ShellScript Target

      A Shell Script target is an aggregate target that contains only onebuild phase, a Run Script build phase. Building a Shell Scripttarget simply runs the associated shell script. Shell Scripttargets are useful if you need to perform custom build steps. WhileRun Script build phases allow you to add custom steps to the buildprocess for a single target, a Shell Script target lets you definea custom build operation that you can use with many targets. Forexample, if your project has several targets that use the filesgenerated by a Shell Script target, you can make each of thosetargets depend upon the Shell Script target.

     

    There are two main reasons you mightneed to duplicate a target: You require two targets that are verysimilar but contain slight differences in the files or build phasesthat they include, or you have a complicated set of options thatyou build with and would prefer to simply start with a copy of atarget that already contains those build settings.

    Xcode allows you to duplicate a target, creating a copy thatcontains the same files, build phases, dependencies and buildconfiguration definitions of the original.

    To create a copy of a target:

    1. Select the target you want to copy in the Groups &Files list.

    2. Choose one of these:

      • Edit > Duplicate

      • Groups & Files list shortcut menu >Duplicate

     

    When your project contains targetsthat are no longer in use, you may want to remove them to reduceclutter.

    To remove a target from a project:

    1. Select the target to delete in the Groups & Fileslist.

    2. Press the Delete key or choose:

      • Edit > Delete.

    When you delete a target, Xcode also deletes the product referencefor the product created by that target and removes any dependencieson the deleted target.

     

    In a complex project, you may haveseveral targets that create a number of related products.Frequently, these targets need to be built in a specific order.Returning to the example of the client-server software package ,you see that the client application, server application, andcommand-line tool targets each link to the private frameworkcreated by another target in the same project.

    Before the application and command-line tool targets can be built,the framework target must be built. Because they require theprivate framework in order to build, each of the application andcommand-line tool targets is said to depend upon the target thatcreates the framework. You can usea targetdependency to ensure that Xcode buildstargets in the proper order; in this example, you would add adependency upon the framework target to each of the application andcommand-line tool targets.

    However, the applications and command-line tool in theclient-server package must still be built individually. None ofthese targets requires the product created by any target other thanthe framework target. Xcode provides another mechanism for groupingtargets that you want to build together but that are otherwiseunrelated; this is an aggregatetarget . This section shows how to add atarget dependency and create an aggregate target, and gives anexample of how you can use these tools to organize a softwaredevelopment effort with multiple products and projects.

     

    Creating AggregateTargets

    To build several targets together, even if they aren’t dependent oneach other, create an aggregatetarget. An aggregatetarget does not produce a product itselfand it does not contain build rules or information property listentries. Instead it exists so that you can make it dependent onother targets. When you build the aggregate target, the buildsystem builds the targets it depends on sequentially or inparallel. To learn about building targets concurrently,see "Buildingin Parallel" .

    To create an aggregate target:

    1. Choose Project > New Target.

    2. Select Aggregate from the New Target Assistant.

    For each target you want to build with this aggregate target, add atarget dependency to the aggregate target.

     

    Adding Target Dependencies

    When you build a target (target A) with a dependency upon anothertarget (target B), Xcode makes sure that target B is built and upto date before building target A. That way, you can be sure thatwhen target A needs the product created by target B, target B isbuilt before target A. In addition, if there are errors buildingtarget B, Xcode doesn’t build target A.

    You can view and modify a target’s dependencies in two ways:

    • In the General pane of the target editor. The Direct Dependencieslist shows the targets upon which the current target depends.

      To add a target dependency, click the plus-sign button. (For theplus sign button to be available, the project must contain orreference more than one target.) The list of targets shown includesall the other targets in the current project, as well as thetargets in any referenced projects. Targets in referenced projectsare grouped according to the project to which theybelong. You may also drag a target from theTargets group to the Direct Dependencies list.

      To remove a target dependency, select it in the list and click theminus button.

    • In the Groups & Files list. Open the Targets group;the targets that the current target depends on are listed beforethe build phases in the target. You can make the current targetdepend on another target by dragging that target to the currenttarget in the Groups & Files list.

     

    Removing Target Dependencies

    To remove a target dependency:

    1. Select the target to modify in the Groups & Fileslist.

    2. Open the target editor and display the General pane.

    3. In the Direct Dependencies list, select the target dependency todelete.

    4. Click the minus (-) button.


    20.Manage target files

    When you add files to a project, you can have Xcode also add thosefiles to one or more targets. This is the easiest way to add filesto a target. However, you may have existing files in your projectthat you wish to add to a target, or find that you no longer need atarget file.

     

    Header files have a special purpose in a target: They publish theprogramming interface to symbols defined or implemented in thetarget’s implementation files. Implementation files in a target useheader files to gain access to symbols defined in otherimplementation files. But implementation files may also requireaccess to the programming interface to frameworks, libraries, orplug-ins that are not part of the project.

    When you define a target, you may implement symbols you want tomake public to clients of the target’s product. But, to make yourproduct easy to use (and to keep implementation details hidden),you may want to keep many of its symbols inaccessible to clients ofyour product. Also, if you develop products to be used both by thedevelopment team and by end users, you may need to publishinterfaces to symbols that must be used only by other team membersbut that end users must not use. You use a headerfile’s role withinits target to specify the purpose of the header file.

    To set the role of header files in a target:

    1. Select the target containing the header files whose role you wantto set.

    2. Select the target’s Copy Headers build phase.

    3. Choose the desired role for each header file from the Role columnin the detail view.

    There are three roles available: publicprivate,and project

    public:The header file is included as part of the build product.Its location is specified by the Public Headers Folder Path(PUBLIC_HEADERS_FOLDER_PATH) build setting. You should publishas public onlyinterfaces that are finalized and meant to be used by yourproduct’s end users.

    private:The header file is included as part of the build product.Its location is specified by the Private Headers Folder Path(PRIVATE_HEADERS_FOLDER_PATH) build setting. You should publishas private interfacesthat you don’t intend to be used by end users or that are in earlystages of development.

    project:The header file is available only for use by implementationfiles in the current project. This header file is not included aspart of the built product.


    21.Build phases

    buildphase represents a task to be performedon a set of files. Each build phase specializes in a specific kindof file, such as header files, source files, resource files, andframeworks and libraries. Each build phase also performs specificoperations on the files associated with it. That way, changes inthe way files of the same kind are processed can be made bycustomizing the operations that the build phaseperforms.

     As you add files to a project, Xcode associatesthem with the appropriate build phase, based on the files’ type(specified by each file’sextension). 

     Build phases available inXcode:

     

    Build phase

    Description

    Copy Headers

    Installs header files with public or private rolesin the appropriate locations in the product. 

    Copy Bundle Resources, Build Java Resources

    Installs files by copying the associated files from the project tothe Resources directoryin the product.

    Copy Files

    Installs files by copying the associated files from the project toa location in the product or to a specific location in the targetfile system, such as /Library/Frameworks or/Library/ApplicationSupport.

    Compile Sources

    Compiles source files into object files using a predefined tool, atool you specify, or a build-rule script.

    Run Script

    Executes a shell script. You can use any scripting language whosescripts you can execute from the command line, such as AppleScript,Perl, Python, Ruby, and so on.

    Link Binary With Libraries

    Links object files with frameworks and libraries to produce abinary file.

    Build ResourceManager Resources

    Compiles .r filesinto resources that go into a separate resource file or into theexecutable's resource fork.

    Compile AppleScripts

    Compiles .applescript filesand places the resulting .scpt filesin the product’sResources/Scripts directory.

     Input files and output files of buildphases:

     

    Build phase

    Inputs

    Outputs

    Copy Headers

    .h files

    Copies in appropriate locations in the product.

    Compile Sources

    .c.m.y.l,among other types of source files

    .o files intarget’s build directory.

    Link Binary With Libraries

    .framework.dylib,and the.o filesin the target’s build directory

    Binary file, framework, or library in product destinationdirectory.

    Copy Bundle Resources

    .nib files, .strings files,image files, and others

    Copies in the product’s Resources directory.

    Build ResourceManager Resources

    .r, and .rsrc files

    Resource (.rsrc)files in the product’s Resourcesdirectory.

    Compile AppleScripts

    .applescript files

    AppleScript script (.scpt)files in the product’sResources/Scripts directory.

    Build phases processing order:

    The order in which the build systemexecutes build phases is important because some build phasesproduce files that are part of the inputs of other build phases.Therefore, the former must be executed before the latter. In nativetargets, dependencies between build phases determine the order ofexecution. 

    In some cases, a build phase inherently includes the outputs ofother build phases as its inputs. For example, the outputs(.o files)of the Compile Sources build phase are part of the inputs of theLink Binary With Libraries build phase. This makes the CompileSources build phase an antecedent of the Link Binary With Librariesbuild phase. Therefore, the order in which build phases areexecuted in a target depends on their inputs andoutputs.

    Most build phases have their inputs and outputs defined implicitly.However, Run Script build phases may have neither. Here, the buildsystem tries to run the associated script in the order specifiedwithin the target, but the actual point in the build process atwhich the script is run is undetermined. If you assign either inputor output files to a Run Script build phase, the script’s point ofexecution in the build process is determined by other targetshaving the build phase’s outputs as their inputs, or the inputs ofthe build phase being the outputs of other build phases.Forexample, regardless ofthe order of the Compile Sources and the Link Binary With Librariesbuild phases in the target, the Compile Sources build phase isexecuted before the Link Binary With Libraries build phase. This isbecause the inputs to the Link Binary With Libraries build phaserely on output from the Compile Sources buildphase.In the Compile Sourcesbuild phase, the build system determines the order in which filesare processed through the inputs and outputs of the target’s buildrules, in a similar way in which the order of build phases isdetermined.

    Typically, there is no need to change the order of build phases ina target; the default arrangement works for the majority of cases.If, however, you find that you need to change the position of abuild phase—for example, when adding custom build phases to aJam-based target—you can reorder a build phase by dragging the iconfor the build phase to its new location in thetarget.

    Add and delete build phases:

     

    To add a build phase:

    1. (Optional) Select the target to which you want to add the buildphase. Otherwise, Xcode adds the build phase to the activetarget.

    2. Choose a build phase from:

      • Project > New Build Phase

    Xcode adds the new build phase after the currently selected buildphase, or, if no build phase is selected, adds it as the last buildphase in the target. Several types of build phases can appear onlyonce in a target; for example, there can be only one CompileSources build phase. However, a target can contain multipleinstances of the Copy Files and Run Script build phases.

    To delete a build phase, select it in the Groups &Files list and press Delete, or choose Edit >Delete. Deleting a build phase does not delete the files in thebuild phase from the project or from the file system.

    Add files to a buildphase:

     

    When you add a file to a project,Xcode lets you choose whether to also add the file to any targetsin the project. When you add files to a target this way, Xcodeautomatically assigns the files to build phases, based on eachfile’s type.

    To view the inputs to a particular build phase, you can:

    • Select the build phase in the Groups & Files list.The files assigned to the build phase are displayed in the detailview.

    • Open the build phase in the Groups & Fileslist.

    Intermediate files—files generated by Xcode in other buildphases—are not listed. Xcode handles these intermediate filesautomatically.

    If the default file placement is not sufficient for your needs, youcan drag the file or files from their current build phase to thenew build phase. You can also drag existing files from the projectgroup to the appropriate build phase in the Groups& Files list. To remove a file from a build phase,select the file and press Delete.

    Compile sources build phase:

     

    The Compile Sources build phase is one of the most easilycustomized build phases (the other one being the Run Script buildphase). The reason is that this build phase must handle a widevariety of file types. Xcode is preconfigured to process severaltypes of source files, but you may have to compile source filesthat Xcode doesn’t know about.

    The feature that makes the Compile Sources build phase so flexibleis its support of buildrules(后面会讲到).

    Copy files build phase:

     

    A Copy Files build phase allows you to copy files and resources ofany type to specific locations as part of the build process. Itcomplements the build phases that copy specific types of files. Anexample is the Copy Headers build phase, which deals only withheader files. You can have as many Copy Files build phases as youneed in a target.

    For example, using a Copy Files build phase, you can copy fontsto/Library/Fonts.Or, if you’re developing a plug-in, a Copy Files build phase cancopy the generated plug-in to the appropriate location. You canhave as many Copy Files build phases in a target as you need.

    To create a Copy Files build phase:

    1. In the project window, open the target to which you want to add thebuild phase, and select the build phase after which to add the newbuild phase.

    2. Choose Project > New Build Phase >New Copy Files Build Phase. Xcode adds the new Copy Files buildphase after the build phase selected in the Groups& Files list.

    3. Drag the files you want to copy from the Groups &Files list to the Copy Files build phase.

    To configure the new Copy Files build phase, select it and open theCopy Files build phase editor.Together, the Destination pop-up menu and thePath field specify the location to which Xcode copies the files inthe Copy Files build phase. The Destination pop-up menu lets youchoose from a number of standardlocations. Tablebelow shows the destination-location namesyou can choose in a Copy Files build phase for an applicationcalled MyApp and the resulting destination path. All the options,except Absolute Path and Products Directory, specify paths insidethe generated bundle.

     

    Destination name

    Destination path

    Absolute Path

    Anywhere.

    Wrapper

    MyApp.app

    Executables

    MyApp.app/Contents/MacOS

    Resources

    MyApp.app/Contents/Resources

    Java Resources

    MyApp.app/Contents/Resources/Java

    Frameworks

    MyApp.app/Contents/Frameworks

    Shared Frameworks

    MyApp.app/Contents/SharedFrameworks

    Shared Support

    MyApp.app/Contents/SharedSupport

    Plug-ins

    MyApp.app/Contents/PlugIns

    Products Directory

    The directory in which Xcode places the project’s builtproducts. 

     

    The Path field specifies the path,relative to the location specified in the Destination pop-up menu,to the target directory. If you choose Absolute Path from the menu,the Path field must contain the complete path to the destinationdirectory for the files.

    The “Copy only when installing” option lets you specify whether thebuild phase copies the files only in installbuilds of the product. 

    Run script build phase:

    Environment variables accessible from a Run Script build phase:

    xcode相关的一些知识(一)_第1张图片

    A Run Script build phase lets you execute any commands you need toperform a task. You can archive filesusing tar,send mail, write messages to a log file, execute AppleScriptscripts, and so on. You can use any of the shell languagesavailable in your system. And you can have any number of Run Scriptbuild phases in a target.

     

    To create a Run Script build phase:

    1. In the Groups & Files list, open the target towhich you want to add the build phase, and select an existing buildphase.

    2. Choose Project > New Build Phase >New Shell Script Build Phase.

    To configure the new Run Script build phase, open the Run Scriptbuild phase Info window.

     

    The Run Script build phase editor contains these fields:

    • Shell. Specifies the path to theappropriate shell.

    • Script. Specifies the script itself. Youcan also enter a script that invokes a script stored elsewhere to,for example, avoid storing an often-changed script in the projectfile.

      A Run Script build phase with the following entries for Shell andScript executes a script called MyScript.sh storedin a directory called Build_Scripts inthe project directory.

      Shell:

      /bin/sh

      Script:

      $(SRCROOT)/Build_Scripts/MyScript.sh

    • Run script only when installing. Runs thescript only during install builds, that is, when usingthe install optionof xcodebuild orwhen the build settings Deployment Location (DEPLOYMENT_LOCATION)and Deployment Postprocessing (DEPLOYMENT_POSTPROCESSING) areon.

    • Show environment variables in buildlog. Lists the build system’s environmentvariables in the build log.

    • Input Files. Specifies the names of theinput files the script operates on.

    • Output Files. Specifies the files thatthe script produces.

      In these two tables, file paths are interpreted relative to theproject directory.

    Xcode uses the input and output files to determine whether to runthe script and to determine the order in which the script isexecuted. Specifying input and output files ensures that Xcode runsthe script only when the modification date of any of the inputfiles is later than the modification date of any of the outputfiles (reducing the time it takes to build your product), and thatthe files the script produces are included in the dependencyanalysis the build system performs before building your product. Ifyou provide no outputs, Xcode runs the script every time you buildthe target.

    After the script terminates, Xcode uses the script’s exit value todetermine whether to continue the build. When the script exits witha nonzero exit value, Xcode stops the build. If you want to performother actions—such as writing to a log file—in the event of a buildfailure, you must perform the appropriate action in the script.  

  4. from: http://blog.sina.com.cn/s/blog_777694e90100y44h.html


你可能感兴趣的:(IOS-深入,ourios)