Home

Wiley iPhone OS Development: Your visual blueprint for developing apps for Apple's mobile devices

image

Contents

1. A Ja Developer Document XET bb dues Help ET Open the Documentation Library by choosing ar Help Developer Documentation Prone OS 3 1 Urar Moods Hels wekane to cade srode Ouch Stam Sods Helenar Moves meg of x 10 amp Library Moods 3 2 Developer Tools Library gt Cening Started Required Renting Choose iPhone OS Library from the Home coding ea Ta Find Documaniation far Saliad Taxt Cetting Siarced drop down menu T iPhone Refi open manaue Rete renna The iPhone Refera Tibrary i you ur bag its A EIF For deta led Ra msaa Mainu information essential to iPhone 05 application development Sunpk Coe Technical Mores Tachnical aku Topks Top Tamanna Toole UE Te Audio S Wim Le he a NiE Hi z hera thical Leam Seow To teas che Pree a ica sy a Phone s 7 Uhra dener mzercihar of estar desenare trek eae ispemenc PITEN os LW Tac fa 3 niam a vara ia an tk iar shirts tos hagdes n Una Apple prosides lo build F bra Fania dae Crneral aera ekg and opel nde par Acres arene Creda Ter T Graphics A Animation appl celion Mias and Tuchrical Ca Kebeciing amp m m l Peronmere Soe Documents 739 of 739 Fiker Doure us User Eap rienit Franewnrks z Tech Lasar amp Lege Experience Coding How Tos Aciinaa Buck UI Carre Ek Bap ke Meseage UI Uh Malia Layer e Mrieoking amp nieni Coding Paw Ta s arji Tuis idh lah AN Franio amp Tons Codhg How Tos Cuing How Taa E
2. s DTrace toolset and can provide a comprehensive view of activity inside your application Use it to monitor object allocation animation and graphic performance and memory leaks as well as to record sequences of user actions for testing your applications in the Simulator Dashcode Dashcode is Xcode s web app development tool Web apps use similar technology to Apple s OS X dashboard widgets so Dashcode can also be used to develop widgets Two template modes select either iPhone or widget targets For the iPhone target the included templates mimic the iPhone s native interface features The Run button in Dashcode creates a web page that loads in Mobile Safari in the Simulator Web apps are not compiled into separate applications and are not installed on the iPhone Dashcode is a legacy development tool and is not described in further detail in this book Apple s editor and asset manager was developed around GCC and is unique to Xcode It adds useful windowing asset listing debugging and auto completion features and includes hooks for the Simulator performance monitoring memory integrity checking and other performance oriented features Behind the Xcode interface the compiler remains a recognizable variant of GCC expanded with extra Apple libraries Although GCC is not a fast compiler iPhone applications are often small so compilation speed is rarely a problem Xcode includes too many features to list here
3. 519 KE 250 1 ME 9 9 ME 35 4 ME POL ME 25 5 ME 2 7 ME 10 7 ME 15 8 ME pI ME SUA Ke 5 1 ME fa ME 4 EE 4ER z gE Z A OME ghd ME 35 8 ME 1 4 MA 263 8 ME 1 1 ME ERE L79 GE 500 35 ME 250 KE 545 7 Ma Folder Poetabia Docueanc Format FOF Apobeatiun Fader Folder Apobcntion Feadar Apolbrsiion Apolcalan Faltar Apolcaion Fedar Folder Apedicasion folder cerSigmingR quest remificare Folder Folder Folder Fodder Feder Folder Fadar Derog Provisioning Profile Fader older Folder Fallar L IaJdeyp e e ponui I SUDN e d SO 900d e SIDIAID The current cost of professional developer enrollment is 99 for individual developers and small businesses Company enrollment requires legal verification of business status and takes two to four weeks to process You must fax a copy of your incorporation documents to Apple on demand Individual enrollment takes one to two weeks business enrollment is likely to take four to six weeks One of the benefits of the Standard iPhone Developer Program is that it is likely but not guaranteed to provide early access to beta versions of the iPhone OS including updates to the SDK You will have a head start of two to three months over non enrolled developers This gives you time to update your apps to make sure they are compatible with the new iPhone OS when it is released Beta versions are a moving target for devel
4. SO BUOY SUIDNpoNU Build a Sample A ah oe ou can use Xcode s features to quickly build and Application test the sample code applications included in the i documentation Compilation is a one click process in Xcode You do not need to know anything about Objective C frameworks or other features of the iPhone OS to build and test the sample applications The only prerequisite is an ability to use the Finder to create and name folders while saving files and to select a target platform in Xcode There are two ways to build a sample application The first is to use the sample code found in the documentation This includes a quick link Clicking the Open Project in Xcode button and choosing a Save As location loads the project into Xcode Behind the scenes a compressed version of the project is decompressed and copied into the directory you nominate The project files are then loaded into Xcode ready to be built If you are downloading a project from an online collection the files are usually compressed into an Build a Sample Application archive that includes a complete directory tree for the project You will need to uncompress the archive manually before you can load the project and optionally copy the files to a working directory From there you can load the project into Xcode by double clicking the file with the xcodeproj extension For convenience you may find it helpful to keep all your applications in
5. code repositories for shared online development with all the features of the GCC compiler can fine tune the compilation process by modifying them and saving custom settings to create specialized compilation templates Work with Application Preferences and Settings Gen haod E an Xcoda f Choose XcodePreferences to E thot Xcode TA mainm MyClass view the Xcode Preferences GA J Acton preakoois a e 9 a dialog box Bs Empty Caches Coresraphics framework TR ra Hide Xcode H onan Click one of the preferences rH Hide Otters Cit Pe n 3 b U MyClass WewControlercy ra categories to view and change Bi QuicXcode Q mome MENR the settings r Prenen i a P A Click apply to make a change and CDN SSS leave the dialog box open to make pigner m et ee EE more changes Click OK to make a Se oea ating aa a Sn apace arcane i A Workspace change and close the dialog box e o A meu ea A W Restore state af ausillary windows Click Cancel to undo the last change if any and close the dialog box Use the scrollbar to scroll horizontally through the complete list of preference groups Click any group to make changes Click or double click individual o f A BB items to make changes s Kay ndings o Toreda a STen Fie Tyres sau Note In the Fonts amp Colors group you can Shift click the entire list of text types to select them all and Pain Test 6 r Monaco then do
6. in detail This book introduces an essential subset of features but as you develop more complex applications you will need to manage your projects in more sophisticated ways Apple s Xcode Project Management Guide includes a detailed summary of Xcode s file and source tree management features The guide is available online in the Developer Connection area of Apple s site Because Apple changes some of its URLs regularly doing a web Search is the easiest way to locate it You should work through this guide as soon as you start reusing code in your projects and when branching projects For advanced developers Xcode includes scripting and automation features that use Apple s Automator plug in which is built into all current versions of OS X Automator can simplify development with scripted file and asset management Mastering Automator will save you significant development time on larger projects I sulDNpoNyY 1 Jojdey e d SO 904d e A m O V Explore the Sample Code Libraries ou can use the sample code libraries to gain a head start on effective development To speed up development you can reuse code from the libraries in your own applications You can also use the libraries as worked examples that demonstrate how to solve coding problems and implement the iPhone s unique features The iPhone s documentation is updated with each new release of the OS Prior to Xcode 3 2 documentation wa
7. ivr cReccponde rr fcvecee Ee mihl chon cemar che eting aat aadabeString balers cea h i In addition to bookmarks and navigation shortcuts Xcode includes a Favorites feature To show the Favorites toolbar choose View gt Layout gt Show Favorites Bar The toolbar appears as a blank gray area below the main Xcode toolbar You can drag items from the Groups amp Files pane and then drop them on the toolbar for quick access To remove an item drag it back to the Groups amp Files pane Do not delete it this deletes it from the project The Favorites feature is a simple file selector It does not include positioning information so you cannot use it to move quickly to a specific location in a file The bookmarks list in the Groups amp Files pane is the only feature in Xcode that can move between different locations in different files Unfortunately there is no way to undock the Bookmarks feature and open it in a separate window pnponug 3aadeyp I SUDN e d SO 904d e A pi O V Debug Your Code E F oe ou can use Xcode s debugging features to eliminate errors in your code The debugging environment is unusually sophisticated You can set breakpoints at line numbers or at specific symbols You can single step through the code after a breakpoint and you can monitor variables You can also set breakpoint actions which force Xcode to perform various actions when it reaches cert
8. o e deliberate memory leak rent T recente gi m A AEE 9 I A O Review how the allocations listings Ae R STITT O are updated as memory is assigned D Watch as the bar graph display flags o the leak with a red indicator and a Mamanin A step change in the bar height Strasse z aan aw The Leaks instrument gives a clear eee 3 ogogopagca indication of memory leaks in the hirano 5 a sie Y aaa z BHEno0o application oe x DO su m her summary The Instruments tool is modular The presets listed in the Instruments menu display one or two monitoring tools from a wider selection of options You can assemble a list of tools to suit your own requirements To add a monitoring tool to the list click the gear icon in the bottom left corner of the Instruments window choose Add Instrument from the pop up menu and then select an instrument from the list that appears next to it Some of the instruments are designed for the Mac environment and either do not work on the iPhone or do not display useful information To remove an instrument from a collection drag it to the Trash Advanced developers can build their own monitoring tools Choose InstrumentBuild New Instrument to view an Instruments development panel You can use this to create a tool to monitor a selection of various system and runtime events and states Work with Application Preferences and Settings Y ou can customize many of the fe
9. similar names Use this to double check that you are editing the correct file Detail View aT gt The Detail View shows the tamane S g SS a item or items selected in 3 ES ii sey ee i the Groups amp Files list with vanes agingT eston Dalegare m B summary and status fields rea sae Praet for each From left to right H ies eee the summary fields are File i Name Build Status Code nnn resor which lists file sizes Build ae a T A Ee Errors Build Warnings and Panua gTest annie cues hAOb jest Asep icationde legeez 3 Target Membership which Sr ae iia E specifies whether the file is Lac aerapaty vemctowie retain TED tLet Ulvlaiau Palaos included in the current ai build target These icons are not named and there is mts _ ss haa Siea no hovering screen tip to pin rakakairotisivla remind you of their function yeti e Pied a upi _ par o ulap lection shacedipalieuticn opens I k G H Text Editor Status Bar Groups amp Files List Use the Text Editor to edit the code of the file you have selected in the Detail View or in the Groups amp Files list The text area includes a complex navigation bar at the top with features that aid Speedy navigation and code management Text Editor Navigation Bar The status bar displays a confirmation message if the compilation was Successful or an error coun
10. with web data The iPhone OS Product Range iPhone OS Product Range iPhone OS devices include the iPhone iPhone 3G iPhone 3GS iPod touch and iPad All share a thin form factor with a unique high resolution display and a multi touch interface The iPod touch is identical to the iPhone series but lacks phone and mobile data features a camera a microphone and GPS The accelerometer Mobile Safari web browser and Wi Fi networking are included However the iPod touch is much more than a crippled iPhone and remains a popular product with buyers and developers Approximately 95 of applications in the App store are compatible with the iPod touch It is also more affordable than an iPhone For developers it is possible to develop test and sell complete applications on an iPod touch An iPhone is not essential unless you intend to develop for iPhone specific hardware features such as the camera GPS compass and so on With the iPhone 3GS comes an improved camera with video capture voice control a compass enhanced Open Memory Limits Battery Life Life The iPhone does not support virtual memory There is no page file and no option for disk swapping When your application runs out of memory there is no more memory available Your application must manage memory errors effectively Otherwise it may be terminated by the iPhone OS without notice it may crash or it may force a complete reboot of the iPhone All your ap
11. Introducing iPhone OS Devices C OTIL ae lt he iPhone iPod touch and iPad combine innovative new computing technologies with a completely new business model Technologically developing for the iPhone family is challenging but rewarding The development environment is loosely based on the Mac with some extensions and limitations but the user environment is innovative and encourages creative and novel experiences If you are a Mac developer you will find many concepts familiar and can likely start iPhone development after a brief reorientation If you are new to the Apple development environment give yourself a few weeks to master the principles and programming models This book includes key concepts with worked examples Combined with Apple s documentation they will enable you to move rapidly toward understanding and creating your own applications PANE The iPhone OS documentation lists thousands of objects message definitions and function calls The biggest challenge for new developers is learning which messages are used to signal which event The second biggest challenge is mastering the syntax of each call to the OS Every message type uses a different syntax with different data structures and access methods Fortunately Apple s code samples include generous amounts of boilerplate code When you begin developing applications you can copy this boilerplate to your own projects and reuse it with minor e
12. One of the most useful is the iPhone Developer site at www theiphonedev com The Source Code tab on the site lists about 50 applications with links to source code Most applications are relatively simple but some are more adventurous and push the limits of what is possible on the iPhone Unlike the Apple sample code examples these applications are more or less complete Although you can reuse or repurpose their code this does not mean the code is in the public domain or that you can use it as you want Most applications are licensed under one of the many open source licenses that cover open code If you add this code to your own projects you must accept the restrictions in the license eS yO EX Introducing Xcode s Work Areas Introducing Xcode s Work Areas File Name Toolbar The Toolbar includes the main Build and Run tool that compiles a project The Info tool displays information about a selected item Click the Tasks button to stop an active operation The Action pop up menu displays a smart list of actions relevant to a selected item A URLMessagingTestAppDelegateh URLMessagingTest Search Field Enter a search string to search the Detail View for a match The search field does not search the Text Editor You can use it to search for groups and files in a project but not for symbols in code The file name displays the name of the file currently being edited Project files often have very
13. a Pos Mec Layer Audiu Touba Aio lir AE Esunrbniar e Launching pour pplication in Landscape Technic Purs Leer Q Review the list of sample code Se oS a telat p s s examples pabean emanare ae E Optionally click Title to sort the coe cerca wert creo er nh ek rene te examples by name ai eel se eh hol od oreo lal me eS a Optionally click Resource Type amen oen a Topic Framework or Date to mat G see re sort the examples by the ane S corresponding criteria ces 2 Optionally scroll down to review mepi O the rest of the list and then select G an example by clicking its title Sor S Men U Aadio Unit Ar mandiin Review information about the example including the version n number and build requirements HelloWorld d SO 900d e Version 1 7 Optionally you can view one or 9 encore more of the files included in the ee A m O V Runtime Requirements Mac D5 X 10 5 3 IPhone O5 2 0 example project by choosing it View Source Code seker Fk _ from the View Source Code drop ent down menu Description HeloWard damanirans hyw Do use a kewhomnd to ener DXT inte a cee field and bw re display the Test in a Document Revision History Date Maras 100 07 07 First public release ad this document help your Yes Its good but Woi belpdul Further examples of source code are available from various sources online
14. ain breakpoints Xcode includes four separate but related debugging windows You can debug directly in the Text Editor setting breakpoints and single stepping through code You can use the mini debugger which is a floating window that summarizes the application state There is also a full debugger window which provides more detailed information about variables and execution status Finally there is a general purpose console window It provides runtime status messages including crash dumps You can also send messages of your own to the console window The console is independent of the main Debug Your Code iPhone a Messages sent to it are not visible to iPhone users It is equivalent to sending the stdout stream to a terminal in Unix Identical debugging features are available on the Simulator and on an attached iPhone You can monitor execution on a real iPhone check variables and receive crash dumps and other real time status information To use the debugging features choose the Debug option from the Compiler Configuration drop down menu When you build and run your application is generated with a full symbol table and other debugging information Remember to select the release setting for a final build run Otherwise your application will use more memory than it needs to and will run slowly Advanced developers can use further features such as conditional breakpoints breakpoint templates breakpoint actions and watchpo
15. appla pronte ym n personn moe ieva linens undar l a s eoperighks in bhis migm m a sntheare khe app ln nears h hn ek Deprived radishes bebe Lha app Acute bh ce a Heul palit iul iue iri sour odo birary Por proeided Urol i7 woo pialietrisule tet Apolo Soo taare in itr cabigcky ond vite weit eckion yiu met poban Groups amp Flies Se ete RS bellewerld E OB styviewCentrulerm IE E ReadMe i lanman Ti HeiaWerkdAppbelegareh m MeloWorbdAppDelegate m H MivwieweContreller t BB eoram amp iher Snurees bo Resources b D Framewnres a Procens HET od Execetables FE Find Results ri Bookrmartss 5 B implementation Mp view ontredier 50M Bo iii E Project Symbols min E bapiurunieten Pili B ig P i FIB Fikes Eo eewtidAocear 6 f i d Bh My m G eiewDikdLoa T Q DAEN hisis a pragma mark bihal 1 steer eldthoukeeturs touchesSeganwithEvenr eur drei i tyla M Bon tHe es t Mot ordieoad re We ahia Le J Tat ld best ie dcboorsubboswede UDTeRbP cl toc esd Letti d Meen tke siga first lands daal the ploaceholees fest that s in the ff Sat risia ba the bebe loge tat tanie ld plan deg maoa rors Ths s o prm wr na puemi ing i Shoes tie tes of tke beck field in tke steig beetance saridols ge lf lstripg texkFLlebc text S aat bha cart eR le Re Td Move the cursor to any location in the file Choose Edit gt Add to Bookmarks to add a bookmark C
16. as P O gt m 5 Use the Simulator to test and explore TE Cee z 9 J the features of the sample e i application a re Sree 3 7 ig heot a dma The Simulator runs the application as Eicon E feat 9 x O if it were installed on an iPhone swore 2 Note Optionally you can quit the jaa jie x Simulator when done by choosing _ Ete z iPhone Simulator Quit iPhone Simulator You can also leave the Simulator running You will be asked to confirm that it should quit and reload if you recompile Halik d lagre heed TEENE alwlelrlriv luli lole Bsucreied To test applications on a real iPhone you will need to provision it To provision a phone you must sign up for the full iPhone Developer Program register be accepted and pay a fee You can then set up Xcode with a set of provisioning keys and also add further keys for specific handsets The provisioning process is complex You create three software keys one for yourself or your managing corporate entity one for each developer in the project and one for each handset You must copy the first two keys to your project folder install the handset key on the iPhone and then add it to the Provisioning Profiles tag under the iPhone Development tab in Xcode s Organizer window You can view the Organizer by choosing Window Organizer in Xcode You can find detailed walkthrough instructions for the provisioning process on the devel
17. atures in Xcode In addition to Xcode s preferences each project features by using the Preferences feature You can set the a separate collection of settings You can use these to preferences to modify the working environment to define the files and folders that are part of the project and suit your own coding style and to reveal some of the to specify build targets including the final name for the features in Xcode that are not visible with the default application Unlike the Xcode preferences project settings settings For example you can change the debugging are not collected in a single location The programmer preferences so Debugger and Console windows name and company copyright tag are not set in Xcode automatically appear during a debugging run they are automatically read from the default user card in The full list of preferences is long and detailed For the Contacts database example you can change the colors and fonts in the Text To view and change the other project settings right click on Editor modify some of the features of the Code Sense the Targets icon in the Groups amp Files pane and then choose auto completion tool change the key bindings in the Get Info from the pop up menu Click the Build tab to view menu tree set up distributed builds on a network and general project compilation options You can typically leave load extra documentation You can also set up source these options unchanged Advanced developers familiar
18. bee MiFi ido H at at roo rke k ee oh aati UD Ta ald 2 eat a Choose the Debug build option from the Q a iaia paama a Compiler Configuration drop down a Buldand Beton Tasks Io s Mi hara F Fh kelgworki E E eonen menu Search aja e a a 35K a Click the Breakpoints switch to select it if it is not already selected Click Build and Debug to create a debug build and then install it in the Simulator E pE aTi ew D mirri Jak A aA ie U or oi n qem ie clia AAL i e AGRA IU M MALLA DE peak eat ee war ine eua Tivi E Diplo ee pilatik li ke maer L I li Une om Fiai d plasteli I ee Tuir het pepe etd hel Dowikettring 20 AA p ni he Canralera HelloWerld z Type a test string into the application in a 12 oo the Simulator to trigger the breakpoint SRR eee Oe O BY iwni B d Me vierdcontecl arm a gt B Jeachte tur Note In this example the debug breakpoint j oe S A p Media ried pee acca re 8 qe is triggered when you attempt to ete E update the string But the breakpoint ed oa can be placed anywhere in the CRON application and triggered at any point Brisa P es F ve se H Review the changes that appear in the aei OP A FEE Hn Fira Theas ereman e Text Editor window Sie e E AAA z a ea a F J The breakpoint location is highlighted vest ptt z x
19. by choosing RunConsole in Xcode To send messages to the console add NSLog statements to your code For example NSLog Hello iPhone Console This prints Hello iPhone Console on the console with an associated time stamp You can use console messages to debug applications that are difficult to manage using the standard debugging tools Multi threaded applications can be particularly challenging Adding a conventional breakpoint can disrupt the interaction between threads You can use NSLog to display the status of variables and program execution without disrupting thread interaction You can also use it to monitor simpler status messages generated by a single thread However the other debugging tools offer more sophistication for problem solving at this level NSLog works in both debug and release builds For best performance you should remove all NSLog statements from an application before final release You should also select the Release build option for a final build so debugging information is not unnecessarily included Profile and Improve Your Code CY N ODAS Af ou can use Xcode s Instruments to monitor features of operation of your application in real time for example you can watch memory allocations check processor activity and monitor file accesses Instruments do not use the debugging system and do not require a debug build You can use Instruments with a release build You can run them on the Sim
20. de Sense Instead of narrowing down the search options by typing you can also press F5 to display a box with a scrollable list of suggestions Xcode s first guess is pre selected but you can scroll through this list to select a different option This list is simply the list of symbols in the application Xcode does not attempt to filter the list for relevance or appropriateness Other keyboard shortcuts are available By default Control forward slash skips between code blocks Control period inserts a series of guesses Control comma reveals the suggestion box You can change these key bindings in the Code Sense tab in the Xcode Preferences For more on Xcode preferences see the section Work with Application Preferences and Settings later in this chapter ponu 1 Jaideys I SUDN e d SO 904d e A m O V Speed Up Editing with A OM ah Ae g WAN r Pop Ups and Bookmarks o a INE code includes three navigation shortcuts All appear in the navigation bar at the top of each file window in the Text Editor The File History menu shows a pop up list of recently edited files Pop up lists for each project are managed independently The Function menu shows a list of function variable and method definitions in the current file You can extend this list and add custom locations to it by adding pragma directives to your code These directives do not affect compilation They work exclusively wi
21. dits As you gain experience you can begin to customize it and extend it to meet your own requirements You will also learn how to add custom messages and message handlers of your own design The App Store Advantage App Store Advantage WebsApps and Native Apps Apple s App Store is a key advantage because Apple distributes your app and does significant marketing for you The ideal iPhone application is simple and elegant and its development is tightly focused which means development cycles can take months as opposed to years Therefore you see the benefit from your development work more quickly than you would from a typical desktop product and the cost of entry in both time and capital is Significantly lower Apple s iPhone SDK is free To download it you must sign up as a developer at http developer apple com iphone Registrations are typically approved within 24 hours If you decide to distribute or sell your applications through the App Store or test them on your own iPhone rather than the SDK Simulator you must pay Apple 99 to join the standard Developer Program Individuals should allow a month for signup Small businesses should allow two months The App Store model is not perfect You must allow two weeks for testing of each submitted application and not all applications are accepted There is no way to check if your application will be approved ahead of submission In the past Apple has blocked applications that compe
22. e Code Sense auto completion feature in Xcode to speed up and simplify development It minimizes typing and reminds you of the names of important variables and other program features Code Sense is a semiautomated tool that fills in code as you type It searches the application s symbol table for matches If there is more than one symbol or feature with a similar name Code Sense inserts the first match it finds You can accept its match by typing Return or you can continue typing to narrow the search and specify a different match When you accept a match Code Sense automatically skips the cursor over the symbol it entered so you can continue editing the remainder of the code For language features including conditionals and loops Code Sense inserts summaries of the syntax with Work with Xcode s Auto Completion Features RAAT appropriately named code blocks For example a for loop appears with initial condition increment and statement code blocks Tab to each block to select it and then begin typing as normal to fill it with code Tab again to move to the next block Code Sense also includes bracket matching indicators for both curly and plain brackets When you type a closing bracket Code Sense flashes the matching open bracket In limited and apparently somewhat random contexts Code Sense may sometimes add an opening square bracket where one is needed You can use this feature to ensure that your brackets are co
23. e Sererhy Todhg Hrw To r Dabry Haw lar ehig Har Tor na e Graphics amp Anim iien Coding How Ta s Coding How Tos Gr ey LLLI Click Sample Code under the Resource a ee Types header in the left hand pane ox 7 Hesnurre Types Dacha HowTo cening fairi Dukia Temene Arlean Kreg Sunpie Cade Teche boa kores Terbabas Oye iPhone Reference Library The iPhone Reference Library is your bookshelf for detailed information essential to iPhone OS application development A list of sample code examples appears in the Documents pane of the Reference Library window Topics u Typa Ouai ky MOCESS iF Yura pip nicl nee IN Frame wrk omer Beenie Cain a serari T aw 0G USE Tht feee sopire lewd yrii tm drakona perapertive n ra te Purkan nini the dhfivrest leningin thal Apel pred ba buli me dha Mafuraiee Neleuwe Thora 5 Lidar Pe eee ee homes aay Fates Techindcal Graphic E Animation ap Kman and Technical Giu Neke biny amp Indore Reponn Audin k Adre Duala Meee ren Gener Optionally you can click the Resource Type sort tag in the Documents pane to sort all the documents by type and group the sample code content together 739 of 739 i Finir Daciei Lin e rsh Gepomting for Phane OS ApHicaiors Teckrical Hotes Dpendl FA for Phaipe 05 Technica Frins babnial Roles t Beoemem Transfer Soraneqks High Efficiency Advanced Audion Coding HE AST Tabi
24. eate an application from scratch without using templates this is not straightforward and is not recommended Many of the templates include features that have been commented out You can add extra features to your application by removing the comments However even with commented sections the list of features included in the templates is minimal In a typical application you will need to add further features by hand You can save further development time by creating custom templates to your own design There is no limit on how complex a template can be Oper Quickly Dorn Recent File Open Recent Prajt Get Into Close Windus Close Current File m SO rk theses SP gun os O ADA Chacas a bemplate fer your mew pareert map Frare drh al Wiew Based Application Thk send ote pete ie eee pei Poe oe a dct har ee eg he wits N rakie edna corre clear ta maraga tha Ara ard anb Ale dir cereale thare Navigate to the folder in which you would like to save your new project Note You may find it useful to create a Trere 8 a aw G 7 T DEVICES ij ea J Jaideyp Temp folder for quick experiments Bo ae Gwea i and tests separate from your wo P main Project folder a an EA aesncn i at lida sti ct O Type a name for the new project ET an O lt o E Note The project is saved inside a folder Seo Aree with the new name Ors Click Save to create the new project Sic GQ All oum
25. elv e n m 7 A fx an arrow appears next to it and the Q p ee n E T a i i feotdapektatirs g s23 Shere Done navigation bar changes to display aera asi pause resume single step and other me iian A g O debugging icons SOA Fingered ar breskgender 1 fbh raer 1 apes ng Lee PF le Choose Run gt Debugger to open a new Hile Edit wiew Frajec Build TE uM Winco or 2 2 Chamed kE Mon 17 48 oh Q J debugging window Debug Bwakpointa Ori var W ae Run with Performance Teo pone aos Stop Artach ba Process Review the list of functions and aE ms aiii methods in the Overview pane AEEA TETEE Mini Debug T jikisa anar bandara r rar Err rra Clear Console RR e A pi O V 8 8 Click the updateString method to JC Debugger Display highlight it and show its variables Carnot Sacer Click self in the right hand variable Se _ viewer to show the variables used in ___________ sum am the updateString method and to sea ne vaiws man ies RO a reveal the string variable that has been oe back vid ca ben seal wo the sz a af ih Y POP on eg ne Fable Cain Wa ioe updated with your new test value You can now review other variables iy So ae rere onary tee ume te oe bc Sal es ha Laces aan and use the Step Over Step Into and eae wm Step Out buttons at the top of the window to continue testing and debugging Xcode s console is usually hidden You can show it
26. en a web browser and navigate to http developer apple com and then follow the links to find the most current enrollment page Note Apple regularly modifies its developer pages so the current URL may be different from the URL shown here 2 Click Continue and then follow the instructions that walk you through the complete signup process Note You must wait until Apple confirms your application before you can complete the signup process If you plan to develop applications for the App Store Select the Standard Developer Program 4 Pay for and activate your chosen program Note Steps 3 and 4 are optional You can download and install the iPhone SDK as soon as Apple confirms your application Navigate to the download location for the SDK Select your OS and then download the compatible SDK release Note The download may be between 2GB and 5GB Q OQ a Slab i ate ft abi eel uper apple cup AAA opk D walap r Conn a ee LZ oe ms i a i She ied oper apple cm Sipe 3 Appk Orecloper Contos i m actien eria Davakar Frege Entella y het force slari enu i Hii appia dee pr ai amp Developer Connection Complete the following steps to enroll in the iPhone Developer Program 2 1 Register as an iPhones Deeeioper If situ hasi mal araid signees ds an iPhone Devcaper we wil walk you tbrough the prones uy Pou ran emmmpble ati suhnmil pur errcadlcent iert saken a Frg
27. ent version of OS X Apple provides three levels of access to the SDK and its contents Anyone can read web versions of the documentation included in the SDK Useful outline descriptions of the development cycle and the documentation for the iPhone s libraries are available online However access to sample code and examples is not available To download the full SDK you must register with Apple s Developer Connection Registration is simple and free but Install the iPhone SDK requires confirmation from Apple Currently development is open to almost anyone who expresses interest Once registration is confirmed you can download the SDK package Installing the SDK gives you access to sample code and the development environment You can develop and test applications on the Simulator but you cannot install them on your iPhone share them with others or upload them to the App Store unless you pay a fee and enroll in the Standard Developer Program You can then provision your iPhone with a unique digital access key supplied by Apple to confirm it as a valid development target in Xcode submit your applications to Apple for possible inclusion in the App Store and create a limited testing program with up to 100 users Corporations developing applications for internal distribution can join the Enterprise Developer Program for 299 This supports in house development only The program does not allow App Store distribution Op
28. folder it is not moved to the corresponding folder on disk The file names in the Groups amp Files list are symbolic links to real files If you right click on a file and then choose Get Info from the pop up menu you will see a name and path Specification The name appears in the Groups amp Files list and can be changed to anything The path specification points to the real file Smart Groups Further Features Features The Implementation Files and Nib Files at the bottom of the Groups amp Files window are examples of Smart Groups You can use Smart Groups to automatically group project files according to search criteria that you define Choose Project gt New Smart Group to add a group Select Simple Filter Smart Group to add files with a simple file name search and the Regular Expression option to include files using a regular expression search Xcode includes a rich set of further features with corresponding windows in its menu tree Xcode s many debugging windows are described in Chapter 1 To use the Class Model tool choose Design gt Class Model gt Quick Model and it displays a graphical view of the relationships between project classes and lists their properties and methods For more on properties and methods see Chapter 2 You can view a Class Browser by choosing Project gt Class Browser This lists all the classes used in the project including those imported from frameworks mee elate e e SddIAIC
29. gukten vn the tst fied sent lzig gerbti igs Ul Tet be ld leeds bed eg See tee view first LoS display toe olor der beck thet s in the text fisd in bhs cobs k tbe check teckP ists p lacehobear i supe bebe d Shore Lie Laat at tie texi fLeld in bhe ring iia It atela te te sLd tet Nelowors xtb MulluWarld _Prulizgeh HelloWord pete apace H HellnWord Appitelegabe m EELS lcerd png E Fl info plist m maim SK A Mainindowsdb a Myviewtorhrnller OB MMviewCencraoliens ISK a E ReaiMetit 5 E et framre k di e BRyveetontrale m 6 D mhana nae amp itolewe bon eee contre ber Qeydesize pect Lele tenher baba lg Tenham stringi tau BANAT FIN vot O erat ests a ey inset dari Thiet e morts typing Saa the oler Eitor be tee best pled h Meld clsriwkocdi UTEt F ie eanl Eltin A owe toe vlee first leads display ths cloacabobser tet m e in ths ff stant wald in Sia Laba le che beck ect ne lid pil aeshr dar oud canestrirg O Press Tab to select the statement code block and then type an Code Sense auto completes an as animated Z Type Return to accept and skip and then type Y Code Sense auto completes Y as YES gt Tab to the Statement code block and then replace it with a call to NSLog and a String literal Code Sense does not attempt to auto complete the string literal Note Code Sense should recognize and auto comple
30. he standard iPhone interface objects including buttons Sliders text fields tables and pickers More generic interface objects including windows and views are also part of the library These provide a background for the interface and make it possible to add custom objects to an application When you sign up for the iPhone development program you receive download links for the latest version of Xcode Do not use the version on your OS X installer disk It will not be up to date and is likely to include bugs that have been fixed in the most recent version The iPhone version of Xcode includes both Mac and iPhone development tools These offer a similar development environment but use different tools and libraries Code developed in one environment is not guaranteed to run successfully in the other There are significant differences between the Mac and iPhone programming models and you will not be able to reuse code without changes The Simulator Simulator The Simulator appears on your desktop as a virtual iPhone or iPad The screen is clickable and there is a double touch feature for testing multi touch interfaces There is no GPS camera or accelerometer but limited work arounds for some of these missing features are available For example you can select images from the Simulator s photo library in place of direct camera capture A limited selection of Apple applications with preset data are built into the Simulator i
31. his text Click the viewDidLoad method Note The cursor is not placed at the start of the method If you begin typing without moving the cursor the method name is deleted and replaced 7 Add a pragma directive to any location in the file Click the Function menu again The label for the pragma mark appears in the list Note You can add as many pragma marks to a file as you need When you click a label name the cursor moves to the label and the entire label is selected Q Groups amp Flies mU ae gw a rt O 9 rullewerld E E My iewCentrullerm 5K Ej ReadMe cn Y Dela T HellewerdddppDelegeteh wi He boWorldip pDlegene m H MiywiewaCn rciler 4 By hie omraler mi Other Sources amp lt 3 Exeoetables 7 A Find Basulis ELIN bookmarks b HJ srm WD Project Symbals H leplen ernznion Files b Hin Files E Helioiridapp Delege a ey E MewCamralerm ft irar Pde History Fal am Hetory Lapari F in tnr ronaqeny tha Palin Pirin vor le Qorgian 17 Disclaimers IFPURTAMT This spgle softwars ws mugoli to you by agolo Dae ageless Lea consicesck lon of pour agrees ta tke following teri od yoe uot Levtoliotics weitiertlon os redistribetlon of this apale socteore comsbltubes gcomshoset of these berms JT ycu do nok ogee slth these cers plese do n5 ups inshell wodtey or sediscribwe tiles sople cofkecre Da cansicerstton nf your agressa fo diigs by bha tot long cares and ruhjack ti theen hare
32. iPhon S4 3 1 vith Mode 1 1 Gore Lacpard E ifihan S0 1 1 vith Xende 1 7 Read Me reve Lerga pi Time ay LE Fimi Quafgarelian Uhiity The SDK download is a standard DMG file so double click it to mount it Double click the MPKG installer to begin installation Step through the License Confirmation and Destination pages Select the elements to install Note You can leave most defaults unchanged You can choose not to install older versions of the SDK Choose Macintosh HD gt Developer to open the installed Developer folder 12 Add the Developer folder to the Places sidebar for ease of navigation Open the Applications folder to reveal Xcode Optionally add Xcode to the Dock for ease of navigation Create a new folder you can use to keep your projects in one location T7 nf A ie E iisk E Maciewech HO 68 8 x r T DEVICES B Eis E iisk EJ Macienesh HO Ese E wee 06 X nsw Bo Y SHARED Bi eaeme TRACES i Al ies AI rumes B A rages AI Movies B Ai tourens l Ii ia i dered LE KS amalakle About zode 4 have iphone_sce_3 1_with_xoode_3 2_final_snow_leopard_load42 dmy iPhone SOK m Name D prgects H Abour toode and IPhone S04 pdt El About Xoodeapp ii applications e B Audio Casheods app B Graphies Tess E Instruments ape Qa Interface Bullder app e D Performance Tool
33. in a run Open Xcode and then load the Hello World application Scroll down to find the line with the dViewController release Statement and then comment it out Note This deliberately creates a memory leak in the code Choose Build gt Build to build the application without running it Choose Run gt Run with Performance Tool gt Leaks to load the memory leak profiler The Simulator loads the application and runs it and the Leaks and Object Allocation Instrument window automatically appears 22 Lo Ruile avd Analyze Quile and Pan Bulle and Run Ereakpoircs OFF Ruild and Debug Rreakpeiras On Clean THEE ay Pad loro hie pee eae hr co evden cade Clean Al Targets H Paene ar h Meet Bulld Warning ar Error a aiiin Previews Quild Warring or Errar Comaile Preproness Show Assembly Code Touch sariei Pimi ed bnlis celi wppl icek zuin me LT Appl entire aon bear bins J d ier p bha tma ra lar A ieeiontreo ar aetor rc are Pitt iaetcckrs Ler well miui traller Wiri traller ve We ebar 5 COAG hoot ce pp ice ce sranie Ste le Ber E p ed bo pre At Add sha ata cont alloc invbec bod ibHema 8 on searld bundle i SSunedla Run Bresennints Coit Debug Areakogints On Run with Performance To Grapa Files TE Helami Y aeachte cat Th Oat H Had biiir ida poled iah BD raterrorites ef Mar eb pelag eu r H MpSeatcnnrslar h E Mysicelentrallere Ti
34. ints For details see Managing Program Execution in the Xcode Debugging Guide section of the Xcode documentation Open Xcode and then load the Hello World application Click the MyViewController m file to open it in the Text Editor window Scroll down to the updateString method declaration and then place the cursor at the start of the last line before the closing curly bracket b j KO Fibs Choose Run gt Manage Breakpoints gt Add Breakpoint at Current Line An arrow appears next to the selected line of code to indicate that a breakpoint has been added 2 Dee Debug Breakpaints On em BB inate raion Fikes d GT Deign sa Debug Run Breakpoints OF Qy iina Maichiig Coda o i 35K 9 han with Pedormaace Too maen Stop i a H Meacan itach to Process m Debugger cH Mini Dehiagger apns Console THR Clear Gansale TER Show F Debugger Display k Wariakies Wits k Deactivate Breakpoints H Shop en Dhjertiee i Fence peeing 4 Manage Greakpaints F Add Breskpoint at Current Line HI Add Speniholic Breakpoint Fie so add C Cscepton Greakpaint ee bt Enable Breakpalnt at Qurrevt Une WHI biel Import Break piiris pwi Slee Over THO Export Ereakpoints 0 atari Step Gut HT teres Mexi Thread CRT ES moai Previous Thread CL fick t t on ine ee kes sad sen with Debugger x Stop on Cebugee i Cebugstri eu Enable Guard Mallee
35. lick Bookmarks in the Groups amp Files pane The bookmark appears in the Bookmarks list An editable list of bookmarks appears in the Detail View Click the Bookmark icon in the Text Editor navigation toolbar The pop up list appears with the new bookmark added You can move the cursor to the bookmarked location by clicking the bookmark E Faste and Match Style Delete Select All Duplicate Refactor 7H Convert bo Objective C 2 0 Format Tene id ieuna bere Tu Bookmarks Kowt Completion Completion List Select Next Flaceholder Edie All in Scope Insert Text Macro Spelling Special Characters TTT Rese lihu Raa Tee bald LEhaTetr ial 7 dr aner Ess Weer PTAC SAET aha teu e Prom Eee beck feos ea that the keter Ix dizeizzadd aF Ete eet tald ma toc ialdd Ease tala rarig irr li rr Imejaa Ee misl ir cer che ting aat aadabeitrirmg vhiitanmaler ne I7 O E Mew Taner re I ER A E Frajeer tenba B macner Fikes o o gal HUW Fie a e Bvvesetoeralenmi E piai T bee in deruseessheitrig JJ Ekora bes tect af the cat bald in tha ebriega ceeksect troscis ra p rbr a tect iali ss Tap Pee tact m tha inhl sa shes ala a bha ririrg rks ccm arrihla m Fact a esl fete ire IIL ikek althaea LhhaTeetr ial er avu Pre urar pArA Tauri bA Torao ee Pren kea beck fueli ea thtt the kateri lx dixeimad sF Eta ee tale ma toc iald Thesk tala rarigr
36. m e O o T Untouch Delete Duplicate Build MyClass Bulld MyClass and Start 7 Build MyClass and Debug i gt Herat Clean MyClass vi Biki b gad SIE Files wu You can now change the build settings if you desire Xcode does not include features for copying or renaming projects You can typically copy a project by copying its folder to a new folder with a different name By default the links in the Groups amp Files window are created so they are relative to the folder root This is not always the case To avoid editing a file from the original project by accident you should double check that the links have been updated correctly Xcode 3 2 includes the Rename tool for renaming application targets Choose Project gt Rename You can use it to change the name that appears under the application icon in Springboard This feature does not rename any of the other files in the project It is also buggy and might delete your project file There is no easy way to rename an entire project in one click including all the source files One work around is to create a template from your project using placeholder template names for key files Alternative semiautomated solutions are available online For example see http mohrt blogspot com 2008 12 renaming xcode project html
37. me Profiler Debugger Threads Mini Gebugger Cansale Clear Comscle Show Debugger Disnlay wariabes View Activate Breakpoints AHI Sieg an Objective C Exceptions Manage Rreaseniots b midden Termninatian Multicure GE Wonlbar Fa Anivity Disp ra Core Daa Hem Large OpenGL 5 Core n nation Dhjet Allocations 4 Leaks CPU Sampler Acthalby Monitor i eH Fi Pause parina on File Shep Inbo P 45 rins Step Tver i Step Dut Next Thread Preis Thread Sere w h Gesuge Ed Stoo on Debupae i Debugstr Enable Guard Mallee Looe inikkite akee Hel cece L7 barile Eai wiri Die ntin ae an ak burara OT brite cite copes 4 airing Mancting i Instrument Shon E Zombies Altach to Process UI Reggie bA ja 4 ObjectAlloc window Es ee mei Review the timeline in the Leaks and i 0009353 Note The Hello World application includes a small o leak e OMT Cc which is visible in the Leaks timeline This is a bug in the Simulator ro J Jaideyp e e ponui Review the memory allocations shown in the detailed view e Note This is a complete list of all the memory allocations in the application I suion e d SO 900d t u m ca s s oh het summary g Type a test string in the application Dee AEE ee 00 03 25 ra in the Simulator to trigger a T a
38. ncluding Photos Contacts Settings and the Safari browser Other applications are not available When you compile an application it is installed on the Simulator and runs immediately Old applications are not deleted but you can rearrange and delete applications just as you can on the iPhone The Simulator runs Intel x86 code and not code compiled for the ARM processor used on the iPhone Simulator performance is not a guide to performance on a real iPhone and running speeds may be very different Applications that rely on real time graphics and sound or other performance features should be tested on real hardware Xcode and GCC and GCC Xcode is based on a modified version of the Gnu Compiler Collection GCC and includes support for all the C variants including Objective C which is the default language for Mac and iPhone development and for other languages that are not relevant to iPhone development Most of the iPhone libraries are written in Objective C some features of the OS still use conventional C calls It is sometimes faster and more efficient to define C functions in your code than to create complete Objective C class definitions Xcode can handle either option Xcode Instruments Instruments Advanced Xcode Xcode Instruments add code profiling and memory management to increase efficiency and eliminate memory errors one of the prime causes of application crashes on the iPhone The package is based on Sun
39. one or more subfolders of a main project or archive folder To select a target platform click the Compilation Configuration drop down menu By default only the iPhone Simulator option is available You can also choose a debug configuration for testing or a release configuration to create a leaner application that requires less memory You can install a release build on your own iPhone but you cannot upload it to the App Store For information about creating a configuration suitable for distribution via the App Store see Appendix 1 Selecta sample application from the documentation Note See the section earlier in this chapter for more on finding sample source code Click Open Project in Xcode Select a target folder Optionally click New Folder to create a new target folder Note You do not need to create a folder for the project itself It is automatically created in a new subfolder aF fire Click Choose to confirm your TA selection A E Moe DSX aall DWD 7 SHARED E rire 7 PLACES GE Deve oper EA Desktop i Muin Ty Docements EJ moies J Husie F rtra JA applicanens 7 SEARCH FOR T Toeay CU Yasmerday LD Past Wark GE ni mages Man siias The sample application is copied to the target folder decompressed and then automatically loaded in Xcode View Source Code geiert Fie F Span Projet in Meu PHellaWorld iPhomezip 346 4K HelloWorld Ve
40. ons For details see Appendix C The iPhone and iPod touch have limited battery life You must take care to manage power by suspending software features in your application when they are not needed Hardware features such as the camera GPS and accelerometer generate waste heat which dramatically decreases battery life It can also make the iPhone uncomfortable to hold and affect its reliability These hardware features should never be left running when they are not required The iPad offers improved battery life and power management is not quite so critical However your application should still suspend non essential features whenever possible You can support users by relying on the standard Cocoa Touch interface library to manage scrolling text input and other interface essentials Applications should not include features that require a complex manual and operation Should be as intuitive as possible I sulIDNpOoNyY 1 Jojdey e d SO 904d e A a O V Install the iPhone SDK A ah oe ou can get started with iPhone development by downloading and installing the iPhone SDK The SDK includes the latest version of the Xcode development environment as well as a full set of documentation for the current version of the iPhone OS You do not need an iPhone to develop with the SDK Xcode includes a simulator on which you can test applications The only prerequisite is an Intel Mac and the most rec
41. oper pages of your Apple account once you have been accepted into the program ou can speed up the development process by beginning a project with one of the Xcode project templates Each template includes a minimal set of files and features and implements an application with a certain type of interface For example the View based Application template creates a blank screen which is an example of an iPhone view a screen that you can fill with settings and information The Utility Application template creates an application with two views as well as buttons to flip between them For more on views see Chapter 3 Templates are not complete sample applications If you compile and run them they either do nothing at all or very little Many of them do not respond to user actions But they do offer a skeleton for an application You can Open Xcode Choose File gt New Project EG If it is not already selected click Application MY Choose a template Review a brief description of the template and its features Click Choose to confirm your selection A Save As dialog box appears allowing you to specify a file location for the new project fill out this skeleton by adding further features to create a working application Templates are built into the Xcode workflow and are not an optional feature Whenever you create a new project you begin by selecting one of the templates Although it is possible to cr
42. opers It is good practice to investigate new OS features when they arrive in beta and to consider new apps that support them but not to commit application code until the beta OS has stabilized and Apple mandates a move to the new OS Introducing Xcode and the iPhone SDK ou can develop applications for the iPhone and iPad with Xcode Apple s iPhone and Mac development environment Xcode requires an Intel compatible Mac running the latest version of OS X It does not require an iPhone or iPad because a simulator is included Most but not quite all of the iPhone s software and hardware features are modeled in the Simulator Xcode includes a complete suite of tools for application development including a compiler and editor interface designer web app tool kit performance profiler and the Simulator Interface Builder Builder Interface Builder is a visual interface design tool It includes a selection of tools that manage links between visual interface objects such as buttons and sliders that appear on the iPhone s display and the software objects and message handlers defined in your code Interface Builder is not a complete visual development environment It is a hybrid tool that includes visual features but also displays lists of objects and methods You must define these objects and methods in your code before you can use them in Interface Builder Interface Builder includes a library with instances of all t
43. pi o The project is created by using the selected template and is automatically loaded into Xcode 10 Review the list of files in the project Optionally you can build and run the project Fawn k Do reer Eget d SO 904d e The project is now ready for editing bd Peerardtdes TO Pied esihe a WA Tesio pide pae ra rh A pi O V m a cere ler ra No Editor You can get the most from templates by creating your own With custom templates you can move beyond the minimal features included in the standard templates to create skeleton applications with a more comprehensive set of features In Xcode 3 2 the template files are available in Developer Platforms iPhoneOS platform Developer Library Xcode Project Templates Application Each folder in this directory appears in the Xcode s Template window To create a custom template drag copy one of the folders to create a duplicate for example Navigation based Application 2 Open the folder to find the __ PROJECTNAME __ xcodeproj file Double click this file to open it in Xcode You can then edit source code add further source code or Interface Builder files include custom icons and so on To rename the template rename its folder Do not change the _ PROJECTNAME__ and ___ PROJECTNAMEASIDENTIFIER__ labels These labels are automatically replaced when you create a new project Work with Xcode s Auto Completion Features ou can use th
44. plications must include basic memory error handling because they may be run on an iPhone with limited free memory You must carefully design applications that use large media files to avoid exceeding memory limits User Expectations Expectations The iPhone programming model assumes that only one application is active Although the iPhone OS is a variant of Unix there is no official support for multi tasking or background execution Users expect applications to launch almost instantly with an equally instant suspend on demand feature Applications should save and restore their States automatically and interfaces should be simple and elegant and follow Apple s design guidelines GL 2 0 graphics acceleration and a faster processor than the base 3G model There is a small but increasing market for premium applications for the 3GS offering extra features and performance at a premium price As long as Apple continues to sell the 3G and the 3GS developing exclusively for the 3GS will limit your application s market However you can assume that most users will upgrade within 12 to 18 months of each new model s release date The latest iPod touch range includes the same enhanced graphics and a faster processor The iPad extends the iPhone OS family in a new direction with a larger touch screen faster processor and additional OS features The core programming model remains largely unchanged but the interface supports new opti
45. ram barsi pa por preler et i Pete of dsrin en epi aia Phere I pos raat hares an Inigloaeed Mar rann rej Mar J5 X erpa Dorie wra dagie fap dl righ reirei Teens of ige Baay Sdi i os a Phase Day Cantar Apo Davaloper Connection I iPhone Dey Cenixr pele Dev 2 Leam che Findarenral reres aed E Sore Bil Proyamminp Gude beprate fur iFbune dee eat Hews and Announcements Banc W Proyremmng Guede Tigi aa Submining Four E tul Copp ard Fuste py ls lbr App itar cen 4 2008 E Bsleread Qceceory Framework Selene IPhone Amerens Uhrary FF Sakat fron a aro oe er brieyi Drenori un Plane dees eae Credleg How To s tee Leam hers co laren features oF Phire in ite aliki E Maz Ket Framer Relercice Semele Cade oecdia Player Framework Referente Yar Ape et lice thee copes tn ingie daor af p i PAA yuu en goaa appa T E Fuir Piret Agplicalion wilh Cure Daia E Anale a vaia ean Piiraa Been E Phoe OS 5 0 Neadiness Chwhlisk z ihin we lng whe her eT fw ii hendurs anj Apel PATI m anis Te Taiu paker evan Cua hiia xf incerta Finne Appr ug IE J0 eel tar nrJ Sars ws cra isa Dehn S ST Phare S08 2 Lac udes the Monde Foares Segreriber amp fei Laspard Gulls PHB Teres larni Bold ATF DF Pee dwumer sida uire oF addhtig nal poal For deakigi raj apikan Tor Bhore aral Prd liani kania fhaa SO 3 1 with Arde 3 1 jlenpardi E fharr S0 1 1 wih Xende 1 1 Read Me Lena Emar Lespard Caran bends E
46. rrectly balanced Code Sense is not supernaturally intelligent and often makes mistakes so you should review its guesses But it is a very useful time saver It is worth taking the time to master it so you can benefit from its features without having to think about them consciously Open the Apple sample Hello World application in Xcode and then click the MyViewController m file to load it in the Text Editor Type void viewDidA Code Sense inserts various guesses as you type Type Return to select the guess that includes the String viewDidAppear Type a curly open bracket and then type Return Code Sense automatically indents the cursor on the next line O Type if Code Sense automatically inserts conditions and Statement code blocks for an i statement and then adds appropriate curly and plain brackets around them Q Tenhi abe Lng QO eo dbo ide fe commas q _ amp piat aia i code lo a al hr bgrowd pny S Dehwitpng Enurcation Tramea rk yi HelloWerke_app A 4 Hel hoWorbcLd bo NelloWorkd_Frefix pch HeloWorleapoDckguce h H HeloWorkAppbelegace m aak inant pny info plist 3 Ei maine SK A MainWinduw sik E MyViewCoenrallerl Mpima onbmilar ISk a E ReadMe i Jeedramework aie Viewlonrolenms B Gimplemeraton ewCeenraller Ar Cyr Ey T ne divlewidlood f Pree tee uses storks being show the cles
47. rsion 1 7 Posted 2008 07 07 Build Requirements Mec 05 X 1005 3 eode 3 1 iPhore 05 L0 Runtime Requirements Mar OS X 10 5 3 iPhone OS 2 0 Description HalleiWerld demonsmates hiis p uae a kbayhnard m enter Taxt imo a raxt field and hows mi display che reat in a lakel Document Revision History Datt Notes 2008 07 07 First public release Did thik derument help you Yes h s good bur Nos halpful_ Shared Folder e H ZevaloramgiarGragh Today 90 03 b ig AddressBook1 TOE Aral i amp B Copy test i pels anita b D Delete Teer Yesterday b D My First Agplication TEMERARA THE a G Mels B1LyOR 200 b D Hame Teer apay 200s b H Selector test oo ooo P ij Sgning test FO OR ees i aur 0408 2009 e Gy Test 14 08 2009 P i TransWweb Ora 08 B Liaraleg 10 03 2009 b H URLMessagingTasr Orgs 2002 b D Very simple test POOR Pon t i Window 14 08 2008 i Tress 5 O Select the Simulator option from the 6 stata Q Compilation Configuration menu maa pra ee n el a ae a O Y E He Werd Fockgragnd prg i E Rarita rar ReFauh arg Ss Click Build and Run to build and run pases naa J o the application E nnianaenn Em oo E ae ow Review the status of the compilation damier a process in the status bar torn i wenmacnntere ss eam a wet r S The application is automatically p emarian nie installed in the Simulator tini O pi o he i e
48. s EP Quaniz Composerape F Liniliries E webbjects TA Moodeapp E D Archive 1 CenificaneSigningRequest cerSigringmecuess 4 develeser identity cer D Decumentation e D Danha D Examples b D Extras b D Headers E Ubay e Wakes lh MyProve toningPrcRle mobleprowision e B Aatomi b E iks E Tois e D usr Mab Mrcified 10 September 2009 O6 1e Parkace Kame Wl Essentials B iPhone SUK TO iPhone SDE 3 0 E Spare Tonle F Doorwrtaan O Dai Mndat Today Lach 31 July 2009 doce 6 June 20s 02 32 20 Awgust 2009 20 52 PO Argus ANG 208 21 July J909 HE23 10 Sapreriber 2008 1A 2F July P909 19 11 July 2009 IXE 10 Sephersteer 23 16 29 28 Way 2009 05 08 Ti Sapneraber 200 1 R24 18 June 2S 12 11 21 July 2009 he 20 1 July P009 22081 20 Awgust S009 21 11 HI Agust ANG 11 20 10 September 2009 18 29 5 Soprambear 2009 00 45 10 September 2009 16 29 30 Awgust 2009 20 52 16 May 200 16 09 10 September 2003 18 29 20 Aisgquer A009 20 52 OU Agust SUS 11 14 20 Auqusr 2009 27 40 Pl Argus A009 20 88 10 September 2005 16 30 DO Argut ANN 20849 E Phare SOE 3A 5 E UM Dovanpmani O Ma 05 X 10 4 Sup Custom Install on Macintosh HD lorafion D oeve cper mlali Bery KE natal Pert KE Rire ni 2 44 Ga Osk Image aman s i Upgrade 4 1302 Upgrade 35 4 ME Upgrade 3ER ME Upgrade 575 ME Install Zero KE Skip Zero KE tira End 38 1 ME EE KE
49. s organized in sections that matched each OS release After Xcode 3 2 the presentation was streamlined Reference material tutorials and links to sample code appear in a single browser like window In Xcode 3 2 you can find links to the sample code library However neither list is comprehensive You can find further links to source code on the Class Reference pages See Chapter 2 for details You can also find incomplete code snippets in some of the reference sections You cannot usually use this code as is without significantly expanding it All the sample code listed on the main reference library page and in the Class Reference is packaged as a complete Xcode project You can download this project and then load it into Xcode and it should compile and run immediately without changes However some code samples are saved with legacy settings and may generate errors You can usually eliminate the errors by setting a new target environment by using the drop down menu at the top left in the main Xcode window for example Simulator 3 1 2 Debug or by saving the main files closing Xcode and then reloading the project at the top left of the documentation window under the Resource Types tab The main Documents window also lists links to the sample code and you can create a list of links by clicking the Resource Types sort header in the title bar and then scrolling down to view the list Explore the Sample Code Libraries
50. t if the compilation failed It also displays information about the status of the current run once an application has been installed in the Simulator or in an attached iPhone Use the Previous and Next arrows and the File History menu to move through your edit history The Function Menu displays a list of code sections On the right from left to right the Bookmarks Breakpoints Class Hierarchy and Included Files icons open drop down menus when clicked Counterpart button swaps between header and implementation files and a Lock button prevents editing You can split the Text Editor to view multiple files by clicking the Split icon under the Lock button Q The Groups amp Files list displays a complete summary of all files and other information associated with a project including a complete file list a class summary a list of included frameworks compile targets and other resources Compilation Configuration Choose options from the Configuration drop down menu to run the compiled application in the Simulator or on an attached iPhone This menu also Summarizes active targets and sets debug or final release status Understanding Xcode Work Areas The Groups amp Files List The Groups amp Files list is the key to managing an Xcode project It summarizes all the components of a project and defines the compilation products and targets However many of its features are not intuitive or obvious are not immediatel
51. te NSLog but does not This is a bug Add a final closing curly bracket Code Sense automatically moves the closing bracket to the far left and then flashes the corresponding Opening bracket a A MyViewController m 58 viewDidAppear implementation AyViewControl ler synthesize textField synthesize label synthesize string void viewDidd ppear BO0L Yang gted J Sp tonimated lt __p statements voidjviewDidLoad fer When the user starts typing show the clear button in the text field textField clearButtonMode UlTextFieldViewModeWhi LeEditing fe When the view first loads display the placeholder text that s in the ff text field in the label label text textField placeholder voidjupdatestring x h A MyViewController m 59 viewDidAppear implementation AyViewControl ler synthesize textField synthesize label synthesize string void viewDidd ppear BO0L animated if animated YES NSLogf Animated _ _ amp O voidjviewDidLoad fe When the user starts typing show the clear button in the text field textField clearButtonMode UlTextFieldViewNodeWhi leEditing fe When the view first loads display the placeholder text that s in the ff text field in the label lobel text textField placeholder onid mda ankan oF You can use a shortcut to select from the list of possible options offered by Co
52. te with its own products because its air time partners have refused to Support them or for other reasons that remain inscrutable However most applications are accepted Many are profitable Some become very profitable indeed This book includes information about developing native applications However web applications remain an interesting option on the iPhone When the iPhone was first released no native SDK was available All applications were developed as web apps for the iPhone s Mobile Safari browser which was optionally supported by server side data management Web apps blend HTML CSS JavaScript and AJAX to create an interface that mimics the iPhone s native interface Flash is not supported Web apps are not listed in the App Store but you can submit them to Apple which lists them in a dedicated area on the Apple web site You can also direct users to your web app within Mobile Safari via a Standard URL If you are familiar with web technologies and if your application is relatively simple you will find it is easier and faster to create an iPhone web app than a native application The disadvantages of apps are limited performance and limited support for the iPhone s enhanced hardware features Unlike stand alone applications most web apps do not work offline Web apps are not covered in detail in this book They remain a legacy option for projects that aggregate and summarize web information and manage user interaction
53. th this menu You can use the Bookmarks menu to remember the current cursor position in each file When you select a Speed Up Editing with Pop Ups and Bookmarks TA bookmark the cursor moves to the saved location The bookmark list for each file is independent However the Bookmarks group in the Groups amp Files pane shows a complete list of project bookmarks You can use this list to move quickly between bookmarked locations in different files You can also click the Bookmarks group to reveal a bookmark editor page This list is designed for renaming bookmarks rather than for quick navigation Single clicking each item selects the relevant file but does not position the cursor Double clicking an item moves the cursor to the correct position but in a new Text Editor window Open Xcode and then load the Hello World application 2 2 Click HelloWorldAppDelegate m The contents of HelloWorldAppDelegate m appear in the editing window The file is automatically but invisibly added to the file history list Click MyViewController m Click the File History pop up menu The two files appear in the recent history list Note You can use the Forward and Back arrows to move through the recent history list Click the Function menu to reveal a list of variables methods and functions Note Until you select an item the Function menu title is lt No selected symbol gt You can display the menu by clicking t
54. uble click the list to show ee oe sino a text size and font selector eee cae ubere Hunano Use spntaxw based farmatting C Use colors when printing Color indexed symbols Copy colors and fonts Scroll through the complete list of preferences to soc e Glee cs ee S review their features p gt Select optional features to ee a err Se eres were S suit your preferences aaa on for example to load non a E essential documentation ead 12 Deve Tat Uy aaa fy A Phone 0S 2 Ube D hniple Cade b ra ries Phone O3 72 1 Library Fi Related Dexcutesis iPhone 08 3 0 Library i Phone 08 Library hone 05 library LER EY A ee ponui application target i File Mame al G E corebraptees rammen E 1 a foundation framenntk E mAn P Malr noih O ee eae tas Universal Access a _ Newer use font sizes smaller than pH pi o ae P S Click Targets to reveal the aah teed same T a O V J Right click on the application target and then choose Get Info from the pop up menu Review the Application Preferences and then click through the tabs Click the Build tab to reveal the build settings and then scroll down to review the complete list of all build Settings Corfquearon Aches Detar a Ole Search ia Build Selling MipTlasaappelegane m Shue Al Eettings Mp lass erona rm E ipl las Ya conira har xia e O A
55. ulator or on an iPhone handset These two environments create different results with different features and options But the principles of profiling an application s features using one or more Instruments are the same for both The Instruments display is split into four areas A toolbar at the top shows key settings Under it the Instruments timeline displays important changes in the status of the settings and features you select for monitoring Beneath the timeline is a detailed view pane which shows relevant variables and other monitored settings Profile and Improve Your Code To the left of the detailed view is a control pane Use this to select between the different options that can appear in the detailed view To use Instruments build an application using the Build feature choose Run gt Run with Performance Tool and then choose from the list of available instruments in the drop down menu The list of instruments available for iPhone development is a small subset of those available on the Mac The tools do not always distinguish between Mac and iPhone monitoring so you should use caution when viewing and interpreting the results You can save an Instruments run to review it later or to compare it with other runs Saving it saves the timeline and the current detailed view You cannot scroll back to watch changes in the detailed view but you can move the timeline play point backward and forward to watch a summary of changes
56. y visible or are simply confusing You can use the Classes folder to review the list of classes in your project Projects that use the Xcode Templates list all the pre included classes here However if you add a new custom class it is not moved to this folder automatically You must move it manually You can load most source code files into the Text window by clicking them However you must double click to open nib files which are used in Interface Builder because Interface Builder is a stand alone application and is not built into Xcode If you double click a source code file it opens in a new maximized floating Text Editor window You often need to add a framework to a project The menu option for adding a framework is not included in the main menu tree To add a framework right click on the Frameworks folder choose Add Existing Frameworks and then select one or more frameworks from the floating list that appears See Chapter 3 for more on frameworks Symbolic Links and Real Files Links and Real Files One of the more confusing features in Xcode is that the list of files in the Groups amp Files list may not mirror the corresponding files in a project folder If you delete a file from the Groups amp Files list the file is removed from the project but it remains in the project folder Similarly if you rename a file in Xcode the original name on disk is not updated If you move a custom class so it appears in Classes

Download Pdf Manuals

image

Related Search

Related Contents

DEI® RAINBOW  user guide - Belfield Software  Guest Pager Anleitung    Equipo de factor de forma pequeña Dell OptiPlex 7020 Manual del  NT11S Manuale dell`operatore  Sony MHC-GSX75 User's Manual  Paper 175    Samsung YP-Z3AW Benutzerhandbuch  

Copyright © All rights reserved.
Failed to retrieve file