设为首页 - 加入收藏 焦点技术网
热搜:java
当前位置:首页 >

xcode相关的一些知识(二)

2013-06-18 17:46:00.0 IOS-深入 ios  
导读:22.Build rulesBuild 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 phas...。。。

22.Build rules

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:

  • System build rules. System build rulesare predefined and unmodifiable, although you can override them.They include rules for processing C-based, Assembler, and Rezsource files. System rules are the same for all targets in aproject.

  • Target-specific buildrules. Target-specific build rules arecustom rules that you have defined for a particular target.

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 /bin/sh.However, you can specify any script interpreter byentering #! asthe first line of the script. When you use a build-rule script, youmust specify the files the script produces as the build rule’soutput files

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 .def suffix,you specify [A-Z]*.def asthe pattern.

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:

  • “using” > “Custom script”

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 .abcdef.Also suppose that the build rule script producesa .c filefor each .abcdef fileand that the generated .c filesare placed in the default directory for intermediate files. In thiscase, the output-files specification could look likethis:

 

$(DERIVED_FILES_DIR)/$(INPUT_FILE_BASE).c

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. Thegenerated files are automatically fed back to the rule-processingengine. For example, continuing the .abcdefexamplerule, Xcode processes the .c filesthe script produces using the rule thatprocesses .c files.

Xcode runs build rule scripts with the currentworking directory set to the project directory. Thisbehavior letsyou access specific source files by using their project-relativepaths.


23.Build Settings

 

A build setting in Xcode has two parts: The name and thespecification. The buildsetting name identifies the build settingand can be used within other settings; in that sense, it is similarto the names of environment variables in a command shell.The buildsetting specification is the informationXcode uses to determine the value of the build setting at buildtime. A build setting may also have a display name,or buildsetting title, which is used to display the build settingin the Xcode user interface.

A build setting

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 (GCC_GENERATE_DEBUGGING_SYMBOLS)build setting. When Xcode creates the gcccommand-lineinvocation to compile a source file, it evaluates compiler buildsettings (such as Generate Debug Symbols) to construct the argumentlist.

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 targetlayer; however, it is important to understand the variouslayers from which build setting values can be derived.

In addition to build settings, you canset per-filecompiler flags that the build system useswhen creating tool invocations. With them you can change how a fileis compiled without affecting any other files in theproject. 

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,  project_name isirrelevant to the build system and doesn’t override the value ofthe PROJECT_NAME buildsetting.

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 similartoThename of this target's product is $(PRODUCT_NAME).

 

In addition to the build settings provided by Xcode, you canadd user-definedbuild settings to a project. Auser-defined build setting is one that is not defined by the buildsystem. You can add them at the command-line, target, project andenvironment levels. You can reference user-defined build settingsin build setting specifications, and scripts in Run Script buildphases. User-defined build settings don’t have a title.

The following list describes some circumstances in which you mayneed to add user-defined build settings to a project:

  • To modify the value of build settings that are not displayed in theXcode application

  • To specify a value that can be used by several build settings indifferent layers 

  • To define a build setting you want to use in Run Script build phasescripts or a build-rule script


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(GCC_OPTIMIZATION_LEVEL)build setting. Note that the Release build configuration doesn’tturn on Deployment Location (DEPLOYMENT_LOCATION);therefore, the product is not copied to the location where it wouldbe installed on a user’s system. It also doesn’t turn on DeploymentPostprocessing (DEPLOYMENT_POSTPROCESSING),which specifies whether to strip binaries and whether to set theirpermissions to standard values.


25.Linking

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:

  • Executable. Executable files are binariescontaining the core logic of a program. Specifically, they containthe program’s entry point, which in C-based programs isthe main function.Once loaded, however, these programs may require the loading ofdynamic libraries to perform functionality they don’t implement. Togenerate an executable file, a target may include static librariesdirectly, or dynamic libraries, either directly or throughframeworks. Executable binaries don’t have an extension; forexample, MyProgram).

  • Bundle. Bundles are executable files thatcan be loaded at runtime by other products. Plug-ins areimplemented using bundles. The term bundle inthis context refers to the binary itself, not to a structuredhierarchy. Bundles have the .bundle extension;for example, MyBundle.bundle.

  • Static Library. Static libraries (alsoknown as archives) are repositories of code that other programsincorporate as their own, which produces larger images. The codeobtained from the static library is loaded at the same time theproduct is loaded. These products, however, do not benefit fromimprovements made in the static library after they are built. Toget new functionality, the products must be rebuilt with theimproved version of the static library. Static libraries havethe .a extension;for example, MyLibrary.a.

  • Dynamic Library. Dynamic librariescontain code that programs load at runtime. The images of productsthat use dynamic libraries are smaller because they don’tincorporate the library’s code into their own. Instead, theseproducts load the appropriate library at runtime. Using dynamiclibraries, products can automatically take advantage of featuresintroduced in versions of the libraries that were not availablewhen the products were built. That is, a program can take advantageof new functionality without being rebuilt. Dynamic libraries havethe .dylib extension; for example, libMyLibrary.1.0.dylib.

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 Cocoa.h systemheader, which in turn includes a number of other headers. When youbuild a target, the compiler spends a great deal of time repeatedlyprocessing the same headers.

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 SHARED_PRECOMPS_DIR (PrecompiledHeaders Cache Path) build setting. It also generates—as needed—avariant for each combination of source header and compiler flags.For example, you may have per-file compiler flags set for some ofthe files in the target you are building. Xcode will create avariant of the precompiled header by precompiling the prefix headerwith the set of compiler flags derived from the target and theindividual source file. As Xcode invokes the compiler to processeach source file in your target, the compiler searches theprecompiled header directory for a precompiled header variantmatching the language and compiler flags for the current compile.Xcode uses the first precompiled header variant that is valid forthe compilation.

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 #include and #define statementsused by the files in your target.

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:

 

#ifdef __OBJC__
    #import 
    #endif
    #define MY_CUSTOM_MACRO 1
    #include "MyCommonHeaderContainingPlainC.h"

 

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:

  • GCC_PREFIX_HEADER (Prefix Header). Changethe value of this build setting to the project-relative path of theprefix header file. If you have a precompiled header file from anexisting project, set the prefix header path to the path to thatfile.

  • GCC_PRECOMPILE_PREFIX_HEADER (PrecompilePrefix Header). Make sure that this option is turned on. Acheckmark is present in the Value column if this option isenabled.

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 GCC_PFE_FILE_C_DIALECTS (CDialects to Precompile) build setting lets you explicitly specifythe C dialects for which Xcode should produce versions of theprecompiled header.

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:

  • Touching the prefix file.

  • Cleaning the target. By default, cleaning a target removes all ofthe intermediate and product files generated for that target by thebuild system, including any precompiled headers. The next time youbuild the target, Xcode rebuilds the target's precompiled headerfiles, along with all other files in thetarget. 

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 distributedbuilds. When you use distributed builds, Xcode distributesas many compilation tasks among the computers available for thispurpose within a network.

27. Dynamic Library(Shared Library) in iOS

Dynamic linking is forbidden if you want to deliver to the AppStore (apart of the Apple provided libraries and frameworks, ofcourse). Only static linking of external libraries is allowed byApple.Ifyou want to integrate code from a framework or dynamic library intoyour application, you should link that code statically into yourapplication’s executable file when building yourproject.Thereason is security: since a dynamic library can be loaded andunloaded at runtime you could download additional executable codeand load it (think plug-in). This could get compromised by a hackerand then having malicious code executing on your phone is a verybad thing. It would also make it possible to add unapprovedfeatures to an approved app. In short: in this environment, Appleconsiders dynamic linking to be a Pandoras box that must bestrictly controlled, otherwise it could compromisesecurity.(非越狱的机器无法访问第三方dylib,注意是第三方,程序会莫名崩溃。)

28.Framework 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.

 

Themost common kind of framework isthe dynamicallylinked framework. Only Apple can install these on an iOSdevice, so there's no point in building them.

staticallylinked framework is almost the same,except it gets linked to your binary at compile time, so there's noproblem using them.

How tocreate custom Framework?see https://github.com/kstenerud/iOS-Universal-Framework.This is a Xcode4 project template to build universal frameworks(arm6, arm7, and simulator) for iOS/iPhone.

(1) Installing the Template System

To install, run the install.sh scriptin either the "Real Framework" or "Fake Framework" dir (orboth).

Now restart Xcode and you'll see StaticiOSFramework (or FakeStatic iOS Framework)under Framework& Library when creating anew project.

To uninstall, run the uninstall.sh scriptand restart Xcode.

(2) Creating an iOS Framework Project\

  1. Start a new project.

  2. For the project type, choose StaticiOSFramework (or FakeStatic iOS Framework), which isunder Framework& Library.

  3. Optionally choose to include unit tests.

  4. Add your classes, resources, etc with your framework as thetarget.

  5. Any header files that need to be available to other projects mustbe declared public. To do so, go to BuildPhases in your framework target,expandCopyHeaders, then drag any header files you want to makepublic from the Project or Private sectionto the Public section.

(3)Building your iOS Framework

  1. Select your framework's scheme (any of its targets willdo).

  2. (optional) Set the "Run" configuration in the scheme editor (It'sset to Debug by default).

  3. Build the framework (both "iOS device" and "Simulator" destinationswill build the same universal binary, so it doesn't matter whichyou select).

  4. Select your framework under "Products", then show in Finder.

There will be two folders in the buildlocation: (yourframework).framework and (yourframework).embeddedframework

If your framework has only code, and no resources (like images,scripts, xibs, core data momd files, etc), you candistribute (yourframework).frameworkto your users and it will justwork.

If you have included resources in your framework,you MUST distribute (yourframework).embeddedframework.

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.

(4)Using an iOS Framework

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":

#import 


29. Group Types

 

The Groups & Files list contains two types ofgroups: staticgroups and smartgroups

Groups & Files list

Staticgroups organize your project’s sourcefiles, including header files, implementation files, frameworks,and other files. (Static groups are themselves grouped under theproject group, which is named after the project and is representedby the blue project icon.) A static group, identified by a yellowfolder icon, can contain any number of files and other staticgroups. Static groups help you organize the files in your projectinto manageable chunks. The project group is a static group thatcontains all the files, frameworks, libraries, and other resourcesincluded in your project.

 

Smart groups are subdivided into twotypes: built-in smart groups and custom smart groups.

30. Grouping files

group letsyou collect related files together. A static group lets you groupan arbitrary set of file, folder, and framework references in yourproject. A smart group, on the other hand, lets you group togetherfiles fitting a particular pattern or rule. 

(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.

Deleting Groups

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.

  • To remove a group and the project’s references to the files in thatgroup, select the group, and press Delete.

  • To remove a group and keep the files it contains, select the groupand choose Ungroup from its shortcut menu.

(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 .m or .c.When you make a change to your project that alters the set of filesmatching a smart group’s rule—for example, addinga .c file—thesmart group automatically updates to reflect the change. You do notneed to add files to a smart group yourself. In fact, Xcode doesnot allow you to drag files to a smart group.

 

Creating a Smart Group

To create a smart group, choose Project > New SmartGroup. Then choose one of the following options:

  • Simple Filter Smart Group. Creates asmart group that collects files whose names contain a specifiedstring.

  • Simple Regular Expression SmartGroup. Creates a smart group that uses aregular expression to specify the pattern that filenames mustfollow.

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 *.nib intheir name. The default Simple Regular Expression Smart Groupcollects all C, C++, Objective-C, Objective-C++, Java, andAppleScript implementation files in your project.

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:

  • Name field. The name of the smart group.By default, this is set to the type of the smart group, forexample, “Simple Filter Smart Group.”

  • Image. The icon used for the smart groupin the project window. The default image for a smart group is thepurple folder icon, but you can also use a custom image torepresent your smart group. To change the icon, click the Choosebutton and navigate to the image file to use.

  • Start From menu. Specifies the directoryfrom which the smart group starts its search for matching files; bydefault, this is the project folder. If the Recursively option isselected, the smart group also searches through subdirectories ofthat folder.

  • Using Pattern field. The actual patternthat files must match in order to be included in the smart group.As mentioned, this pattern can be either a simple string that thesmart group filters on or a regular expression, depending on thesetting of the options beneath the field. For examples of each ofthese, look at the smart group templates. The Simple Filter SmartGroup template uses the pattern *.nib.Any files with.nib intheir name are included in this smart group. The Simple RegularExpression Smart Group, on the other hand, uses the regularexpression \.(c|cpp|C|CPP|m|mm|java|sh|scpt)$ tocollect all implementation files ending in any one of thesesuffixes, regardless of the case of the filename and extension. Formore information on regular expressions, see the POSIXspecification.

  • Save For menu. Determines the scope forwhich this smart group is defined. You can have the smart groupappear in all your projects, or you can specify that the smartgroup be specific to the current project.

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. 

The favoritesbar in the project window lets you savefrequently accessed items and return to them quickly. To show thefavorites bar, choose View > Layout >Show Favorites Bar.

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:

  1. Select that item in the Groups & Files list or inthe detail view and open its Info window.

  2. Click Comments to open the Comments pane.

    This pane contains a single text field into which you can type anyinformation you wish. To add comments, click in the Comments fieldand type your entry. You can also link to additional resources fromthe Comments pane; hypertext links, email addresses and other URLsare actionable in this field.

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.


33.FileManagement

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 OpenQuickly command, which lets you openfiles by filename or by the symbols they define. Open Quicklysearches are case insensitive and limited to the current projectand the active SDK

To open a file quickly:

  1. Choose File > Open Quickly to display the OpenQuickly dialog (Figure3-1).

  2. In the search field, type the name of the file or symbol you wantto view.

    You can also select a filename or symbol name in the text editorand display the Open Quickly dialog to prefill the dialog’s searchfield with the selected text. When opening header files referencedin #include and #import statements,you need only to place the cursor on the referent line and displaythe Open Quickly dialog to start the header-file search.

  3. From the search results list, select the files you want to open andclick Open.


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:

  1. Place the cursor in the symbol that you want to learn moreabout.

  2. Press the option button at the same time you double-click themouse.

 

The below shows Quick Help with informationfor the colorWithAlphaComponent: methodof the NSColor class.

Quick Help

The top portion always contains the following:

  • The close button, which lets you manually close Quick Help.

  • The name of the symbol you are looking up.

  • Documentation button, which opens the reference document for thissymbol in the Documentation window, were you can view additionaldetails about this symbol as well as read about all the othersymbols defined for this API.

  • A button that opens the header file that defines this symbol.

(2)Using documentationwindow

 

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

 TheXcode Quick Start pageThe documentation home page

(2)Setting documentation preferences

 

The Documentation Sets group in Documentation preferences lists, bypublisher, the documentation sets that are:

  • Installed (black text)

  • Available but not installed (gray text)

 

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:

  • Make sure there is a check mark only in the fields you want tosee.

To change the order in which content appears in Quick Help:

  • Drag the field names to the order you prefer.

To ensure that fonts always use a minimum size

  • Select the option "Never use font sizes smaller than."

  • Choose a font size from the pop-up menu.


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 below shows a timeline thatexplains the relationship between deployment target and baseSDK.

 SDKdevelopment timelineCross-development timeline

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 NSObject class methodto check the availability of weakly linked classes at run time.This simple, efficient mechanism takes advantage ofthe NS_CLASS_AVAILABLE classavailability macro, available for most frameworks in iOS.

 

if ([UIPrintInteractionController class]) {
    // Create an instance of the class and use it.
} else {
    // Alternate code path to follow when the
    // class is not available.
}

This works because if a weakly linked class is not available,sending a message to it is like sending a messageto nil.If you subclass a weakly linked class and the superclass isunavailable, then the subclass also appearsunavailable.

 

To use the class methodas shown here, you need to do more than ensure that a frameworksupports the NS_CLASS_AVAILABLE macro.You must also configure certain project settings. With theserequired settings in place, the preceding code safely tests theavailability of a class, even when running on a version of iOS inwhich the class is not present. These settings are asfollows:

  • The base SDK for your Xcode project must be iOS 4.2 or newer. Thename for this setting in the build settings editoris SDKROOT(Base SDK).

  • The deployment target for your project must be iOS 3.1 or newer.The name for this setting is MACOSX_DEPLOYMENT_TARGET(Mac OS X Deployment Target).

  • The compiler for your project must be the LLVM-GCC 4.2 compiler ornewer, or the LLVM compiler (Clang) 1.5 or newer. The name for thissetting is GCC_VERSION(C/C++ Compiler Version).

  • You must ensure that any frameworks not available in your project’sdeployment target are weakly linked, rather thanrequired. 

 

In Mac OS X (and in iOS projects that do notmeet the set of conditions just listed), you cannot usethe class methodto determine if a weakly linked class is available. Instead, usethe NSClassFromString functionin code similar to the following:

Class cls = NSClassFromString (@"NSRegularExpression");
if (cls) {
    // Create an instance of the class and use it.
} else {
    // Alternate code path to follow when the
    // class is not available.
}

(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 instancesRespondToSelector: methodtells you if a given method selector is available. For example, touse theavailableCaptureModesForCameraDevice: method,first available in iOS 4.0, you could use code like thefollowing:

 Checking the availability of anObjective-C method

if ([UIImagePickerController instancesRespondToSelector:
              @selector (availableCaptureModesForCameraDevice:)]) {
    // Method is available for use.
    // Your code can check if video capture is available and,
    // if it is, offer that option.
} else {
    // Method is not available.
    // Alternate code to use only still image capture.
}

Check the availability of an Objective-C property by passing thegetter method name (which is the same as the property name)toinstancesRespondToSelector:.

 

To determine if a weakly linked C function isavailable, use the fact that the linker sets the address ofunavailable functions to NULL.Check a function’s address—and hence, its availability—by comparingthe address to NULL or nil.For example, before using theCGColorCreateGenericCMYK functionin a project whose deployment target is earlier than Mac OS Xv10.5, use code like the following:

Checking theavailability of a C function

if (CGColorCreateGenericCMYK != NULL) {
    CGColorCreateGenericCMYK (0.1,0.5.0.0,1.0,0.1);
} else {
    // Function is not available.
    // Alternate code to create a color object with earlier technology
}

Check the availability of an external (extern)constant or a notification name by explicitly comparing itsaddress—and not thesymbol’s bare name—to NULL or nil.

(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 is availablein your deployment target, you should require that framework (andnot weakly link it).

(4)Conditionally compiling for different SDKs

 

#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
    // code only compiled when targeting Mac OS X and not iOS
    // note use of 1050 instead of __MAC_10_5
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
    if (CGColorCreateGenericCMYK != NULL) {
        CGColorCreateGenericCMYK(0.1,0.5.0.0,1.0,0.1);
    } else {
#endif
    // code to create a color object with earlier technology
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
    }
#endif
#endif
}

from:http://blog.sina.com.cn/s/blog_777694e90100yi1v.html

(编辑: MyGameZone)

网友评论
相关文章