`
ydbc
  • 浏览: 717885 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

xcode相关的一些知识(二)

 
阅读更多

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.

<wbr></wbr>

There are two types of build rules:

  • System build rules.<wbr>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.</wbr>

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

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">/bin/sh</code>.However, you can specify any script interpreter byentering<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">#!&lt;interpreter_path&gt;</code><wbr>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</wbr></wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.def</code><wbr>suffix,you specify<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">[A-Z]*.def</code><wbr>asthe pattern.</wbr></wbr></wbr></wbr>

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.

<wbr></wbr>

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:

<wbr></wbr>

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:

xcode相关的一些知识(二)

For example, suppose that you need to define a buildrule to process files with theextension<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.abcdef</code>.Also suppose that the build rule script producesa<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.c</code><wbr>filefor each<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.abcdef</code><wbr>fileand that the generated<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.c</code><wbr>filesare placed in the default directory for intermediate files. In thiscase, the output-files specification could look likethis:</wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

$(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.<wbr>Thegenerated files are automatically fed back to the rule-processingengine. For example, continuing the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.abcdef</code>examplerule, Xcode processes the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.c</code><wbr>filesthe script produces using the rule thatprocesses<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.c</code><wbr>files.</wbr></wbr></wbr></wbr></wbr></wbr>

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


23.Build Settings

<wbr></wbr>

A build setting in Xcode has two parts: The name and thespecification. The<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">buildsetting name</strong><wbr>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<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">buildsetting specification</strong><wbr>is the informationXcode uses to determine the value of the build setting at buildtime. A build setting may also have a display name,or<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">buildsetting title</strong>, which is used to display the build settingin the Xcode user interface.</wbr></wbr></wbr></wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">gcc</code>command-lineinvocation to compile a source file, it evaluates compiler buildsettings (such as Generate Debug Symbols) to construct the argumentlist.</wbr>

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<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">targetlayer</em>; however, it is important to understand the variouslayers from which build setting values can be derived.</wbr>

In addition to build settings, you canset<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">per-filecompiler flags</strong><wbr>that the build system useswhen creating tool invocations. With them you can change how a fileis compiled without affecting any other files in theproject.<wbr></wbr></wbr></wbr>

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, <wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">project_name</code><wbr>isirrelevant to the build system and doesn’t override the value ofthe<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">PROJECT_NAME</code><wbr>buildsetting.</wbr></wbr></wbr></wbr>

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

<wbr></wbr>

In addition to the build settings provided by Xcode, you canadd<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">user-definedbuild settings</strong><wbr>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.</wbr></wbr>

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<wbr></wbr>

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


24.Predefined build configurations

<wbr></wbr>

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.

<wbr></wbr>

The binary file (or image) a targetproduces can be of one of these types:

  • Executable.<wbr>Executable files are binariescontaining the core logic of a program. Specifically, they containthe program’s entry point, which in C-based programs isthe<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">main</code><wbr>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,<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">MyProgram</code>).</wbr></wbr></wbr></wbr>

  • Bundle.<wbr>Bundles are executable files thatcan be loaded at runtime by other products. Plug-ins areimplemented using bundles. The term<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">bundle</em><wbr>inthis context refers to the binary itself, not to a structuredhierarchy. Bundles have the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.bundle</code><wbr>extension;for example,<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">MyBundle.bundle</code>.</wbr></wbr></wbr></wbr></wbr></wbr>

  • Static Library.<wbr>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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.a</code><wbr>extension;for example,<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">MyLibrary.a</code>.</wbr></wbr></wbr></wbr>

  • Dynamic Library.<wbr>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,<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">libMyLibrary.1.0.dylib</code>.</wbr></wbr>

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.<wbr></wbr>


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

<wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">Cocoa.h</code><wbr>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.</wbr></wbr>

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.

<wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">SHARED_PRECOMPS_DIR</code><wbr>(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.</wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">#include</code><wbr>and<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">#define</code><wbr>statementsused by the files in your target.</wbr></wbr></wbr></wbr>

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:

<wbr></wbr>

#ifdef __OBJC__
    #import <Cocoa/Cocoa.h>
    #endif
    #define MY_CUSTOM_MACRO 1
    #include "MyCommonHeaderContaining<wbr>PlainC.h"
</wbr>

<wbr></wbr>

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

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

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">GCC_PFE_FILE_C_DIALECTS</code><wbr>(CDialects to Precompile) build setting lets you explicitly specifythe C dialects for which Xcode should produce versions of theprecompiled header.</wbr></wbr>

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.<wbr></wbr>

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<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">distributedbuilds</strong>. When you use distributed builds, Xcode distributesas many compilation tasks among the computers available for thispurpose within a network.</wbr>


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

<wbr></wbr>

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.

<wbr></wbr>

Themost common kind of framework isthe<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">dynamicallylinked framework</strong>. Only Apple can install these on an iOSdevice, so there's no point in building them.</wbr>

A<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">staticallylinked framework</strong><wbr>is almost the same,except it gets linked to your binary at compile time, so there's noproblem using them.</wbr></wbr>

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

(1) Installing the Template System

To install, run the<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">install.sh</strong><wbr>scriptin either the "Real Framework" or "Fake Framework" dir (orboth).</wbr></wbr>

Now restart Xcode and you'll see<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">StaticiOSFramework</strong><wbr>(or<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">FakeStatic iOS Framework</strong>)under<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">Framework&amp; Library</strong><wbr>when creating anew project.</wbr></wbr></wbr></wbr></wbr>

To uninstall, run the<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">uninstall.sh</strong><wbr>scriptand restart Xcode.</wbr></wbr>

(2) Creating an iOS Framework Project\

  1. Start a new project.

  2. For the project type, choose<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">StaticiOSFramework</strong><wbr>(or<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">FakeStatic iOS Framework</strong>), which isunder<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">Framework&amp; Library</strong>.</wbr></wbr></wbr></wbr>

  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<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">BuildPhases</strong><wbr>in your framework target,expand<strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">CopyHeaders</strong>, then drag any header files you want to makepublic from the<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">Project</strong><wbr>or<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">Private</strong><wbr>sectionto the<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">Public</strong><wbr>section.</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>


(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:<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">(yourframework).framework</strong><wbr>and<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">(yourframework).embeddedframework</strong></wbr></wbr></wbr>

If your framework has only code, and no resources (like images,scripts, xibs, core data momd files, etc), you candistribute<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">(yourframework).framework</strong>to your users and it will justwork.</wbr>

If you have included resources in your framework,you<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">MUST</strong><wbr>distribute<wbr><strong style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px">(yourframework).embeddedframework</strong>.</wbr></wbr></wbr>

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 <MyFramework/MyClass.h>


29. Group Types

<wbr></wbr>

The Groups & Files list contains two types ofgroups:<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">staticgroups</em><wbr>and<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">smartgroups</em>,<wbr></wbr></wbr></wbr></wbr>

Groups & Files list

Staticgroups<wbr>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.</wbr>

<wbr></wbr>

Smart groups<wbr>are subdivided into twotypes: built-in smart groups and custom smart groups.</wbr>

  • Built-in smart groups contain particular classes of components,files, symbols, or items. You cannot customize the contents ofthese groups. There are several built-in smart groups:

    • Targets.<wbr>Contains the targets in yourproject. A<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">target</strong><wbr>containsthe instructions for creating a software component orproduct.<wbr></wbr></wbr></wbr></wbr>

    • Executables.<wbr>Contains all the executablesdefined in your project.</wbr>

    • Errors and Warnings.<wbr>Lists the errors andwarnings generated when you build.<wbr></wbr></wbr>

    • Find Results.<wbr>Contains the results of anysearches you perform in your project. Each search creates an entryin this group.<wbr></wbr></wbr>

    • Bookmarks.<wbr>Lists locations—files orspecific locations within a file—to which you can returneasily.</wbr>

    • SCM.<wbr>Lists all the files that have sourcecontrol information.</wbr>

    • Project Symbols.<wbr>Lists the symbolsdefined in your project.<wbr></wbr></wbr>

  • Custom smart groups collect files that match a certain rule orpattern. These groups have purple folder icons and you cancustomize their contents using wildcard patterns or regularexpressions. There are two types of smartgroups:<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">simplefilter</em><wbr>or<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">simpleregular expression</em>. Xcode provides two predefined custom smartgroups:</wbr></wbr></wbr>

    • Implementation Files.<wbr>Contains theimplementation files in your project, such as those with theextensions<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">c</code>,<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">cpp</code>,and<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">m</code>,to name a few.</wbr></wbr></wbr></wbr>

    • NIB Files.<wbr>Contains the nib files used tocreate your product’s user interface.</wbr>

30. Grouping files

A<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">group</strong><wbr>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.<wbr></wbr></wbr></wbr>

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

<wbr></wbr>

Creating a Static Group

You can create a static group in any of the following ways:

  • Create an empty group. Choose Project > New Groupand type the name for the group.

  • Create a group from existing items. Select the items you want togroup and choose Project > Group.

  • Create a group based on an existing directory structure. ChooseProject > Add to Project. Then select the folder,and select “Recursively create groups for added folders.”

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.m</code><wbr>or<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.c</code>.When you make a change to your project that alters the set of filesmatching a smart group’s rule—for example, addinga<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.c</code><wbr>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.</wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

Creating a Smart Group

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

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

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

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">*.nib</code><wbr>intheir name. The default Simple Regular Expression Smart Groupcollects all C, C++, Objective-C, Objective-C++, Java, andAppleScript implementation files in your project.</wbr></wbr>

Configuring a Smart Group

To configure a smart group, select the group in the Groups& Files list and open the Smart Group Infowindow,

<wbr></wbr>

Here is what the Smart Group Info window contains:

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

  • Image.<wbr>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.</wbr>

  • Start From menu.<wbr>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.</wbr>

  • Using Pattern field.<wbr>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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">*.nib</code>.Any files with<code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">.nib</code><wbr>intheir name are included in this smart group. The Simple RegularExpression Smart Group, on the other hand, uses the regularexpression<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">\.(c|cpp|C|CPP|m|mm|java|sh|scpt)$</code><wbr>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.</wbr></wbr></wbr></wbr></wbr>

  • Save For menu.<wbr>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.</wbr>

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.<wbr></wbr>

The<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">favoritesbar</strong><wbr>in the project window lets you savefrequently accessed items and return to them quickly. To show thefavorites bar, choose View &gt; Layout &gt;Show Favorites Bar.</wbr></wbr>

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.

<wbr></wbr>

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.

<wbr></wbr>

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

<wbr></wbr>

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

<wbr></wbr>

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<wbr><strong style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-weight:bold">OpenQuickly</strong><wbr>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</wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">#include</code><wbr>and<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">#import</code><wbr>statements,you need only to place the cursor on the referent line and displaythe Open Quickly dialog to start the header-file search.</wbr></wbr></wbr></wbr>

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


34. Documentation Access

(1)Using quick help

<wbr></wbr>

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.

<wbr></wbr>

The below<wbr>shows Quick Help with informationfor the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">colorWithAlphaComponent:</code><wbr>methodof the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NSColor</code><wbr>class.</wbr></wbr></wbr></wbr></wbr>

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

<wbr></wbr>

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.

<wbr></wbr>

The first time you open the Documentation window, it opens to theXcode Quick Start page, shown below

<wbr></wbr>TheXcode Quick Start pageThe documentation home page

(2)Setting documentation preferences

<wbr></wbr>

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

  • Installed (black text)

  • Available but not installed (gray text)

<wbr></wbr>

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.

<wbr></wbr>

The below<wbr>shows a timeline thatexplains the relationship between deployment target and baseSDK.</wbr>

<wbr></wbr>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:

  • Not defined in the base SDK (for example, a symbol from a newerOS), you get a compile-time error.

  • Defined in the base SDK but marked as deprecated, you get acompile-time warning.

  • Defined in the deployment target, your code links and buildsnormally. At run time:

    • On a system running an OS earlier than the deployment target, yourcode may fail to load if you use symbols unavailable in thatOS.

    • On a system running an OS equal to or later than the deploymenttarget, your code has null pointers for symbols not available inthat OS..”

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

<wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NSObject</code><wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)"><a href="http://disanji.net/iOS_Doc/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/class" target="_self">class</a></code><wbr>methodto check the availability of weakly linked classes at run time.This simple, efficient mechanism takes advantage ofthe<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NS_CLASS_AVAILABLE</code><wbr>classavailability macro, available for most frameworks in iOS.</wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

if ([UIPrintInteractionContro<wbr>ller class]) {
</wbr>
    // 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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">nil</code>.If you subclass a weakly linked class and the superclass isunavailable, then the subclass also appearsunavailable.</wbr>

<wbr></wbr>

To use the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">class</code><wbr>methodas shown here, you need to do more than ensure that a frameworksupports the<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NS_CLASS_AVAILABLE</code><wbr>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:</wbr></wbr></wbr></wbr>

  • The base SDK for your Xcode project must be iOS 4.2 or newer. Thename for this setting in the build settings editoris<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">SDKROOT(Base SDK)</code>.</wbr>

  • The deployment target for your project must be iOS 3.1 or newer.The name for this setting is<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">MACOSX_DEPLOYMENT_TARGET(Mac OS X Deployment Target)</code>.</wbr>

  • 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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">GCC_VERSION(C/C++ Compiler Version)</code>.</wbr>

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

<wbr></wbr>

In Mac OS X (and in iOS projects that do notmeet the set of conditions just listed), you cannot usethe<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">class</code><wbr>methodto determine if a weakly linked class is available. Instead, usethe<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)"><a href="http://disanji.net/iOS_Doc/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSClassFromString" target="_self">NSClassFromString</a></code><wbr>functionin code similar to the following:</wbr></wbr></wbr></wbr>

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

<wbr></wbr>

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<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)"><a href="http://disanji.net/iOS_Doc/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/instancesRespondToSelector:" target="_self">instancesRespondToSelect<wbr>or:</wbr></a></code><wbr>methodtells you if a given method selector is available. For example, touse the<code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)"><a href="http://disanji.net/iOS_Doc/documentation/UIKit/Reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/clm/UIImagePickerController/availableCaptureModesForCameraDevice:" target="_self">availableCaptureModesFor<wbr>CameraDevice:</wbr></a></code><wbr>method,first available in iOS 4.0, you could use code like thefollowing:</wbr></wbr></wbr>

<wbr></wbr>Checking the availability of anObjective-C method

if ([UIImagePickerController instancesRespondToSelect<wbr>or:
</wbr>
              @selector (availableCaptureModesFor<wbr>CameraDevice:)]) {
</wbr>
    // 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)toinstancesRespondToSelect<wbr>or:</wbr>.

<wbr></wbr>

To determine if a weakly linked C function isavailable, use the fact that the linker sets the address ofunavailable functions to<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NULL</code>.Check a function’s address—and hence, its availability—by comparingthe address to<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NULL</code><wbr>or<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">nil</code>.For example, before using the<code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">CGColorCreateGenericCMYK<wbr></wbr></code><wbr>functionin a project whose deployment target is earlier than Mac OS Xv10.5, use code like the following:</wbr></wbr></wbr></wbr></wbr>

Checking theavailability of a C function

if (CGColorCreateGenericCMYK<wbr> != NULL) {
</wbr>
    CGColorCreateGenericCMYK<wbr> (0.1,0.5.0.0,1.0,0.1);
</wbr>
} 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<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">not</em><wbr>thesymbol’s bare name—to<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">NULL</code><wbr>or<wbr><code style="font-size:13px; font-family:Courier,Consolas,monospace; color:rgb(102,102,102)">nil</code>.</wbr></wbr></wbr></wbr></wbr>

(3)Weak linking to an entire framework

<wbr></wbr>

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<wbr><em style="font-family:'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; font-size:13px; font-style:italic">is</em><wbr>availablein your deployment target, you should require that framework (andnot weakly link it).</wbr></wbr>

(4)Conditionally compiling for different SDKs

<wbr></wbr>

#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<wbr> != NULL) {
</wbr>
        CGColorCreateGenericCMYK<wbr>(0.1,0.5.0.0,1.0,0.1);
</wbr>
    } 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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics