Apple SharkUserGuide.pdf Manuel
Apple sur Fnac.com
- Pour voir la liste complète des manuels APPLE, cliquez ici
-->
ou juste avant la balise de fermeture -->
TELECHARGER LE PDF sur :
Commander un produit Apple sur Fnac.com
Voir également d'autres Guides et documentation APPLE :
Apple-InstrumentsUserGuide.pdf-manuel
Apple-Logic-Pro-9-TDM-Guide-manuel
Apple-macbook_air_users_guide.pdf-manuel
Apple-macbook_air-13-inch_mid-2012-qs_ta.pdf-manuel
Apple-AppStoreMarketingGuidelines-JP.pdf-Japon-manuel
Apple-macbook_pro_retina_qs_ta.pdf-manuel
Apple-ipad_user_guide_tu.pdf-manuel
Apple-ipad_user_guide_th.pdf-manuel
Apple-iphone_user_guide_gr.pdf-manuel
Apple-Nike_Plus_iPod_Sensor_UG_2A.pdf-manuel
Apple-ipad_manual_del_usuario.pdf-manuel
Apple-ipad_uzivatelska_prirucka.pdf-manuel
Apple-ipad_wifi_informations_importantes.pdf-manuel
Apple-Xsan_2_Admin_Guide_v2.3.pdf-manuel
Apple-macbook_pro-13-inch-late-2012-quick_start.pdf-manuel
Apple-CocoaDrawingGuide.pdf-manuel
Apple-Cryptographic-Services-Guide-manuel
Apple-Resource-Programming-Guide-manuel
AppleSafariVisualEffectsProgGuide.pdf-manuel
/Apple-WorkingWithUSB.pdf-manuel
Apple-macbook_pro-retina-mid-2012-important_product_info_f.pdf-manuel
Apple-iOS_Security_May12.pdf-manue
Apple-Mac-Pro-2008-Performance-and-Productivity-for-Creative-Pros
Apple-iPod_shuffle_4thgen_Manuale_utente.pdf-Italie-Manuel
Apple-KernelProgramming.pdf-manuel
Apple-Core-Data-Model-Versioning-and-Data-Migration-Programming-Guide-manuel
Apple-RED_Workflows_with_Final_Cut_Pro_X.pdf-manuel
Apple-Transitioning-to-ARC-Release-Notes-manuel
Apple-iTunes-Connect-Sales-and-Trends-Guide-manuel
Apple-App-Sandbox-Design-Guide-manuel
Apple-String-Programming-Guide-manuel
Apple-Secure-Coding-Guide-manuel
Apple_AirPort_Networks_Early2009.pdf-manuel
Apple-TimeCapsule_SetupGuide_TA.pdf-manuel
Apple-time_capsule_4th_gen_setup.pdf-manuel
Apple-TimeCapsule_SetupGuide.pdf-manuel
Apple-TimeCapsule_SetupGuide_CH.pdf-Chinois-manuel
Apple-CodeSigningGuide.pdf-manuel
Apple-ViewControllerPGforiOS.pdf-manuel
Apple-KeyValueObserving.pdf-manuel
Apple-mac_mini-late-2012-quick_start.pdf-manuel
Apple-OS-X-Mountain-Lion-Core-Technologies-Overview-June-2012-manuel
Apple-OS-X-Server-Product-Overview-June-2012-manuel
Apple-Apple_Server_Diagnostics_UG_109.pdf-manuel
Apple-PackageMaker_UserGuide.pdf-manuel
Apple-Instrumentos_y_efectos_de_Logic_Studio.pdf-Manuel
Apple-ipod_nano_kayttoopas.pdf-Finlande-Manuel
Apple_ProRes_White_Paper_October_2012.pdf-Manuel
Apple-wp_osx_configuration_profiles.pdf-Manuel
Apple-UsingiTunesProducerFreeBooks.pdf-Manuel
Apple-ipad_manual_do_usuario.pdf-Portugais-Manuel
Apple-Instruments_et_effets_Logic_Studio.pdf-Manuel
Apple-ipod_touch_gebruikershandleiding.pdf-Neerlandais-Manuel
AppleiPod_shuffle_4thgen_Manual_del_usuario.pdf-Espagnol-Manuel
Apple-Premiers-contacts-avec-votre-PowerBook-G4-Manuel
Apple_Composite_AV_Cable.pdf-Manuel
Apple-iPod_shuffle_3rdGen_UG_DK.pdf-Danemark-Manuel
Apple-iPod_classic_160GB_Benutzerhandbuch.pdf-Allemand-Manuel
Apple-VoiceOver_GettingStarted-Manuel
Apple-iPod_touch_2.2_Benutzerhandbuch.pdf-Allemand-Manuel
Apple-Apple_TV_Opstillingsvejledning.pdf-Allemand-Manuel
Apple-iPod_shuffle_4thgen_Manuale_utente.pdf-Italie-Manuel
Apple-iphone_prirucka_uzivatela.pdf-Manuel
Apple-Aan-de-slag-Neerlandais-Manuel
Apple-airmac_express-80211n-2nd-gen_setup_guide.pdf-Thailande-Manuel
Apple-ipod_nano_benutzerhandbuch.pdf-Allemand-Manuel
Apple-aperture3.4_101.pdf-Manuel
Apple-Pages09_Anvandarhandbok.pdf-Manuel
Apple-nike_plus_ipod_sensor_ug_la.pdf-Mexique-Manuel
Apple-ResEdit-Reference-For-ResEdit02.1-Manuel
Apple-ipad_guide_de_l_utilisateur.pdf-Manuel
Apple-Compressor-4-Benutzerhandbuch-Allemand-Manuel
Apple-AirPort_Networks_Early2009_DK.pdf-Danemark-Manuel
Apple-MacBook_Pro_Mid2007_2.4_2.2GHz_F.pdf-Manuel
Apple-MacBook_13inch_Mid2010_UG_F.pdf-Manuel
Apple-Xserve-RAID-Presentation-technologique-Janvier-2004-Manuel
Apple-MacBook_Pro_15inch_Mid2010_F.pdf-Manuel
Apple-AirPort_Express-opstillingsvejledning.pdf-Danemark-Manuel
Apple-DEiPod_photo_Benutzerhandbuch_DE0190269.pdf-Allemand-Manuel
Apple-Final-Cut-Pro-X-Logic-Effects-Reference-Manuel
Apple-iPod_touch_2.1_Brugerhandbog.pdf-Danemark-Manuel
Apple-Remote-Desktop-Administratorhandbuch-Version-3.1-Allemand-Manuel
Apple-Qmaster-4-User-Manual-Manuel
Apple-Server_Administration_v10.5.pdf-Manuel
Apple-ipod_classic_features_guide.pdf-Manuel
Apple-iPhone_Finger_Tips_Guide.pdf-Anglais-Manuel
Apple-Boitier-de-l-ordinateur-Manuel
Apple-Guide_de_configuration_de_l_Airport_Express_5.1.pdf-Manuel
Apple-iMac_Mid2010_UG_F.pdf-Manuel
Apple-MacBook_13inch_Mid2009_F.pdf-Manuel
Apple-MacBook_Mid2007_UserGuide.F.pdf-Manuel
Apple-Designing_AirPort_Networks_10.5-Windows_F.pdf-Manuel
Apple-Administration_de_QuickTime_Streaming_et_Broadcasting_10.5.pdf-Manuel
Apple-Opstillingsvejledning_til_TimeCapsule.pdf-Danemark-Manuel
Apple-iPod_nano_5th_gen_Benutzerhandbuch.pdf-Manuel
Apple-AirPort_Extreme_Installationshandbuch.pdf-Manuel
Apple-Final_Cut_Express_4_Installation_de_votre_logiciel.pdf-Manuel
Apple-MacBook_Pro_15inch_2.53GHz_Mid2009.pdf-Manuel
Apple-Network_Services.pdf-Manuel
Apple-Aperture_Performing_Adjustments_f.pdf-Manuel
Apple-Supplement_au_guide_Premiers_contacts.pdf-Manuel
Apple-Administration_des_images_systeme_et_de_la_mise_a_jour_de_logiciels_10.5.pdf-Manuel
Apple-Mac_OSX_Server_v10.6_Premiers_contacts.pdf-Francais-Manuel
Apple-Designing_AirPort_Networks_10.5-Windows_F.pdf-Manuel
Apple-Mise_a_niveau_et_migration_v10.5.pdf-Manue
Apple-MacBookPro_Late_2007_2.4_2.2GHz_F.pdf-Manuel
Apple-Mac_mini_Late2009_SL_Server_F.pdf-Manuel
Apple-Mac_OS_X_Server_10.5_Premiers_contacts.pdf-Manuel
Apple-iPod_touch_2.0_Guide_de_l_utilisateur_CA.pdf-Manuel
Apple-MacBook_Pro_17inch_Mid2010_F.pdf-Manuel
Apple-Comment_demarrer_Leopard.pdf-Manuel
Apple-iPod_2ndGen_USB_Power_Adapter-FR.pdf-Manuel
Apple-Feuille_de_operations_10.4.pdf-Manuel
Apple-Time_Capsule_Installationshandbuch.pdf-Allemand-Manuel
Apple-F034-2262AXerve-grappe.pdf-Manuel
Apple-Mac_Pro_Early2009_4707_UG_F
Apple-imacg5_17inch_Power_Supply
Apple-Logic_Studio_Installieren_Ihrer_Software_Retail
Apple-Aperture_Getting_Started_d.pdf-Allemand
Apple-getting_started_with_passbook
Apple-iPod_mini_2nd_Gen_UserGuide.pdf-Anglais
Apple-Deploiement-d-iPhone-et-d-iPad-Reseaux-prives-virtuels
Apple-Mac_OS_X_Server_Glossaire_10.5
Apple-iphone_bluetooth_headset_userguide
Apple-Administration_des_services_reseau_10.5
Apple-iPod_nano_4th_gen_Manuale_utente
Apple-iBook-G4-Getting-Started
Apple-Guide_des_fonctionnalites_de_l_iPod_classic
Apple-Guide_de_configuration_d_Xsan_2
Apple-MacBook_Late2006_UsersGuide
Apple-Mac_mini_Mid2010_User_Guide_F.pdf-Francais
Apple-PowerBookG3UserManual.PDF.Anglais
Apple-Installation_de_votre_logiciel_Logic_Studio_Retail
Apple-Pages-Guide-de-l-utilisateur
Apple-MacBook_Pro_13inch_Mid2009.pdf.Anglais
Apple-MacBook_Pro_15inch_Mid2009
Apple-Installation_de_votre_logiciel_Logic_Studio_Upgrade
Apple-airportextreme_802.11n_userguide
Apple-iPod_classic_160GB_User_Guide
Apple-iPod_nano_5th_gen_UserGuide
Apple-ipod_touch_features_guide
Apple-Wireless_Mighty_Mouse_UG
Apple-Advanced-Memory-Management-Programming-Guide
Apple-iOS-App-Programming-Guide
Apple-Concurrency-Programming-Guide
Apple-MainStage-2-User-Manual-Anglais
Apple-iMacG3_2002MultilingualUserGuide
Apple-iBookG3_DualUSBUserGuideMultilingual.PDF.Anglais
Apple-Guide_de_l_utilisateur_de_Mac_Pro_Early_2008
Apple-Installation_de_votre_logiciel_Logic_Express_8
Apple-iMac_Guide_de_l_utilisateur_Mid2007
Apple-imacg5_20inch_OpticalDrive
Apple-FCP6_Formats_de_diffusion_et_formats_HD
Apple-prise_en_charge_des_surfaces_de_controle_logic_pro_8
Apple-Aperture_Quick_Reference_f
Apple-aluminumAppleKeyboard_wireless2007_UserGuide
Apple-ipod_shuffle_features_guide
ApplePowerMacG5_(Early_2005)_UserGuide
Apple-MacBook_Pro_Early_2008_Guide_de_l_utilisateur
Apple-Nouvelles-fonctionnalites-aperture-1.5
Apple-premiers_contacts_2e_ed_10.4.pdf-Mac-OS-X-Server
Apple-premiers_contacts_2e_ed_10.4
Apple-Keynote2_UserGuide.pdf-Japon
Apple-Welcome_to_Tiger.pdf-Japon
Apple-XsanAdminGuide_j.pdf-Japon
Apple-PowerBookG4_UG_15GE.PDF-Japon
Apple-Xsan_Migration.pdf-Japon
Apple-Xserve_Intel_DIY_TopCover_JA.pdf-Japon
Apple-iPod_nano_6thgen_User_Guide_J.pdf-Japon
Apple-Aperture_Photography_Fundamentals.pdf-Japon
Apple-nikeipod_users_guide.pdf-Japon
Apple-QuickTime71_UsersGuide.pdf-Japon
Apple-iMacG5_iSight_UG.pdf-Japon
Apple-Aperture_Performing_Adjustments_j.pdf-Japon
Apple-iMacG5_17inch_HardDrive.pdf-Japon
Apple-iPod_shuffle_Features_Guide_J.pdf-Japon
Apple-MacBook_Air_User_Guide.pdf-Japon
Apple-MacBook_UsersGuide.pdf-Japon
Apple-iPad_iOS4_Brukerhandbok.pdf-Norge-Norvege
Apple-Apple_AirPort_Networks_Early2009_H.pd-Norge-Norvege
Apple-iPod_classic_120GB_no.pdf-Norge-Norvege
Apple-Xserve_Intel_DIY_ExpansionCardRiser_JA.pdf-Japon
Apple-iMacG5_Battery.pdf-Japon
Apple-Logic_Pro_8_Getting_Started.pdf-Japon
Apple-PowerBook-handbok-Norge-Norveg
Apple-iWork09_formler_og_funksjoner.pdf-Norge-Norvege
Apple-MacBook_Pro_15inch_Mid2010_H.pdf-Norge-Norvege
Apple-MacPro_HardDrive_DIY.pdf-Japon
Apple-iPod_Fifth_Gen_Funksjonsoversikt.pdf-Norge-Norvege
Apple-MacBook_13inch_white_Early2009_H.pdf-Norge-Norvege
Apple-GarageBand_09_Komme_i_gang.pdf-Norge-Norvege
Apple-MacBook_Pro_15inch_Mid2009_H.pdf-Norge-Norvege
Apple-imac_mid2011_ug_h.pdf-Norge-Norvege
Apple-iDVD_08_Komme_i_gang.pdf-Norge-Norvege
Apple-MacBook_Air_11inch_Late2010_UG_H.pdf-Norge-Norvege
Apple-iMac_Mid2010_UG_H.pdf-Norge-Norvege
Apple-MacBook_13inch_Mid2009_H.pdf-Norge-Norvege
/Apple-iPhone_3G_Viktig_produktinformasjon_H-Norge-Norvege
Apple-MacBook_13inch_Mid2010_UG_H.pdf-Norge-Norvege
Apple-macbook_air_13inch_mid2011_ug_no.pdf-Norge-Norvege
Apple-Mac_mini_Early2009_UG_H.pdf-Norge-Norvege
Apple-ipad2_brukerhandbok.pdf-Norge-Norvege
Apple-iPhoto_08_Komme_i_gang.pdf-Norge-Norvege
Apple-MacBook_Air_Brukerhandbok_Late2008.pdf-Norge-Norvege
Apple-Pages09_Brukerhandbok.pdf-Norge-Norvege
Apple-MacBook_13inch_Late2009_UG_H.pdf-Norge-Norvege
Apple-iPhone_3GS_Viktig_produktinformasjon.pdf-Norge-Norvege
Apple-MacBook_13inch_Aluminum_Late2008_H.pdf-Norge-Norvege
Apple-Wireless_Keyboard_Aluminum_2007_H-Norge-Norvege
Apple-NiPod_photo_Brukerhandbok_N0190269.pdf-Norge-Norvege
Apple-MacBook_Pro_13inch_Mid2010_H.pdf-Norge-Norvege
Apple-MacBook_Pro_17inch_Mid2010_H.pdf-Norge-Norvege
Apple-Velkommen_til_Snow_Leopard.pdf-Norge-Norvege.htm
Apple-TimeCapsule_Klargjoringsoversikt.pdf-Norge-Norvege
Apple-iPhone_3GS_Hurtigstart.pdf-Norge-Norvege
Apple-Snow_Leopard_Installeringsinstruksjoner.pdf-Norge-Norvege
Apple-iMacG5_iSight_UG.pdf-Norge-Norvege
Apple-iPod_Handbok_S0342141.pdf-Norge-Norvege
Apple-ipad_brukerhandbok.pdf-Norge-Norvege
Apple-GE_Money_Bank_Handlekonto.pdf-Norge-Norvege
Apple-MacBook_Air_11inch_Late2010_UG_H.pdf-Norge-Norvege
Apple-iPod_nano_6thgen_Brukerhandbok.pdf-Norge-Norvege
Apple-iPod_touch_iOS4_Brukerhandbok.pdf-Norge-Norvege
Apple-MacBook_Air_13inch_Late2010_UG_H.pdf-Norge-Norvege
Apple-MacBook_Pro_15inch_Early2011_H.pdf-Norge-Norvege
Apple-Numbers09_Brukerhandbok.pdf-Norge-Norvege
Apple-Welcome_to_Leopard.pdf-Japon
Apple-PowerMacG5_UserGuide.pdf-Norge-Norvege
Apple-iPod_touch_2.1_Brukerhandbok.pdf-Norge-Norvege
Apple-Boot_Camp_Installering-klargjoring.pdf-Norge-Norvege
Apple-MacOSX10.3_Welcome.pdf-Norge-Norvege
Apple-iPod_shuffle_3rdGen_UG_H.pdf-Norge-Norvege
Apple-iPhone_4_Viktig_produktinformasjon.pdf-Norge-Norvege
Apple_TV_Klargjoringsoversikt.pdf-Norge-Norvege
Apple-iMovie_08_Komme_i_gang.pdf-Norge-Norvege
Apple-iPod_classic_160GB_Brukerhandbok.pdf-Norge-Norvege
Apple-Boot_Camp_Installering_10.6.pdf-Norge-Norvege
Apple-Network-Services-Location-Manager-Veiledning-for-nettverksadministratorer-Norge-Norvege
Apple-iOS_Business_Mar12_FR.pdf
Apple-PCIDualAttachedFDDICard.pdf
Apple-Aperture_Installing_Your_Software_f.pdf
Apple-User_Management_Admin_v10.4.pdf
Apple-Compressor-4-ユーザーズマニュアル Japon
Apple-Network_Services_v10.4.pdf
Apple-iPod_2ndGen_USB_Power_Adapter-DE
Apple-AirPort_Express_Opstillingsvejledning_5.1.pdf
Apple-MagSafe_Airline_Adapter.pdf
Apple-L-Apple-Multiple-Scan-20-Display
Apple-Administration_du_service_de_messagerie_10.5.pdf
Apple-iMac_Intel-based_Late2006.pdf-Japon
Apple-iPhone_3GS_Finger_Tips_J.pdf-Japon
Apple-Power-Mac-G4-Mirrored-Drive-Doors-Japon
Apple-atadrive_pmg4mdd.j.pdf-Japon
Apple-iPod_touch_2.2_User_Guide_J.pdf-Japon
Apple-Mac_OS_X_Server_v10.2.pdf
Apple-AppleCare_Protection_Plan_for_Apple_TV.pdf
Apple-DVD_Studio_Pro_4_Installation_de_votre_logiciel
Apple-PowerBookG4_17inch1.67GHzUG
Apple-iMac_Intel-based_Late2006
Apple-Installation_de_votre_logiciel
Apple-guide_des_fonctions_de_l_iPod_nano
Apple-Administration_de_serveur_v10.5
Apple-Mac-OS-X-Server-Premiers-contacts-Pour-la-version-10.3-ou-ulterieure
Apple-iBookG3_14inchUserGuideMultilingual
Apple-mac_pro_server_mid2010_ug_f
Apple-Motion_Supplemental_Documentation
Apple-iphone_guide_de_l_utilisateur
Apple-macbook_air_11inch_mid2011_ug_fr
Apple-NouvellesfonctionnalitesdeLogicExpress7.2
Apple-Mac_Pro_Early2009_4707_UG
Apple-guide_de_l_utilisateur_de_Numbers08
Apple-Guide_de_configuration_et_d'administration
Apple-mac_integration_basics_fr_106.
Apple-iPod_shuffle_4thgen_Guide_de_l_utilisateur
Apple-081811_APP_iPhone_Japanese_v5.4.pdf-Japan
Apple-Recycle_Contract120919.pdf-Japan
Apple-World_Travel_Adapter_Kit_UG
Apple-iPod_nano_6thgen_User_Guide
Apple-Mac_mini_Early2009_UG_F.pdf-Manuel-de-l-utilisateur
Apple-Compressor_3_Batch_Monitor_User_Manual_F.pdf-Manuel-de-l-utilisateur
Apple-Premiers__contacts_avec_iDVD_08
Apple-Mac_mini_Intel_User_Guide.pdf
Apple-Prise_en_charge_des_surfaces_de_controle_Logic_Express_8
Apple-mac_integration_basics_fr_107.pdf
Apple-Final-Cut-Pro-7-Niveau-1-Guide-de-preparation-a-l-examen
Apple-Logic9-examen-prep-fr.pdf-Logic-Pro-9-Niveau-1-Guide-de-preparation-a-l-examen
Apple-aperture_photography_fundamentals.pdf-Manuel-de-l-utilisateu
Apple-emac-memory.pdf-Manuel-de-l-utilisateur
Apple-Apple-Installation-et-configuration-de-votre-Power-Mac-G4
Apple-Guide_de_l_administrateur_d_Xsan_2.pdf
Apple-premiers_contacts_avec_imovie6.pdf
Apple-Tiger_Guide_Installation_et_de_configuration.pdf
Apple-Final-Cut-Pro-7-Level-One-Exam-Preparation-Guide-and-Practice-Exam
Apple-ard_admin_guide_2.2_fr.pdf
Apple-systemoverviewj.pdf-Japon
Apple-Xserve_TO_J070411.pdf-Japon
Apple-premiers_contacts_avec_iwork_08.pdf
Apple-services_de_collaboration_2e_ed_10.4.pdf
Apple-iPhone_Bluetooth_Headset_Benutzerhandbuch.pdf
Apple-Guide_de_l_utilisateur_de_Keynote08.pdf
APPLE/Apple-Logic-Pro-9-Effectsrfr.pdf
Apple-Logic-Pro-9-Effectsrfr.pdf
Apple-iPod_shuffle_3rdGen_UG_F.pdf
Apple-iPod_classic_160Go_Guide_de_l_utilisateur.pdf
Apple-iBookG4GettingStarted.pdf
Apple-Administration_de_technologies_web_10.5.pdf
Apple-Compressor-4-User-Manual-fr
Apple-MainStage-User-Manual-fr.pdf
Apple-PowerBookG4_15inch1.67-1.5GHzUserGuide.pdf
Apple-MacBook_Pro_15inch_Mid2010_CH.pdf
Apple-LED_Cinema_Display_27-inch_UG.pdf
Apple-MacBook_Pro_15inch_Mid2009_RS.pdf
Apple-macbook_pro_13inch_early2011_f.pdf
Apple-iphone_user_guide-For-iOS-6-Software
Apple-iDVD5_Getting_Started.pdf
Apple-guide_des_fonctionnalites_de_l_ipod_touch.pdf
Apple_macbook_pro_13inch_early2011_f
Apple_Guide_de_l_utilisateur_d_Utilitaire_RAID
Apple_Time_Capsule_Early2009_Setup_F
Apple_iphone_4s_finger_tips_guide_rs
apple_iphone_gebruikershandleiding
apple_apple_tv_3rd_gen_setup_tw
apple_macbook_pro-retina-mid-2012-important_product_info_ch
apple_Macintosh-User-s-Guide-for-Macintosh-PowerBook-145
Apple_ipod_touch_user_guide_ta
Apple_TV_2nd_gen_Setup_Guide_h
Apple_ipod_touch_manual_del_usuario
Apple_iphone_4s_finger_tips_guide_tu
Apple_macbook_pro_retina_qs_th
Apple-Manuel_de_l'utilisateur_de_Final_Cut_Server
Apple-Cinema_Tools_4.0_User_Manual_F
Apple-Personal-LaserWriter300-User-s-Guide
Apple-QuickTake-100-User-s-Guide-for-Macintosh
Apple-User-s-Guide-Macintosh-LC-630-DOS-Compatible
Apple-iPhone_iOS3.1_User_Guide
Apple-iphone_4s_important_product_information_guide
Apple-iPod_shuffle_Features_Guide_F
Apple-Premiers_contacts_avec_iMovie_08
Apple-macbook_pro-retina-mid-2012-important_product_info_br
Apple-macbook_pro-13-inch-mid-2012-important_product_info
Apple-macbook_air-11-inch_mid-2012-qs_br
Apple-Manuel_de_l_utilisateur_de_MainStage
Apple-Compressor_3_User_Manual_F
Apple-guide_de_configuration_airport_express_4.2
Apple-Instruments_et_effets_Logic_Express_8
Apple-Manuel_de_l_utilisateur_de_WaveBurner
Apple-Macmini_Guide_de_l'utilisateur
Disque dur, ATA parallèle Instructions de remplacement
Apple-final_cut_pro_x_logic_effects_ref_f
Apple-Leopard_Installationshandbok
Apple-thunderbolt_display_getting_started_1e
Apple-Compressor-4-Benutzerhandbuch
Apple-macbook_air_11inch_mid2011_ug
Apple-macbook_air-mid-2012-important_product_info_j
Apple-iPod-nano-Guide-des-fonctionnalites
Apple-iPod-nano-Guide-des-fonctionnalites
Apple-iPod-nano-Guide-de-l-utilisateur-4eme-generation
Apple-iPod-nano-Guide-de-l-utilisateur-4eme-generation
Apple-Manuel_de_l_utilisateur_d_Utilitaire_de_reponse_d_impulsion
Apple-Aperture_2_Raccourcis_clavier
Apple-livetype_2_user_manual_f
Apple-macbook_air_guide_de_l_utilisateur
Apple-MacBook_Early_2008_Guide_de_l_utilisateur
Apple-Keynote-2-Guide-de-l-utilisateur
Apple-PowerBook-User-s-Guide-for-PowerBook-computers
Apple-Macintosh-Performa-User-s-Guide-5200CD-and-5300CD
Apple-Macintosh-Performa-User-s-Guide
Apple-iPod-nano-Guide-des-fonctionnalites
Apple-iPad-User-Guide-For-iOS-5-1-Software
Apple-Boot-Camp-Guide-d-installation-et-de-configuration
Apple-iPod-nano-Guide-de-l-utilisateur-4eme-generation
Power Mac G5 Guide de l’utilisateur APPLE
Guide de l'utilisateur PAGE '08 APPLE
Guide de l'utilisateur KEYNOTE '09 APPLE
Guide de l'Utilisateur KEYNOTE '3 APPLE
Guide de l'Utilisateur UTILITAIRE RAID
Guide de l'Utilisateur Logic Studio
Power Mac G5 Guide de l’utilisateur APPLE
Guide de l'utilisateur PAGE '08 APPLE
Guide de l'utilisateur KEYNOTE '09 APPLE
Guide de l'Utilisateur KEYNOTE '3 APPLE
Guide de l'Utilisateur UTILITAIRE RAID
Guide de l'Utilisateur Logic Studio
Guide de l’utilisateur ipad Pour le logiciel iOS 5.1
PowerBook G4 Premiers Contacts APPLE
Guide de l'Utilisateur iphone pour le logiciel ios 5.1 APPLE
Guide de l’utilisateur ipad Pour le logiciel iOS 4,3
Guide de l’utilisateur iPod nano 5ème génération
Guide de l'utilisateur iPod Touch 2.2 APPLE
Guide de l’utilisateur QuickTime 7 Mac OS X 10.3.9 et ultérieur Windows XP et Windows 2000
Guide de l'utilisateur MacBook 13 pouces Mi 2010
Guide de l’utilisateur iPhone (Pour les logiciels iOS 4.2 et 4.3)
Guide-de-l-utilisateur-iPod-touch-pour-le-logiciel-ios-4-3-APPLE
Guide-de-l-utilisateur-iPad-2-pour-le-logiciel-ios-4-3-APPLE
Guide de déploiement en entreprise iPhone OS
Guide-de-l-administrateur-Apple-Remote-Desktop-3-1
Guide-de-l-utilisateur-Apple-Xserve-Diagnostics-Version-3X103
Guide-de-configuration-AirPort-Extreme-802.11n-5e-Generation
Guide-de-configuration-AirPort-Extreme-802-11n-5e-Generation
Guide-de-l-utilisateur-Capteur-Nike-iPod
Guide-de-l-utilisateur-iMac-21-5-pouces-et-27-pouces-mi-2011-APPLE
Guide-de-l-utilisateur-Apple-Qadministrator-4
Guide-d-installation-Apple-TV-3-eme-generation
User-Guide-iPad-For-ios-5-1-Software
Shark User Guide
(Legacy)Contents
Introduction 12
Overview 12
Philosophy 12
Organization of This Document 13
Getting Started with Shark 16
Main Window 16
Mini Configuration Editors 18
Perform Sampling 18
Session Windows and Files 19
Session Files 20
Session Information Sheet 21
Session Report 22
Advanced Settings Drawer 22
Shark Preferences 23
Time Profiling 28
Statistical Sampling 28
Taking a Time Profile 30
Profile Browser 31
Heavy View 35
Tree View 35
Profile Display Preferences 37
Chart View 39
Advanced Chart View Settings 42
Code Browser 45
Assembly Browser 48
Advanced Code Browser Settings 50
ISA Reference Window 54
Tips and Tricks 56
Example: Optimizing MPEG-2 using Time Profiles 58
Base 58
Vectorization 60
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
2System Tracing 63
Tracing Methodology 63
Basic Usage 64
Interpreting Sessions 66
Summary View In-depth 67
Trace View In-depth 73
Timeline View In-depth 77
Sign Posts 90
Tips and Tricks 93
Other Profiling and Tracing Techniques 97
Time Profile (All Thread States) 97
Malloc Trace 101
Using a Malloc Trace 102
Advanced Display Options 105
Static Analysis 107
Using Shark with Java Programs 108
Java Tracing Techniques 109
Linking Shark with the Java Virtual Machine 110
Event Counting and Profiling Overview 111
Timed Counters: The Performance Counter Spreadsheet 111
Event-Driven Counters: Correlating Events with Your Code 119
Advanced Profiling Control 122
Process Attach 122
Process Launch 122
Batch Mode 125
Windowed Time Facility (WTF) 125
WTF with System Trace 127
Unresponsive Application Measurements 128
Command Line Shark 129
Basic Methodology 130
Common Options 131
Target Selection 132
Reports 133
Custom Configurations 133
More Information 134
Interprocess Remote Control 134
Programmatic Control 134
Command Line Remote Control 137
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
3
ContentsNetwork/iPhone Profiling 138
Using Shared Profiling Mode 141
Mac OS X Firewall Considerations 143
Advanced Session Management and Data Mining 145
Automatic Symbolication Troubleshooting 145
Symbol Lookup 145
Debugging Information 146
Manual Session Symbolication 146
Managing Sessions 150
Comparing Sessions 150
Merging Sessions 151
Data Mining 151
Callstack Data Mining 152
Perf Count Data Mining 157
Example: Using Data Mining with a Time Profile 158
A Performance Problem... 158
Taking Samples 160
High Level Analysis 162
Analysis Via Source Navigation 163
Introduction To Focusing 168
Dig Deeper by Charging Costs 173
Example: Graphical Analysis using Chart View with a Malloc Trace 176
Taking Samples 176
Graphical Analysis of a Malloc Trace 179
Custom Configurations 183
The Config Editor 184
Simple Timed Samples and Counters Config Editor 186
Malloc Data Source PlugIn Editor 189
Static Analysis Data Source PlugIn Editor 190
Java Trace Data Source PlugIn Editor 191
Sampler Data Source PlugIn Editor 192
System Trace Data Source PlugIn Editor 193
All Thread States Data Source PlugIn Editor 194
Analysis and Viewer PlugIn Summary 195
Counter Spreadsheet Analysis PlugIn Editor 196
Using the Editor 196
Spreadsheet Configuration Example 199
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
4
ContentsHardware Counter Configuration 202
Configuring the Sampling Technique: The Sampling Tab 202
Common Elements in Performance Counter Configuration Tabs 206
Counter Control 206
Privilege Level Filtering 207
Process Marking 207
MacOS X OS-Level Counters Configuration 208
Intel CPU Performance Counter Configuration 209
PowerPC G3/G4/G4+ CPU Performance Counter Configuration 211
PowerPC G5 (970) Performance Counter Configuration 213
PowerPC North Bridge Counter Configuration 221
U1.5/U2 North Bridges 222
U3 North Bridge 223
U4 (Kodiak) North Bridge 226
ARM11 CPU Performance Counter Configuration 229
Command Reference 230
Menu Reference 230
Shark 230
File 230
Edit 231
Format 233
Config 233
Sampling 234
Data Mining 235
Window 235
Help 236
Alphabetical Reference 236
Miscellaneous Topics 242
Code Analysis with the G5 (PPC970) Model 242
Supervisor Space Sampling Guidelines 243
Intel Core Performance Counter Event List 246
Intel Core 2 Performance Counter Event List 252
PPC 750 (G3) Performance Counter Event List 263
PPC 7400 (G4) Performance Counter Event List 265
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
5
ContentsPPC 7450 (G4+) Performance Counter Event List 271
PPC 970 (G5) Performance Counter Event List 282
UniNorth-2 (U1.5/2) Performance Counter Event List 315
UniNorth-3 (U3) Performance Counter Event List 318
Kodiak (U4) Performance Counter Event List 322
ARM11 Performance Counter Event List 326
Document Revision History 328
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
6
ContentsFigures, Tables, and Listings
Getting Started with Shark 16
Figure 1-1 Main Window 16
Figure 1-2 Process Target 17
Figure 1-3 Mini Configuration Editor 18
Figure 1-4 Session Inspector Panel 21
Figure 1-5 Sample Window with Advanced Settings Drawer visible at right 23
Figure 1-6 Shark Preferences — Appearance 24
Figure 1-7 Shark Preferences — Sampling 25
Figure 1-8 Shark Preferences — Sessions 26
Figure 1-9 Shark Preferences — Search Paths 27
Time Profiling 28
Figure 2-1 Execution Before Sampling 29
Figure 2-2 Sampling Results 29
Figure 2-3 Time Profile mini-configuration editor 31
Figure 2-4 The Profile Browser 32
Figure 2-5 Tuning Advice 33
Figure 2-6 Callstack Table 34
Figure 2-7 Heavy Profile View Detail 35
Figure 2-8 Tree Profile View 36
Figure 2-9 Profile Analysis Preferences 37
Figure 2-10 Chart View 40
Figure 2-11 Advanced Settings for the Chart View 44
Figure 2-12 Code Browser 45
Figure 2-13 Hot Spot Scrollbar 47
Figure 2-14 Assembly Browser 50
Figure 2-15 Advanced Settings for the Code Browser 53
Figure 2-16 x86 Asm Browser Advanced Settings 54
Figure 2-17 ARM Asm Browser Advanced Settings 54
Figure 2-18 ISA Reference Window 55
Figure 2-19 Original Time Profile, with Tuning Advice 59
Figure 2-20 Code Browser with Vectorization Hint 61
Figure 2-21 Time Profile after Vectorizing IDCT 61
Table 2-1 MPEG-2 Performance Improvement 61
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
7System Tracing 63
Figure 3-1 Time Profile vs. System Trace Comparison 64
Figure 3-2 System Trace Mini Config Editor 65
Figure 3-3 Summary View 67
Figure 3-4 Summary View: Scheduler 68
Figure 3-5 Summary View: System Calls 69
Figure 3-6 Summary View: VM Faults 71
Figure 3-7 Summary View Advanced Settings Drawer 72
Figure 3-8 Trace View: Scheduler 74
Figure 3-9 Trace View: System Calls 75
Figure 3-10 Trace View: VM Faults 77
Figure 3-11 Timeline View 78
Figure 3-12 Timeline View: Thread Run Intervals 79
Figure 3-13 Thread Run Interval Inspector 79
Figure 3-14 Timeline View: System Calls 81
Figure 3-15 System Call Inspector 82
Figure 3-16 Timeline View: VM Faults 83
Figure 3-17 VM Fault Inspector 84
Figure 3-18 Interrupt Inspector 85
Figure 3-19 Sign Post Inspector 86
Figure 3-20 Timeline View Advanced Settings Drawer 89
Listing 3-1 ~/Library/Application Support/Shark/KDebugCodes/myFirstSignPosts 90
Listing 3-2 signPostExample.c 92
Listing 3-3 testKernelSignPost.c 92
Other Profiling and Tracing Techniques 97
Figure 4-1 Time Profile (All Thread States) mini configuration editor 98
Figure 4-2 Time Profile (All Thread States) session, heavy view 99
Figure 4-3 Time Profile (All Thread States) session, tree view 100
Figure 4-4 Malloc Trace mini configuration editor 102
Figure 4-5 Malloc Trace session, profile browser 103
Figure 4-6 Malloc Trace session, chart view 104
Figure 4-7 Enabling Malloc Trace Advanced Options 105
Figure 4-8 Additional Malloc Trace Charts 106
Figure 4-9 Static Analysis mini configuration editor 108
Figure 4-10 How Shark-for-Java differs from regular Shark configurations 109
Figure 4-11 Performance Counter Spreadsheet 114
Figure 4-12 Counters Menu 115
Figure 4-13 Performance Counter Spreadsheet: Advanced Settings 116
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
8
Figures, Tables, and ListingsFigure 4-14 Chart View with additional timed counter graphs 121
Advanced Profiling Control 122
Figure 5-1 Process Attach 122
Figure 5-2 Launch Process Panel 123
Figure 5-3 Batch Mode 125
Figure 5-4 Normal Profiling Workflow 126
Figure 5-5 Windowed Time Facility Workflow 126
Figure 5-6 The Windowed Time Facility Timeline 128
Figure 5-7 Unresponsive Application Triggering 129
Figure 5-8 Samples Taken for Towers of Hanoi N=10..20 137
Figure 5-9 Network/iPhone Manager 139
Figure 5-10 Command Line Shark in Network Profiling Mode 142
Figure 5-11 Sharing Firewall Warning Dialog 143
Figure 5-12 Firewall Sharing Preferences, while adding a new port range for Shark 144
Listing 5-1 Towers of Hanoi Source Code 135
Listing 5-2 Instrumented Towers of Hanoi 135
Advanced Session Management and Data Mining 145
Figure 6-1 Session Inspector: Symbols 147
Figure 6-2 Symbolication Dialog 148
Figure 6-3 Before Symbolication 149
Figure 6-4 After Symbolication 150
Figure 6-5 Example Callstacks 153
Figure 6-6 Heavy View 153
Figure 6-7 Tree View 154
Figure 6-8 Data Mining Advanced Settings 155
Figure 6-9 Contextual Data Mining Menu 157
Figure 6-10 Perf Count Data Mining Palette 158
Figure 6-11 Example Shapes 159
Figure 6-12 Example Shapes, Replicated 160
Figure 6-13 Sampling a Specific Process 161
Figure 6-14 Default Profile View 161
Figure 6-15 Navigation Via the Call-Stack Pane 163
Figure 6-16 Navigation Via the Call-Stack Pane with Tree View 163
Figure 6-17 Source View: SKTGraphicView selectAll 164
Figure 6-18 Source View: NSObject 165
Figure 6-19 Source View: SKTGraphicView selectGraphic 166
Figure 6-20 Source View: SKTGraphicView invalidateGraphic 167
Figure 6-21 Tree view before focusing 168
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
9
Figures, Tables, and ListingsFigure 6-22 Data Mining Contextual Menu 168
Figure 6-23 After Focus Symbol -[SKTGraphicView drawRect:] 169
Figure 6-24 After focus and expansion 170
Figure 6-25 Source View: SKTGraphic drawInView:isSelected: 171
Figure 6-26 Source View: SKGraphic drawHandlesInView: 172
Figure 6-27 Source View: SKGraphic drawHandleAtPoint:inView: 173
Figure 6-28 Heavy View of Focused Sketch 174
Figure 6-29 Expanded Heavy View of Focused Sketch 174
Figure 6-30 After Charge Library libRIP.A.dylib 175
Figure 6-31 After Flatten Library 175
Figure 6-32 Malloc Trace Main Window 177
Figure 6-33 Result of Malloc Sampling 178
Figure 6-34 Chart View 179
Figure 6-35 Place to Select 180
Figure 6-36 Graph View with Call-Stack Pane 182
Custom Configurations 183
Figure 7-1 Main Configuration Menu 183
Figure 7-2 Config Editor 186
Figure 7-3 Simple Timed Samples and Counters Data Source - Sampling Tab 187
Figure 7-4 Simple Timed Samples and Counters Data Source - Counter Settings 188
Figure 7-5 Malloc Data Source - Sampling Settings 189
Figure 7-6 Static Analysis Data Source - Settings 190
Figure 7-7 Java Trace Data Source - Sampling Settings 191
Figure 7-8 Sampler Data Source - Settings 192
Figure 7-9 System Trace Data Source - Settings 193
Figure 7-10 All Thread States Data Source - Settings 194
Figure 7-11 Counter Spreadsheet Analysis 196
Figure 7-12 Choosing a counter-based starting configuration 199
Figure 7-13 Enabling two performance counters 200
Figure 7-14 Performance Spreadsheet: Shortcut Equation 201
Hardware Counter Configuration 202
Figure 8-1 Timed Samples & Counters Data Source - Advanced Sampling Tab 203
Figure 8-2 A typical set of performance counter controls 206
Figure 8-3 Process Marker 208
Figure 8-4 MacOS X Performance Counters Configuration 209
Figure 8-5 Intel Core 2 Configuration Tab 211
Figure 8-6 PowerPC G4+ Configuration Tab (G3 and G4 are similar) 213
Figure 8-7 PowerPC 970 Processor Performance Counters Configuration 215
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
10
Figures, Tables, and ListingsFigure 8-8 PowerPC 970 IMC (IFU) Configuration Tab 217
Figure 8-9 PowerPC 970 IMC (IDU) Configuration Tab 221
Figure 8-10 U1.5/U2 Configuration Tab 223
Figure 8-11 U3 Memory Configuration Tab 225
Figure 8-12 U3 API Configuration Tab 226
Figure 8-13 U4 (Kodiak) Memory Configuration Tab 227
Figure 8-14 U4 (Kodiak) API Configuration Tab 228
Figure 8-15 ARM11 Counter Configuration Tab 229
Miscellaneous Topics 242
Figure B-1 PPC970 Resource Modeling 243
Figure B-2 Timer Sampling in the Kernel 244
Figure B-3 CPU PMI Sampling in the Kernel 245
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
11
Figures, Tables, and ListingsImportant: This document may not represent best practices for current development. Links to downloads
and other resources may no longer be valid.
Overview
Shark is a tool for performance understanding and optimization. Why is it called “Shark?” Performance tuning
requires a hunter’s mentality, and no animal is as pure in this quest as a shark. A shark is also an expert in his
field — one who uses all potential resources to achieve his goals. The name “Shark” embodies the spirit and
emotion you should have when tuning your code.
To help you analyze the performance of your code, Shark allows you to profile the entire system (kernel and
drivers as well as applications). At the simplest level, Shark profiles the system while your code is running to
see where time is being spent. It can also produce profiles of hardware and software performance events such
as cache misses, virtual memory activity, memory allocations, function calls, or instruction dependency stalls.
This information is an invaluable first step in your performance tuning effort so you can see which parts of
your code or the system are the bottlenecks.
In addition to showing you where time is being spent, Shark can give you advice on how to improve your
code. Shark is capable of identifying many common performance pitfalls and visually presents the costs of
these problems to you.
Philosophy
The first and most important step when optimizing your code is to determine what to optimize. In a program
of moderate complexity, there can be thousands of different code paths. Optimizing all of them is normally
impractical due to deadlines and limited programmer resources. There are also more subtle tradeoffs between
optimized code and portability and maintenance that limit candidates for optimization.
Here are a few general guidelines for finding a good candidate for optimization:
1. It should be time-critical. This is generally any operation that is perceptibly slow; the user has to wait for
the computer to finish doing something before continuing. Optimizing functionality that is already faster
than the user can perceive is usually unnecessary.
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
12
Introduction2. It must be relevant. Optimizing functionality that is rarely used is usually counter-productive.
3. It shows up as a hot spot in a time profile. If there is no obvious hot spot in your code or you are spending
a lot of time in system libraries, performance is more likely to improve through high-level improvements
(architectural changes).
Low-level optimizationstypically focus on a single segment of code and make it a better match to the hardware
and software systemsit is being run on. Examples of low-level optimizationsinclude using vector or cache hint
instructions. High-level optimizations include algorithmic or other architectural changes to your program.
Examples of high-level optimizations include data structure choice (for example, switching from a linked list
to a hash-table) or replacing calls to computationally expensive functions with a cache or lookup table.
Remember, it is critical to profile before investing your time and effort in optimization. Sadly, many programmers
invest prodigious amounts of effort optimizing what their intuition tellsthem isthe performance-criticalsection
of code only to realize no performance improvement. Profiling quickly reveals that bottlenecks often lie far
from where programmers might assume they are. Using Shark, you can focus your optimization efforts on both
algorithmic changes and tuning performance-critical code. Often, even small changesto a critical piece of code
can yield large overall performance improvements.
By default, Shark creates a profile of execution behavior by periodically interrupting each processor in the
system and sampling the currently running process, thread, and instruction address as well as the function
callstack. Along with this contextual information, Shark can record the values of hardware and software
performance counters. Each counter is capable of counting a wide variety of performance events. In the case
of processor and memory controller counters, these include detailed, low-level information that is otherwise
impossible to know without a simulator. The overhead for sampling with Shark is extremely low because all
sample collection takes place in the kernel and is based on hardware interrupts. A typical sample incurs an
overhead on the order of 20µs. This overhead can be significantly larger if callstack recording is enabled and
a virtual memory fault is incurred while saving the callstack. Time profiles generated by Shark are statistical in
nature; they give a representative view of what wasrunning on the system during a sampling session . Samples
can include all of the processes running on the system from both user and supervisor code, or samples can be
limited to a specific process or execution state. Shark’s sampling period can be an arbitrary time interval (timer
sampling). Shark also has the ability to use a performance event as the sampling trigger (event sampling).
Using event sampling, it is possible to associate performance events such as cache misses or instruction stalls
with the code that caused them. Additionally, Shark can generate exact profiles for specific function calls or
memory allocations.
Organization of This Document
This manual is organized into four major sections, each consisting of two or three chapters, plus several
appendices. Here is a brief “roadmap” to help you orient yourself:
Introduction
Organization of This Document
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
13● Getting Started with Shark— This introduction and “Getting Started with Shark” (page 16) are designed
to give you an overall introduction to Shark. After covering some basic philosophy here, “Getting Started
with Shark” (page 16) describes basic ways to use Shark to sample your applications, features of the
Session windows that open after you sample your applications, and the use of Shark’s global preferences.
● Profiling Configurations— Three chapters discuss Shark’s default Configurations — its methods of
collecting samples from your system or applications — and presentation of the sampled results in Session
windows. These chapters are probably the most important ones. “Time Profiling” (page 28) discusses Time
Profiling , the most frequently used configuration, which gives a statistical profile of processor utilization.
System Tracing , discussed in “System Tracing” (page 63), provides an exact trace of user-kernel transitions,
and is useful both to debug interactions between your program and the underlying system and to provide
a “microscope” to examine multithreaded programming issues in detail. After the complete chapters
devoted to these two configurations, the remainder are covered in “Other Profiling and Tracing
Techniques” (page 97). Time Profile (All Thread States) is a variant of Time Profile that also samples blocked
threads, and as a result is a good way to get an overview of locking behavior in multithreaded applications.
Malloc Trace allows you to examine memory allocation and deallocation activity in detail. Shark can apply
Static Analysis to your application in order to quickly examine rarely-traversed code paths. Equivalents
for Time Profile , Malloc Trace , and an exact Call Trace , all customized for use with Java applications, are
also available. Finally, the chapter gives an overview of Shark’s extensive performance counter recording
and analysis capabilities.
● Advanced Techniques—Shark’s basic techniquesforsampling and analysis are sufficient for most purposes,
but with complex applications you may need more sophisticated techniques. “Advanced Profiling
Control” (page 122) covers waysto start and stop Shark’ssampling very precisely, allowing you to carefully
control what issampled, in advance. You can also learn how to control Shark remotely from other machines
or even to control Shark running on iOS devices attached to your machine in this chapter. “Advanced
Session Management and Data Mining” (page 145) looks at Shark’s symbol management and data mining
techniques, which are ways to very precisely select subsets of your samples for examination after they are
taken.
● Custom Configurations— Shark is not just limited to its default configurations. If you want to save your
own custom settings for a configuration or create a new one from scratch, then you will want to check
out chapters “Custom Configurations” (page 183) and “Hardware Counter Configuration” (page 202). The
first describes how you may make adjustments to the existing configurations, while the latter covers the
many options relating to the use of hardware performance counters. Because there are so many different
possible combinations of performance counters, only a limited number of the possibilities are covered by
the default configurations. Hence, thisislikely to be the main area where the use of custom configurations
will be necessary for typical Shark users.
● Appendices— The first appendix, “Command Reference” (page 230), provides a brief reference to Shark’s
menu commands. The second, “Miscellaneous Topics” (page 242), describes several minor, miscellaneous
options that do not really fit in anywhere else or are of interest only to a small minority of Shark users. The
Introduction
Organization of This Document
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
14remainder of the appendices (“Intel Core Performance Counter Event List” (page 246), “Intel Core 2
Performance Counter Event List” (page 252), “PPC 750 (G3) Performance Counter Event List” (page 263),
“PPC 7400 (G4) Performance Counter Event List” (page 265), “PPC 7450 (G4+) Performance Counter Event
List” (page 271),“PPC 970 (G5) Performance Counter Event List” (page 282),“UniNorth-2 (U1.5/2) Performance
Counter Event List” (page 315), “UniNorth-3 (U3) Performance Counter Event List” (page 318), and “Kodiak
(U4) Performance Counter Event List” (page 322)) provide a reference for the performance counters that
you can measure with Shark.
Introduction
Organization of This Document
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
15Starting to use Shark is a relatively simple process. You only need to choose one or two items from menus and
press a big “Start” button in order to start sampling your applications. This chapter describes these basic steps
and a few other general Shark features, such as its preferences.
Main Window
Figure 1-1 Main Window
After launching Shark, you will be presented with Shark’s main window, as illustrated in Figure 1-1. The default
sampling configuration istimer-based sampling (Time Profile ) of everything running on the system. By default,
the Time Profile configuration uses a 1 ms timer as the trigger for sampling and will record for 30 seconds
(30,000 samples per processor). Opening the Sampling Configuration menu (#1) allows you to select from
various built-in profiling configurations. Here is a list:
● Time Profile— This configuration, the default, performs timer-based sampling, interrupting your system
after a regular interval and taking a sample of what is executing. It is a great starting point, as it allows
you to very quickly see what code in your application is actually executing most frequently. Knowing this
isthe firststep to successfully optimizing CPU-bound applications. See “Time Profiling” (page 28) for more
information.
● System Trace—This configuration records an exact trace of callsinto the Mac OS X kernel by your program,
and which threads are running. It is useful for examining your program’s interactions with Mac OS X and
for visualizing how your threads are interacting in multithreaded programs. System Trace is discussed in
depth in “System Tracing” (page 63).
● Time Profile (All Thread States)— This variation on time profiling also records the state of all blocked,
inactive threads. As a result, it’s a great way to see how much and why your threads are blocked. This is
quite helpful in the development of multithreaded programs that do a lot of synchronization. This
configuration is described in “Time Profile (All Thread States)” (page 97).
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
16
Getting Started with Shark● Malloc Trace— If your program allocates and deallocates a lot of memory, performance can suffer and
the odds of accidental memory leaks increase. Shark can help you find and analyze these allocations.
“Malloc Trace” (page 101) talks about this more.
● Static Analysis— Shark can provide some basic optimization hints without actually running code. See
“Static Analysis” (page 107) for more information.
●
Java Profiling— Because Java programs run within the Java Virtual Machine (JVM), normally sampling
them with Shark produces little useful information. However, Shark also includes several configurations
that simulate the normal Time Profile , Malloc Trace , and even an exact trace of method calls, but while
collecting information about what the JVM is executing instead of the native machine. A full description
of these options and how to attach Shark to your Java programs is given in “Using Shark with Java
Programs” (page 108).
● Hardware Measurements— The L2 cache miss and Processor Bandwidth (x86 systems) or Memory
Bandwidth (PowerPC systems) configurations measure memory system activity using counters built into
the hardware. They are a great way to see how your program is being slowed because of poor cache
memory use. See “Event Counting and Profiling Overview” (page 111) for an overview of Shark’s counter
measurement capabilities.
These built-in configurations are adequate for sampling most applications. After you have used Shark for
awhile, however, you may decide that you would like to sample something in your application that is not
covered by the built-in collection of options. In particular, you may want to perform hardware measurements
using countersthat are not used by the default hardware measurement configurations. The processfor building
your own configurations is described in “Custom Configurations” (page 183). This process is complex enough
that you should probably familiarize yourself with Shark before attempting the creation of configurations.
By default, Shark samples your entire system, as indicated by the “Everything” item selected for you in the
Target pop-up menu (#2). Popping open this menu allows you to select a specific process or file (Figure 1-2).
You may also choose different targets using the keyboard: Command-1 for everything, Command-2 for an
executing process, and Command-3 for a file. For a Time Profile , it is unnecessary to select a specific target,
but others like Malloc Trace and Static Analysis require you to target a specific process or file. If you select the
“Process” target, you can also choose to launch a new process. See “Process Attach” (page 122) and “Process
Launch” (page 122) for full instructions on the process attaching and launching target selection techniques.
Figure 1-2 Process Target
Getting Started with Shark
Main Window
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
17Mini Configuration Editors
Each configuration typically has a few parameters that are frequently modified. Shark allows you to edit these
easily using themini configuration editors associated with each configuration. You can enablemini configuration
editors by selecting the Config ShowMini Config Editor menu item(Command-Shift-C). Mostmini configuration
editors are similar to the one depicted in “Shark Preferences,” but all have small configuration-specific variations.
The selection of controls available in each min configuration editor are described in the chapters associated
with each type of configuration.
Figure 1-3 Mini Configuration Editor
Perform Sampling
After you choose what you would like to sample (or trace, with some configurations) and how, then actually
using Shark to sample your program is extremely simple. There are two main ways to start sampling:
1. Click the Start button (#3 in “Main Window”).
2. Press the current “Hot Key” (Option-Esc , by default).
Shark will emit a brief tone and the Shark icon in the dock will turn bright red to let you know that Shark is
now actively sampling. At this point, you should exercise your program appropriately to trigger the execution
of code that you want to measure. Sometimes this may require no active input on your part, but if you are
measuring something like user interface performance then you may need to manually perform several steps
while Shark samples.
Getting Started with Shark
Perform Sampling
Retired Document | 2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
18
Drawing and Printing
Guide for iOSContents
About Drawing and Printing in iOS 7
At a Glance 7
Custom UI Views Allow Greater Drawing Flexibility 8
Apps Can Draw Into Offscreen Bitmaps or PDFs 10
Apps Have a Range of Options for Printing Content 10
It’s Easy to Update Your App for High-Resolution Screens 11
See Also 11
iOS Drawing Concepts 12
The UIKit Graphics System 12
The View Drawing Cycle 13
Coordinate Systems and Drawing in iOS 13
Points Versus Pixels 16
Obtaining Graphics Contexts 18
Color and Color Spaces 20
Drawing with Quartz and UIKit 20
Configuring the Graphics Context 21
Creating and Drawing Paths 23
Creating Patterns, Gradients, and Shadings 24
Customizing the Coordinate Space 24
Applying Core Animation Effects 27
About Layers 27
About Animations 28
Accounting for Scale Factors in Core Animation Layers 28
Drawing Shapes Using Bézier Paths 30
Bézier Path Basics 30
Adding Lines and Polygons to Your Path 31
Adding Arcs to Your Path 32
Adding Curves to Your Path 34
Creating Oval and Rectangular Paths 35
Modifying the Path Using Core Graphics Functions 35
Rendering the Contents of a Bézier Path Object 36
Doing Hit-Detection on a Path 38
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
2Drawing and Creating Images 40
Drawing Images 40
Creating New Images Using Bitmap Graphics Contexts 41
Generating PDF Content 45
Creating and Configuring the PDF Context 45
Drawing PDF Pages 48
Creating Links Within Your PDF Content 50
Printing 52
Printing in iOS is Designed to be Simple and Intuitive 52
The Printing User Interface 52
How Printing Works in iOS 56
The UIKit Printing API 57
Printing Support Overview 58
Printing Workflow 59
Printing Printer-Ready Content 61
Using Print Formatters and Page Renderers 63
Setting the Layout Properties for the Print Job 63
Using a Print Formatter 65
Using a Page Renderer 69
Testing the Printing of App Content 73
Common Printing Tasks 73
Testing for Printing Availability 73
Specifying Print-Job Information 74
Specifying Paper Size, Orientation, and Duplexing Options 75
Integrating Printing Into Your User Interface 76
Responding to Print-Job Completion and Errors 79
Improving Drawing Performance 80
Supporting High-Resolution Screens In Views 82
Checklist for Supporting High-Resolution Screens 82
Drawing Improvements That You Get for Free 82
Updating Your Image Resource Files 83
Loading Images into Your App 83
Using an Image View to Display Multiple Images 84
Updating Your App’s Icons and Launch Images 85
Drawing High-Resolution Content Using OpenGL ES or GLKit 85
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
3
ContentsLoading Images 88
System Support for Images 89
UIKit Image Classes and Functions 89
Other Image-Related Frameworks 90
Supported Image Formats 90
Maintaining Image Quality 91
Document Revision History 92
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
4
ContentsFigures, Tables, and Listings
About Drawing and Printing in iOS 7
Figure I-1 You can combine custom views with standard views, and even draw things offscreen. 7
iOS Drawing Concepts 12
Figure 1-1 The relationship between drawing coordinates, view coordinates, and hardware coordinates
14
Figure 1-2 Default coordinate systems in iOS 15
Figure 1-3 A one-point line centered at a whole-numbered point value 17
Figure 1-4 Appearance of one-point-wide lines on standard and retina displays 18
Figure 1-5 Arc rendering in Core Graphics versus UIKit 26
Table 1-1 Core graphics functions for modifying graphics state 21
Drawing Shapes Using Bézier Paths 30
Figure 2-1 Shape drawn with methods of the UIBezierPath class 32
Figure 2-2 An arc in the default coordinate system 33
Figure 2-3 Curve segments in a path 34
Listing 2-1 Creating a pentagon shape 31
Listing 2-2 Creating a new arc path 33
Listing 2-3 Assigning a new CGPathRef to a UIBezierPath object 35
Listing 2-4 Mixing Core Graphics and UIBezierPath calls 36
Listing 2-5 Drawing a path in a view 37
Listing 2-6 Testing points against a path object 38
Drawing and Creating Images 40
Listing 3-1 Drawing a scaled-down image to a bitmap context and obtaining the resulting image 42
Listing 3-2 Drawing to a bitmap context using Core Graphics functions 43
Generating PDF Content 45
Figure 4-1 Creating a link destination and jump point 51
Listing 4-1 Creating a new PDF file 46
Listing 4-2 Drawing page-based content 48
Printing 52
Figure 5-1 System item action button—used for printing 53
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
5Figure 5-2 Printer-options popover view (iPad) 53
Figure 5-3 Printer-options sheet (iPhone) 54
Figure 5-4 Print Center 55
Figure 5-5 Print Center: detail of print job 56
Figure 5-6 Printing architecture 57
Figure 5-7 Relationships of UIKit printing objects 57
Figure 5-8 The layout of a multi-page print job 65
Table 5-1 Deciding how to print app content 58
Listing 5-1 Printing a single PDF document with capability for page-range selection 62
Listing 5-2 Printing an HTML document (without header information) 66
Listing 5-3 Printing the contents of a web view 68
Listing 5-4 Drawing the header and footer of a page 71
Listing 5-5 Enabling or disabling a print button based on availability of printing 74
Listing 5-6 Setting properties of a UIPrintInfo object and assigning it to the printInfo property 74
Listing 5-7 Setting the printing orientation to match image dimension 75
Listing 5-8 Implementing the printInteractionController:choosePaper: method 76
Listing 5-9 Presenting printing options based upon current device type 77
Listing 5-10 Implementing a completion-handler block 79
Improving Drawing Performance 80
Table A-1 Tips for improving drawing performance 80
Supporting High-Resolution Screens In Views 82
Listing B-1 Initializing a render buffer’s storage and retrieving its actual dimensions 85
Loading Images 88
Table C-1 Usage scenarios for images 88
Table C-2 Supported image formats 90
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
6
Figures, Tables, and ListingsThis document covers three related subjects:
● Drawing custom UI views. Custom UI views allow you to draw content that cannot easily be drawn with
standard UI elements. For example, a drawing program might use a custom view for the user’s drawing,
or an arcade game might use a custom view into which it draws sprites.
● Drawing into offscreen bitmap and PDF content. Whether you plan to display the images later, export
them to a file, or print the images to an AirPrint-enabled printer, offscreen drawing lets you do so without
interrupting the user’s workflow.
● Adding AirPrint support to your app. The iOS printing system lets you draw your content differently to fit
on the page.
Figure I-1 You can combine custom views with standard views, and even draw things offscreen.
At a Glance
The iOS native graphics system combines three major technologies: UIKit, Core Graphics, and Core Animation.
UIKit provides views and some high-level drawing functionality within those views, Core Graphics provides
additional (lower-level) drawing support within UIKit views, and Core Animation provides the ability to apply
transformations and animation to UIKit views. Core Animation is also responsible for view compositing.
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
7
About Drawing and Printing in iOSCustom UI Views Allow Greater Drawing Flexibility
This document describes how to draw into custom UI views using native drawing technologies. These
technologies, which include the Core Graphics and UIKit frameworks, support 2D drawing.
Before you consider using a custom UI view, you should make certain that you really need to do so. Native
drawing is suitable for handling more complex 2D layout needs. However, because custom views are
processor-intensive, you should limit the amount of drawing you do using native drawing technologies.
As an alternative to custom drawing, an iOS app can draw things onscreen in several other ways.
● Using standard (built-in) views. Standard viewslet you draw common user-interface primitives, including
lists, collections, alerts, images, progress bars, tables, and so on without the need to explicitly draw anything
yourself. Using built-in views not only ensures a consistent user experience between iOS apps, but also
saves you programming effort. If built-in views meet your needs, you should read ViewProgramming Guide
for iOS .
● Using Core Animation layers. Core Animation lets you create complex, layered 2D views with animation
and transformations. Core Animation is a good choice for animating standard views, or for combining
views in complex ways to present the illusion of depth, and can be combined with custom-drawn views
as described in this document. To learn more about Core Animation, read Core Animation Overview.
● Using OpenGL ES in a GLKit view or a custom view. The OpenGL ES framework provides a set of
open-standard graphics libraries geared primarily toward game development or apps that require high
frame rates, such as virtual prototyping apps and mechanical and architectural design apps. It conforms
to the OpenGL ES 2.0 and OpenGL ES v1.1 specifications. To learn more about OpenGL drawing, read
OpenGL ES Programming Guide for iOS .
● Using web content. The UIWebView class lets you display web-based user interfaces in an iOS app. To
learn more about displaying web content in a web view, read Using UIWebView to display select document
types and UIWebView Class Reference .
Depending on the type of app you are creating, it may be possible to use little or no custom drawing code.
Although immersive apps typically make extensive use of custom drawing code, utility and productivity apps
can often use standard views and controls to display their content.
The use of custom drawing code should be limited to situations where the content you display needsto change
dynamically. For example, a drawing app typically needsto use custom drawing code to track the user’s drawing
commands, and an arcade-style game may need to update the screen constantly to reflect the changing game
environment. In those situations, you should choose an appropriate drawing technology and create a custom
view class to handle events and update the display appropriately.
About Drawing and Printing in iOS
At a Glance
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
8On the other hand, if the bulk of your app’s interface is fixed, you can render the interface in advance to one
or more image files and display those images at runtime using the UIImageView class. You can layer image
views with other content as needed to build your interface. You can also use the UILabel class to display
configurable text and include buttons or other controls to provide interactivity. For example, an electronic
version of a board game can often be created with little or no custom drawing code.
Because custom views are generally more processor-intensive (with less help from the GPU), if you can do
what you need to do using standard views, you should always do so. Also, you should make your custom views
as small as possible, containing only content that you cannot draw in any other way, use use standard views
for everything else. If you need to combine standard UI elements with custom drawing, consider using a Core
Animation layer to superimpose a custom view with a standard view so that you draw as little as possible.
A Few Key Concepts Underpin Drawing With the Native Technologies
When you draw content with UIKit and Core Graphics, you should be familiar with a few concepts in addition
to the view drawing cycle.
● For the drawRect: method, UIKit creates a graphics context for rendering to the display. This graphics
context contains the information the drawing system needs to perform drawing commands, including
attributes such as fill and stroke color, the font, the clipping area, and line width. You can also create and
draw into custom graphics context for bitmap images and PDF content.
● UIKit has a default coordinate system where the origin of drawing is at the top-left of a view; positive
values extend downward and to the right of that origin. You can change the size, orientation, and position
of the default coordinate system relative to the underlying view or window by modifying the current
transformation matrix, which maps a view’s coordinate space to the device screen.
●
In iOS, the logical coordinate space, which measures distances in points, is not equal to the device
coordinate space, which measures in pixels. For greater precision, points are expressed in floating-point
values.
Relevant Chapter: “iOS Drawing Concepts” (page 12)
UIKit, Core Graphics, and Core Animation Give Your App Many Tools For Drawing
The UIKit and Core Graphics have many complementary graphics capabilitiesthat encompass graphics contexts,
Bézier paths, images, bitmaps, transparency layers, colors, fonts, PDF content, and drawing rectangles and
clipping areas. In addition, Core Graphics has functions related to line attributes, color spaces, pattern colors,
gradients, shadings, and image masks. The Core Animation framework enables you to create fluid animations
by manipulating and displaying content created with other technologies.
About Drawing and Printing in iOS
At a Glance
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
9Relevant Chapters: “iOS Drawing Concepts” (page 12), “Drawing Shapes Using Bézier Paths” (page
30), “Drawing and Creating Images” (page 40), “Generating PDF Content” (page 45)
Apps Can Draw Into Offscreen Bitmaps or PDFs
It is often useful for an app to draw content offscreen:
● Offscreen bitmap contexts are often used when scaling down photographs for upload, rendering content
into an image file for storage purposes, or using Core Graphics to generate complex images for display.
● Offscreen PDF contexts are often used when drawing user-generated content for printing purposes.
After you create an offscreen context, you can draw into it just as you would draw within the drawRect:
method of a custom view.
Relevant Chapters: “Drawing and Creating Images” (page 40), “Generating PDF Content” (page
45)
Apps Have a Range of Options for Printing Content
As of iOS 4.2, apps can print content wirelessly to supported printers using AirPrint. When assembling a print
job, they have three ways to give UIKit the content to print:
● They can give the framework one or more objects that are directly printable; such objects require minimal
app involvement. These are instances of the NSData, NSURL, UIImage, or ALAsset classes containing or
referencing image data or PDF content.
● They can assign a print formatter to the print job. A print formatter is an object that can lay out content
of a certain type (such as plain text or HTML) over multiple pages.
● They can assign a page renderer to the print job. A page renderer is usually an instance of a custom subclass
of UIPrintPageRenderer that draws the content to be printed in part or in full. A page renderer can
use one or more print formatters to help it draw and format its printable content.
About Drawing and Printing in iOS
At a Glance
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
10Relevant Chapter: “Printing” (page 52)
It’s Easy to Update Your App for High-Resolution Screens
Some iOS devices feature high-resolution screens, so your app must be prepared to run on these devices and
on devices with lower-resolution screens. iOS handles much of the work required to handle the different
resolutions, but your app must do the rest. Your tasksinclude providing specially named high-resolution images
and modifying your layer- and image-related code to take the current scale factor into account.
Relevant Appendix: “Supporting High-Resolution Screens In Views” (page 82)
See Also
For complete examples of printing, see the PrintPhoto , Recipes and Printing , and PrintWebView sample code
projects.
About Drawing and Printing in iOS
See Also
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
11High-quality graphics are an important part of your app’s user interface. Providing high-quality graphics not
only makes your app look good, but it also makes your app look like a natural extension to the rest of the
system. iOS provides two primary paths for creating high-quality graphics in your system: OpenGL or native
rendering using Quartz, Core Animation, and UIKit. This document describes native rendering. (To learn about
OpenGL drawing, see OpenGL ES Programming Guide for iOS .)
Quartz isthe main drawing interface, providing support for path-based drawing, anti-aliased rendering, gradient
fill patterns, images, colors, coordinate-space transformations, and PDF document creation, display, and parsing.
UIKit provides Objective-C wrappers for line art, Quartz images, and color manipulations. Core Animation
provides the underlying support for animating changes in many UIKit view properties and can also be used to
implement custom animations.
This chapter provides an overview of the drawing process for iOS apps, along with specific drawing techniques
for each of the supported drawing technologies. You will also find tips and guidance on how to optimize your
drawing code for the iOS platform.
Important: Not all UIKit classes are thread safe. Be sure to check the documentation before performing
drawing-related operations on threads other than your app’s main thread.
The UIKit Graphics System
In iOS, all drawing to the screen—regardless of whether it involves OpenGL, Quartz, UIKit, or Core
Animation—occurs within the confines of an instance of the UIView class or a subclass thereof. Views define
the portion of the screen in which drawing occurs. If you use system-provided views, this drawing is handled
for you automatically. If you define custom views, however, you must provide the drawing code yourself. If
you use Quartz, Core Animation, and UIKit to draw, you use the drawing concepts described in the following
sections.
In addition to drawing directly to the screen, UIKit also allows you to draw into offscreen bitmap and PDF
graphics contexts. When you draw in an offscreen context, you are not drawing in a view, which means that
concepts such as the view drawing cycle do not apply (unless you then obtain that image and draw it in an
image view or similar).
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
12
iOS Drawing ConceptsThe View Drawing Cycle
The basic drawing model forsubclasses of the UIView classinvolves updating content on demand. The UIView
class makes the update process easier and more efficient; however, by gathering the update requests you
make and delivering them to your drawing code at the most appropriate time.
When a view is first shown or when a portion of the view needs to be redrawn, iOS asks the view to draw its
content by calling the view’s drawRect: method.
There are several actions that can trigger a view update:
● Moving or removing another view that was partially obscuring your view
● Making a previously hidden view visible again by setting its hidden property to NO
● Scrolling a view off of the screen and then back onto the screen
● Explicitly calling the setNeedsDisplay or setNeedsDisplayInRect: method of your view
System views are redrawn automatically. For custom views, you must override the drawRect: method and
perform all your drawing inside it. Inside your drawRect: method, use the native drawing technologies to
draw shapes, text, images, gradients, or any other visual content you want. The first time your view becomes
visible, iOS passes a rectangle to the view’s drawRect: method that contains your view’s entire visible area.
During subsequent calls, the rectangle includes only the portion of the view that actually needsto be redrawn.
For maximum performance, you should redraw only affected content.
After calling your drawRect: method, the view marks itself as updated and waits for new actions to arrive
and trigger another update cycle. If your view displays static content, then all you need to do is respond to
changes in your view’s visibility caused by scrolling and the presence of other views.
If you want to change the contents of the view, however, you must tell your view to redraw its contents. To
do this, call the setNeedsDisplay or setNeedsDisplayInRect: method to trigger an update. For example,
if you were updating content several times a second, you might want to set up a timer to update your view.
You might also update your view in response to user interactions or the creation of new content in your view.
Important: Do not call your view’s drawRect: method yourself. That method should be called only by
code built into iOS during a screen repaint. At other times, no graphics context exists, so drawing is not
possible. (Graphics contexts are explained in the next section.)
Coordinate Systems and Drawing in iOS
When an app draws something in iOS, it has to locate the drawn content in a two-dimensional space defined
by a coordinate system. This notion mightseem straightforward at first glance, but it isn’t. Appsin iOS sometimes
have to deal with different coordinate systems when drawing.
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
13In iOS, all drawing occurs in a graphics context. Conceptually, a graphics context is an object that describes
where and how drawing should occur, including basic drawing attributes such as the colors to use when
drawing, the clipping area, line width and style information, font information, compositing options, and so on.
In addition, as shown in Figure 1-1 (page 14), each graphics context has a coordinate system. More precisely,
each graphics context has three coordinate systems:
● The drawing (user) coordinate system. This coordinate system is used when you issue drawing commands.
● The view coordinate system (base space). This coordinate system is a fixed coordinate system relative to
the view.
● The (physical) device coordinate system. This coordinate system represents pixels on the physical screen.
Figure 1-1 The relationship between drawing coordinates, view coordinates, and hardware coordinates
The drawing frameworks of iOS create graphics contexts for drawing to specific destinations—the screen,
bitmaps, PDF content, and so on—and these graphics contexts establish the initial drawing coordinate system
for that destination. This initial drawing coordinate system is known as the default coordinate system, and is
a 1:1 mapping onto the view’s underlying coordinate system.
Each view also has a current transformation matrix (CTM), a mathematical matrix that maps the points in the
current drawing coordinate system to the (fixed) view coordinate system. The app can modify this matrix (as
described later) to change the behavior of future drawing operations.
Each of the drawing frameworks of iOS establishes a default coordinate system based on the current graphics
context. In iOS, there are two main types of coordinate systems:
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
14● An upper-left-origin coordinate system (ULO), in which the origin of drawing operationsis at the upper-left
corner of the drawing area, with positive values extending downward and to the right. The default
coordinate system used by the UIKit and Core Animation frameworks is ULO-based.
● A lower-left-origin coordinate system (LLO), in which the origin of drawing operations is at the lower-left
corner of the drawing area, with positive values extending upward and to the right. The default coordinate
system used by Core Graphics framework is LLO-based.
These coordinate systems are shown in Figure 1-2.
Figure 1-2 Default coordinate systems in iOS
UIKit Core Graphics
(0.0, 0.0)
(0.0, 0.0)
Note: The default coordinate system in OS X is LLO-based. Although the drawing functions and
methods of the Core Graphics and AppKit frameworks are perfectly suited to this default coordinate
system, AppKit provides programmatic support for flipping the drawing coordinate system to have
an upper-left origin.
Before calling your view’s drawRect: method, UIKit establishes the default coordinate system for drawing to
the screen by making a graphics context available for drawing operations. Within a view’s drawRect: method,
an app can set graphics-state parameters (such as fill color) and draw to the current graphics context without
needing to refer to the graphics context explicitly. This implicit graphics context establishes a ULO default
coordinate system.
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
15Points Versus Pixels
In iOS there is a distinction between the coordinates you specify in your drawing code and the pixels of the
underlying device. When using native drawing technologies such as Quartz, UIKit, and Core Animation, the
drawing coordinate space and the view’s coordinate space are both logical coordinate spaces, with distances
measured in points. These logical coordinate systems are decoupled from the device coordinate space used
by the system frameworks to manage the pixels onscreen.
The system automatically maps points in the view’s coordinate space to pixels in the device coordinate space,
but this mapping is not always one-to-one. This behavior leads to an important fact that you should always
remember:
One point does not necessarily correspond to one physical pixel.
The purpose of using points (and the logical coordinate system) is to provide a consistent size of output that
is device independent. For most purposes, the actualsize of a point isirrelevant. The goal of pointsisto provide
a relatively consistentscale that you can use in your code to specify the size and position of views and rendered
content. How points are actually mapped to pixels is a detail that is handled by the system frameworks. For
example, on a device with a high-resolution screen, a line that is one point wide may actually result in a line
that is two physical pixels wide. The result is that if you draw the same content on two similar devices, with
only one of them having a high-resolution screen, the content appears to be about the same size on both
devices.
In iOS, the UIScreen, UIView, UIImage, and CALayer classes provide properties to obtain (and, in some
cases, set) a scale factor that describes the relationship between points and pixels for that particular object.
For example, every UIKit view has a contentScaleFactor property. On a standard-resolution screen, the
scale factor is typically 1.0. On a high-resolution screen, the scale factor is typically 2.0. In the future, other scale
factors may also be possible. (In iOS prior to version 4, you should assume a scale factor of 1.0.)
Native drawing technologies, such as Core Graphics, take the current scale factor into account for you. For
example, if one of your views implements a drawRect: method, UIKit automatically sets the scale factor for
that view to the screen’sscale factor. In addition, UIKit automatically modifiesthe current transformation matrix
of any graphics contexts used during drawing to take into account the view’s scale factor. Thus, any content
you draw in your drawRect: method is scaled appropriately for the underlying device’s screen.
Because of this automatic mapping, when writing drawing code, pixels usually don’t matter. However, there
are times when you might need to change your app’s drawing behavior depending on how points are mapped
to pixels—to download higher-resolution images on devices with high-resolution screens or to avoid scaling
artifacts when drawing on a low-resolution screen, for example.
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
16In iOS, when you draw things onscreen, the graphics subsystem uses a technique called antialiasing to
approximate a higher-resolution image on a lower-resolution screen. The best way to explain this technique
is by example. When you draw a black vertical line on a solid white background, if that line falls exactly on a
pixel, it appears as a series of black pixels in a field of white. If it appears exactly between two pixels, however,
it appears as two grey pixels side-by-side, as shown in Figure 1-3.
Figure 1-3 A one-point line centered at a whole-numbered point value
Positions defined by whole-numbered points fall at the midpoint between pixels. For example, if you draw a
one-pixel-wide vertical line from (1.0, 1.0) to (10.0, 10.0), you get a fuzzy grey line. If you draw a two-pixel-wide
line, you get a solid black line because it fully covers two pixels (one on either side of the specified point). As
a rule, lines that are an odd number of physical pixels wide appear softer than lines with widths measured in
even numbers of physical pixels unless you adjust their position to make them cover pixels fully.
Where the scale factor comes into play is when determining how many pixels are covered by a one-point-wide
line.
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
17On a low-resolution display (with a scale factor of 1.0), a one-point-wide line is one pixel wide. To avoid
antialiasing when you draw a one-point-wide horizontal or vertical line, if the line is an odd number of pixels
in width, you must offset the position by 0.5 points to either side of a whole-numbered position. If the line is
an even number of points in width, to avoid a fuzzy line, you must not do so.
Figure 1-4 Appearance of one-point-wide lines on standard and retina displays
On a high-resolution display (with a scale factor of 2.0), a line that is one point wide is not antialiased at all
because it occupies two full pixels (from -0.5 to +0.5). To draw a line that covers only a single physical pixel,
you would need to make it 0.5 points in thickness and offset its position by 0.25 points. A comparison between
the two types of screens is shown in Figure 1-4.
Of course, changing drawing characteristics based on scale factor may have unexpected consequences. A
1-pixel-wide line might look nice on some devices but on a high-resolution device might be so thin that it is
difficult to see clearly. It is up to you to determine whether to make such a change.
Obtaining Graphics Contexts
Most of the time, graphics contexts are configured for you. Each view object automatically creates a graphics
contextso that your code can start drawing immediately assoon as your custom drawRect: method is called.
As part of this configuration, the underlying UIView class creates a graphics context (a CGContextRef opaque
type) for the current drawing environment.
If you want to draw somewhere other than your view (for example, to capture a series of drawing operations
in a PDF or bitmap file), or if you need to call Core Graphics functions that require a context object, you must
take additional steps to obtain a graphics context object. The sections below explain how.
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
18For more information about graphics contexts, modifying the graphics state information, and using graphics
contextsto create customcontent,seeQuartz 2DProgrammingGuide . For a list of functions used in conjunction
with graphics contexts, see CGContext Reference , CGBitmapContext Reference , and CGPDFContext Reference .
Drawing to the Screen
If you use Core Graphics functions to draw to a view, either in the drawRect: method or elsewhere, you’ll
need a graphics context for drawing. (The first parameter of many of these functions must be a CGContextRef
object.) You can call the function UIGraphicsGetCurrentContext to get an explicit version of the same
graphics context that’s made implicit in drawRect:. Because it’s the same graphics context, the drawing
functions should also make reference to a ULO default coordinate system.
If you want to use Core Graphics functions to draw in a UIKit view, you should use the ULO coordinate system
of UIKit for drawing operations. Alternatively, you can apply a flip transform to the CTM and then draw an
object in the UIKit view using Core Graphics native LLO coordinate system. “Flipping the Default Coordinate
System” (page 25) discusses flip transforms in detail.
The UIGraphicsGetCurrentContext function always returns the graphics context currently in effect. For
example, if you create a PDF context and then call UIGraphicsGetCurrentContext, you’d receive that PDF
context. You must use the graphics context returned by UIGraphicsGetCurrentContext if you use Core
Graphics functions to draw to a view.
Note: The UIPrintPageRenderer class declares several methods for drawing printable content.
In a manner similar to drawRect:, UIKit installs an implicit graphics context for implementations
of these methods. This graphics context establishes a ULO default coordinate system.
Drawing to Bitmap Contexts and PDF Contexts
UIKit provides functions for rendering images in a bitmap graphics context and for generating PDF content
by drawing in a PDF graphics context. Both of these approachesrequire that you first call a function that creates
a graphics context—a bitmap context or a PDF context, respectively. The returned object serves as the current
(and implicit) graphics context for subsequent drawing and state-setting calls. When you finish drawing in the
context, you call another function to close the context.
Both the bitmap context and the PDF context provided by UIKit establish a ULO default coordinate system.
Core Graphics has corresponding functions for rendering in a bitmap graphics context and for drawing in a
PDF graphics context. The context that an app directly creates through Core Graphics, however, establishes a
LLO default coordinate system.
iOS Drawing Concepts
The UIKit Graphics System
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
19Note: In iOS, it is recommended that you use the UIKit functions for drawing to bitmap contexts
and PDF contexts. However, if you do use the Core Graphics alternatives and intend to display the
rendered results, you will have to adjust your code to compensate for the difference in default
coordinate systems. See “Flipping the Default Coordinate System” (page 25) for more information.
For details, see “Drawing and Creating Images” (page 40) (for drawing to bitmap contexts) and “Generating
PDF Content” (page 45) (for drawing to PDF contexts).
Color and Color Spaces
iOS supports the full range of color spaces available in Quartz; however, most apps should need only the RGB
color space. Because iOS is designed to run on embedded hardware and display graphics onscreen, the RGB
color space is the most appropriate one to use.
The UIColor object provides convenience methods for specifying color values using RGB, HSB, and grayscale
values. When creating colors in this way, you never need to specify the color space. It is determined for you
automatically by the UIColor object.
You can also use the CGContextSetRGBStrokeColor and CGContextSetRGBFillColor functions in the
Core Graphics framework to create and set colors. Although the Core Graphics framework includes support for
creating colors using other color spaces, and for creating custom color spaces, using those colors in your
drawing code is not recommended. Your drawing code should always use RGB colors.
Drawing with Quartz and UIKit
Quartz is the general name for the native drawing technology in iOS. The Core Graphics framework is at the
heart of Quartz, and is the primary interface you use for drawing content. This framework provides data types
and functions for manipulating the following:
● Graphics contexts
● Paths
●
Images and bitmaps
● Transparency layers
● Colors, pattern colors, and color spaces
● Gradients and shadings
● Fonts
● PDF content
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
20UIKit builds on the basic features of Quartz by providing a focused set of classesfor graphics-related operations.
The UIKit graphics classes are not intended as a comprehensive set of drawing tools—Core Graphics already
providesthat. Instead, they provide drawing support for other UIKit classes. UIKitsupport includesthe following
classes and functions:
● UIImage, which implements an immutable class for displaying images
● UIColor, which provides basic support for device colors
● UIFont, which provides font information for classes that need it
● UIScreen, which provides basic information about the screen
● UIBezierPath, which enables your app to draw lines, arcs, ovals, and other shapes.
● Functions for generating a JPEG or PNG representation of a UIImage object
● Functions for drawing to a bitmap graphics context
● Functions for generating PDF data by drawing to a PDF graphics context
● Functions for drawing rectangles and clipping the drawing area
● Functions for changing and getting the current graphics context
For information about the classes and methods that comprise UIKit, see UIKit Framework Reference . For more
information about the opaque types and functions that comprise the Core Graphics framework, see Core
Graphics Framework Reference .
Configuring the Graphics Context
Before calling your drawRect: method, the view object creates a graphics context and sets it as the current
context. This context exists only for the lifetime of the drawRect: call. You can retrieve a pointer to this
graphics context by calling the UIGraphicsGetCurrentContext function. This function returns a reference
to a CGContextRef type, which you pass to Core Graphics functions to modify the current graphics state.
Table 1-1 lists the main functions you use to set different aspects of the graphics state. For a complete list of
functions, see CGContext Reference . This table also lists UIKit alternatives where they exist.
Table 1-1 Core graphics functions for modifying graphics state
Graphics state Core Graphics functions UIKit alternatives
CGContextRotateCTM None
CGContextScaleCTM
CGContextTranslateCTM
CGContextConcatCTM
Current transformation matrix
(CTM)
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
21Graphics state Core Graphics functions UIKit alternatives
Clipping area CGContextClipToRect UIRectClip function
CGContextSetLineWidth None
CGContextSetLineJoin
CGContextSetLineCap
CGContextSetLineDash
CGContextSetMiterLimit
Line: Width, join, cap, dash,
miter limit
Accuracy of curve estimation CGContextSetFlatness None
Anti-aliasing setting CGContextSetAllowsAntialiasing None
CGContextSetRGBFillColor UIColor class
CGContextSetRGBStrokeColor
Color: Fill and stroke settings
Alpha global value CGContextSetAlpha None
(transparency)
Rendering intent CGContextSetRenderingIntent None
CGContextSetFillColorSpace UIColor class
CGContextSetStrokeColorSpace
Color space: Fill and stroke
settings
CGContextSetFont UIFont class
CGContextSetFontSize
CGContextSetCharacterSpacing
Text: Font, font size, character
spacing, text drawing mode
The UIImage class
and various drawing
functions let you
specify which blend
mode to use.
Blend mode CGContextSetBlendMode
The graphics context contains a stack of saved graphics states. When Quartz creates a graphics context, the
stack is empty. Using the CGContextSaveGState function pushes a copy of the current graphics state onto
the stack. Thereafter, modifications you make to the graphics state affect subsequent drawing operations but
do not affect the copy stored on the stack. When you are done making modifications, you can return to the
previous graphics state by popping the saved state off the top of the stack using the
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
22CGContextRestoreGState function. Pushing and popping graphics states in this manner is a fast way to
return to a previous state and eliminates the need to undo each state change individually. It is also the only
way to restore some aspects of the state, such as the clipping path, back to their original settings.
For general information about graphics contexts and using them to configure the drawing environment, see
“Graphics Contexts” in Quartz 2D Programming Guide .
Creating and Drawing Paths
A path is a vector-based shapes created from a sequence of lines and Bézier curves. UIKit includes the
UIRectFrame and UIRectFill functions(among others) for drawing simple pathssuch asrectanglesin your
views. Core Graphics also includes convenience functions for creating simple paths such as rectangles and
ellipses.
For more complex paths, you must create the path yourself using the UIBezierPath class of UIKit, or using
the functions that operate on the CGPathRef opaque type in the Core Graphics framework. Although you can
construct a path without a graphics context using either API, the pointsin the path still must refer to the current
coordinate system (which either has a ULO or LLO orientation), and you still need a graphics context to actually
render the path.
When drawing a path, you must have a current context set. This context can be a custom view’s context (in
drawRect:), a bitmap context, or a PDF context. The coordinate system determines how the path is rendered.
UIBezierPath assumes a ULO coordinate system. Thus, if your view is flipped (to use LLO coordinates), the
resulting shape may render differently than intended. For best results, you should alwaysspecify pointsrelative
to the origin of the current coordinate system of the graphics context used for rendering.
Note: Arcs are an aspect of paths that require additional work even if this “rule” is followed. If you
create a path using Core Graphic functions that locate points in a ULO coordinate system, and then
render the path in a UIKit view, the direction an arc “points” is different. See “Side Effects of Drawing
with Different Coordinate Systems” (page 25) for more on this subject.
For creating paths in iOS, it is recommended that you use UIBezierPath instead of CGPath functions unless
you need some of the capabilities that only Core Graphics provides, such as adding ellipses to paths. For more
on creating and rendering paths in UIKit, see “Drawing Shapes Using Bézier Paths” (page 30).
For information on using UIBezierPath to draw paths, see “Drawing Shapes Using Bézier Paths” (page 30).
For information on how to draw paths using Core Graphics, including information about how you specify the
pointsfor complex path elements,see “Paths”inQuartz 2DProgramming Guide . Forinformation on the functions
you use to create paths, see CGContext Reference and CGPath Reference .
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
23Creating Patterns, Gradients, and Shadings
The Core Graphics framework includes additional functions for creating patterns, gradients, and shadings. You
use these typesto create non monochrome colors and use them to fill the paths you create. Patterns are created
from repeating images or content. Gradients and shadings provide different ways to create smooth transitions
from color to color.
The details for creating and using patterns, gradients, and shadings are all covered in Quartz 2D Programming
Guide .
Customizing the Coordinate Space
By default, UIKit creates a straightforward current transformation matrix that maps points onto pixels. Although
you can do all of your drawing without modifying that matrix, sometimes it can be convenient to do so.
When your view’s drawRect: method is first called, the CTM is configured so that the origin of the coordinate
system matches the your view’s origin, its positive X axis extends to the right, and its positive Y axis extends
down. However, you can change the CTM by adding scaling, rotation, and translation factors to it and thereby
change the size, orientation, and position of the default coordinate system relative to the underlying view or
window.
Using Coordinate Transforms to Improve Drawing Performance
Modifying the CTM is a standard technique for drawing content in a view because it allows you to reuse paths,
which potentially reduces the amount of computation required while drawing. For example, if you want to
draw a square starting at the point (20, 20), you could create a path that moves to (20, 20) and then draws the
needed set of lines to complete the square. However, if you later decide to move that square to the point (10,
10), you would have to recreate the path with the new starting point. Because creating paths is a relatively
expensive operation, it is preferable to create a square whose origin is at (0, 0) and to modify the CTM so that
the square is drawn at the desired origin.
In the Core Graphics framework, there are two ways to modify the CTM. You can modify the CTM directly using
the CTM manipulation functions defined in CGContext Reference . You can also create a CGAffineTransform
structure, apply any transformations you want, and then concatenate that transform onto the CTM. Using an
affine transform lets you group transformations and then apply them to the CTM all at once. You can also
evaluate and invert affine transforms and use them to modify point, size, and rectangle values in your code.
For more information on using affine transforms, see Quartz 2D Programming Guide and CGAffineTransform
Reference .
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
24Flipping the Default Coordinate System
Flipping in UIKit drawing modifiesthe backing CALayer to align a drawing environment having a LLOcoordinate
system with the default coordinate system of UIKit. If you only use UIKit methods and function for drawing,
you shouldn’t need to flip the CTM. However, if you mix Core Graphics or Image I/O function calls with UIKit
calls, flipping the CTM might be necessary.
Specifically, if you draw an image or PDF document by calling Core Graphics functions directly, the object is
rendered upside-down in the view’s context. You must flip the CTM to display the image and pages correctly.
To flip a object drawn to a Core Graphics context so that it appears correctly when displayed in a UIKit view,
you must modify the CTM in two steps. You translate the origin to the upper-left corner of the drawing area,
and then you apply a scale translation, modifying the y-coordinate by -1. The code for doing this looks similar
to the following:
CGContextSaveGState(graphicsContext);
CGContextTranslateCTM(graphicsContext, 0.0, imageHeight);
CGContextScaleCTM(graphicsContext, 1.0, -1.0);
CGContextDrawImage(graphicsContext, image, CGRectMake(0, 0, imageWidth,
imageHeight));
CGContextRestoreGState(graphicsContext);
If you create a UIImage object initialized with a Core Graphics image object, UIKit performs the flip transform
for you. Every UIImage object is backed by a CGImageRef opaque type. You can access the Core Graphics
object through the CGImage property and do some work with the image. (Core Graphics has image-related
facilities not available in UIKit.) When you are finished, you can recreate the UIImage object from the modified
CGImageRef object.
Note: You can use the Core Graphics function CGContextDrawImage to draw an image to any
rendering destination. This function has two parameters, the first for a graphics context and the
second for a rectangle that defines both the size of the image and its location in a drawing surface
such as a view. When drawing an image with CGContextDrawImage, if you don’t adjust the current
coordinate system to a LLO orientation, the image appears inverted in a UIKit view. Additionally, the
origin of the rectangle passed into this function is relative to the origin of the coordinate system
that is current when the function is called.
Side Effects of Drawing with Different Coordinate Systems
Some rendering oddities are brought to light when you draw an object with with reference to the default
coordinate system of one drawing technology and then render it in a graphics context of the other. You may
want to adjust your code to account for these side effects.
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
25Arcs and Rotations
If you draw an path with functionssuch as CGContextAddArc and CGPathAddArc and assume a LLOcoordinate
system, then you need to flip the CTM to render the arc correctly in a UIKit view. However, if you use the same
function to create an arc with points located in a ULO coordinate system and then render the path in a UIKit
view, you’ll notice that the arc is an altered version of its original. The terminating endpoint of the arc now
pointsin the opposite direction of what that endpoint would do were the arc created using the UIBezierPath
class. For example, a downward-pointing arrow now points upward (as shown in Figure 1-5), and the direction
in which the arc “bends” is also different. You must change the direction of Core Graphics-drawn arcsto account
for the ULO-based coordinate system; this direction is controlled by the startAngle and endAngle parameters
of those functions.
Figure 1-5 Arc rendering in Core Graphics versus UIKit
Arc specified in Core Graphics Arc rendered in UIKit
y
y
x
(0,0)
(0,0)
x
You can observe the same kind of mirroring effect if you rotate an object (for example, by calling
CGContextRotateCTM). If you rotate an object using Core Graphics calls that make reference to a ULO
coordinate system, the direction of the object when rendered in UIKit is reversed. You must account for the
different directions of rotation in your code; with CGContextRotateCTM, you do this by inverting the sign of
the angle parameter (so, for example, a negative value becomes a positive value).
Shadows
The direction a shadow falls from its object is specified by an offset value, and the meaning of that offset is a
convention of a drawing framework. In UIKit, positive x and y offsets make a shadow go down and to the right
of an object. In Core Graphics, positive x and y offsets make a shadow go up and to the right of an object.
Flipping the CTM to align an object with the default coordinate system of UIKit does not affect the object’s
shadow, and so a shadow does not correctly track its object. To get it to track correctly, you must modify the
offset values appropriately for the current coordinate system.
iOS Drawing Concepts
Drawing with Quartz and UIKit
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
26Note: Prior to iOS 3.2, Core Graphics and UIKit shared the same convention for shadow direction:
positive offset values make the shadow go down and to the right of an object.
Applying Core Animation Effects
Core Animation is an Objective-C framework that provides infrastructure for creating fluid, real-time animations
quickly and easily. Core Animation is not a drawing technology itself, in the sense that it does not provide
primitive routines for creating shapes, images, or other types of content. Instead, it is a technology for
manipulating and displaying content that you created using other technologies.
Most apps can benefit from using Core Animation in some form in iOS. Animations provide feedback to the
user about what is happening. For example, when the user navigates through the Settings app, screens slide
in and out of view based on whether the user is navigating further down the preferences hierarchy or back up
to the root node. This kind of feedback is important and provides contextual information for the user. It also
enhances the visual style of an app.
In most cases, you may be able to reap the benefits of Core Animation with very little effort. For example,
several properties of the UIView class (including the view’s frame, center, color, and opacity—among others)
can be configured to trigger animations when their values change. You have to do some work to let UIKit know
that you want these animations performed, but the animations themselves are created and run automatically
for you. For information about how to trigger the built-in view animations, see “Animating Views” in UIView
Class Reference .
When you go beyond the basic animations, you must interact more directly with Core Animation classes and
methods. The following sections provide information about Core Animation and show you how to work with
its classes and methods to create typical animations in iOS. For additional information about Core Animation
and how to use it, see Core Animation Programming Guide .
About Layers
The key technology in Core Animation is the layer object. Layers are lightweight objects that are similar in
nature to views, but that are actually model objects that encapsulate geometry, timing, and visual properties for
the content you want to display. The content itself is provided in one of three ways:
● You can assign a CGImageRef to the contents property of the layer object.
● You can assign a delegate to the layer and let the delegate handle the drawing.
● You can subclass CALayer and override one of the display methods.
iOS Drawing Concepts
Applying Core Animation Effects
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
27When you manipulate a layer object’s properties, what you are actually manipulating is the model-level data
that determines how the associated content should be displayed. The actual rendering of that content is
handled separately from your code and is heavily optimized to ensure it is fast. All you must do is set the layer
content, configure the animation properties, and then let Core Animation take over.
For more information about layers and how they are used, see Core Animation Programming Guide .
About Animations
When it comes to animating layers, Core Animation uses separate animation objects to control the timing and
behavior of the animation. The CAAnimation class and its subclasses provide different types of animation
behaviors that you can use in your code. You can create simple animations that migrate a property from one
value to another, or you can create complex keyframe animations that track the animation through the set of
values and timing functions you provide.
Core Animation also lets you group multiple animations together into a single unit, called a transaction. The
CATransaction object manages the group of animations as a unit. You can also use the methods of this class
to set the duration of the animation.
For examples of how to create custom animations, see Animation Types and Timing Programming Guide .
Accounting for Scale Factors in Core Animation Layers
Apps that use Core Animation layers directly to provide content may need to adjust their drawing code to
account for scale factors. Normally, when you draw in your view’s drawRect: method, or in the
drawLayer:inContext: method of the layer’s delegate, the system automatically adjusts the graphics
context to account for scale factors. However, knowing or changing that scale factor might still be necessary
when your view does one of the following:
● Creates additional Core Animation layers with different scale factors and composites them into its own
content
● Sets the contents property of a Core Animation layer directly
Core Animation’s compositing engine looks at the contentsScale property of each layer to determine
whether the contents of that layer need to be scaled during compositing. If your app creates layers without
an associated view, each new layer object’s scale factor is initially set to 1.0. If you do not change that scale
factor, and if you subsequently draw the layer on a high-resolution screen, the layer’s contents are scaled
automatically to compensate for the difference in scale factors. If you do not want the contents to be scaled,
you can change the layer’s scale factor to 2.0 by setting a new value for the contentsScale property, but if
you do so without providing high-resolution content, your existing content may appear smaller than you were
expecting. To fix that problem, you need to provide higher-resolution content for your layer.
iOS Drawing Concepts
Applying Core Animation Effects
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
28Important: The contentsGravity property of the layer plays a role in determining whether
standard-resolution layer content is scaled on a high-resolution screen. This property is set to the value
kCAGravityResize by default, which causes the layer content to be scaled to fit the layer’s bounds.
Changing the gravity to a nonresizing option eliminates the automatic scaling that would otherwise occur.
In such a situation, you may need to adjust your content or the scale factor accordingly.
Adjusting the content of your layer to accommodate different scale factors is most appropriate when you set
the contents property of a layer directly. Quartz images have no notion of scale factors and therefore work
directly with pixels. Therefore, before creating the CGImageRef object you plan to use for the layer’s contents,
check the scale factor and adjust the size of your image accordingly. Specifically, load an appropriately sized
image from your app bundle or use the UIGraphicsBeginImageContextWithOptions function to create
an image whose scale factor matches the scale factor of your layer. If you do not create a high-resolution
bitmap, the existing bitmap may be scaled as discussed previously.
For information on how to specify and load high-resolution images, see “Loading Images into Your App” (page
83). For information about how to create high-resolution images, see “Drawing to Bitmap Contexts and PDF
Contexts” (page 19).
iOS Drawing Concepts
Applying Core Animation Effects
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
29In iOS 3.2 and later, you can use the UIBezierPath class to create vector-based paths. The UIBezierPath
class is an Objective-C wrapper for the path-related features in the Core Graphics framework. You can use this
classto define simple shapes,such as ovals and rectangles, as well as complex shapesthat incorporate multiple
straight and curved line segments.
You can use path objects to draw shapes in your app’s user interface. You can draw the path’s outline, fill the
space it encloses, or both. You can also use paths to define a clipping region for the current graphics context,
which you can then use to modify subsequent drawing operations in that context.
Bézier Path Basics
A UIBezierPath object is a wrapper for a CGPathRef data type. Paths are vector-based shapes that are built
using line and curve segments. You can use line segments to create rectangles and polygons, and you can use
curve segments to create arcs, circles, and complex curved shapes. Each segment consists of one or more
points(in the current coordinate system) and a drawing command that defines how those points are interpreted.
Each set of connected line and curve segments form what is referred to as a subpath. The end of one line or
curve segment in a subpath defines the beginning of the next. A single UIBezierPath object may contain
one or more subpaths that define the overall path, separated by moveToPoint: commands that effectively
raise the drawing pen and move it to a new location.
The processes for building and using a path object are separate. Building the path is the first process and
involves the following steps:
1. Create the path object.
2. Set any relevant drawing attributes of your UIBezierPath object, such as the lineWidth or
lineJoinStyle properties for stroked paths or the usesEvenOddFillRule property for filled paths.
These drawing attributes apply to the entire path.
3. Set the starting point of the initial segment using the moveToPoint: method.
4. Add line and curve segments to define a subpath.
5. Optionally, close the subpath by calling closePath, which draws a straight line segment from the end
of the last segment to the beginning of the first.
6. Optionally, repeat the steps 3, 4, and 5 to define additional subpaths.
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
30
Drawing Shapes Using Bézier PathsWhen building your path, you should arrange the points of your path relative to the origin point (0, 0). Doing
so makes it easier to move the path around later. During drawing, the points of your path are applied as-is to
the coordinate system of the current graphics context. If your path is oriented relative to the origin, all you
have to do to reposition it is apply an affine transform with a translation factor to the current graphics context.
The advantage of modifying the graphics context (as opposed to the path object itself) is that you can easily
undo the transformation by saving and restoring the graphics state.
To draw your path object, you use the stroke and fill methods. These methods render the line and curve
segments of your path in the current graphics context. The rendering process involves rasterizing the line and
curve segments using the attributes of the path object. The rasterization process does not modify the path
object itself. As a result, you can render the same path object multiple timesin the current context or in another
context.
Adding Lines and Polygons to Your Path
Lines and polygons are simple shapes that you build point-by-point using the moveToPoint: and
addLineToPoint: methods. The moveToPoint: method sets the starting point of the shape you want to
create. From that point, you create the lines of the shape using the addLineToPoint: method. You create
the linesin succession, with each line being formed between the previous point and the new point you specify.
Listing 2-1 shows the code needed to create a pentagon shape using individual line segments. (Figure 2-1
showsthe result of drawing thisshape with appropriate stroke and fill colorsettings, as described in “Rendering
the Contents of a Bézier Path Object” (page 36).) This code sets the initial point of the shape and then adds
four connected line segments. The fifth segment is added by the call to the closePath method, which connects
the last point (0, 40) with the first point (100, 0).
Listing 2-1 Creating a pentagon shape
UIBezierPath *aPath = [UIBezierPath bezierPath];
// Set the starting point of the shape.
[aPath moveToPoint:CGPointMake(100.0, 0.0)];
// Draw the lines.
[aPath addLineToPoint:CGPointMake(200.0, 40.0)];
[aPath addLineToPoint:CGPointMake(160, 140)];
[aPath addLineToPoint:CGPointMake(40.0, 140)];
[aPath addLineToPoint:CGPointMake(0.0, 40.0)];
Drawing Shapes Using Bézier Paths
Adding Lines and Polygons to Your Path
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
31[aPath closePath];
Figure 2-1 Shape drawn with methods of the UIBezierPath class
Using the closePath method not only ends the subpath describing the shape, it also draws a line segment
between the first and last points. This is a convenient way to finish a polygon without having to draw the final
line.
Adding Arcs to Your Path
The UIBezierPath class providessupport for initializing a new path object with an arc segment. The parameters
of the bezierPathWithArcCenter:radius:startAngle:endAngle:clockwise: method define the
circle that containsthe desired arc and the start and end points of the arc itself. Figure 2-2 showsthe components
that go into creating an arc, including the circle that defines the arc and the angle measurements used to
Drawing Shapes Using Bézier Paths
Adding Arcs to Your Path
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
32specify it. In this case, the arc is created in the clockwise direction. (Drawing the arc in the counterclockwise
direction would paint the dashed portion of the circle instead.) The code for creating this arc isshown in Listing
2-2 (page 33).
Figure 2-2 An arc in the default coordinate system
100 200
100
200
(0, 0)
3π
4
(135°) rad
75 pts
0 rad (0°)
(150, 150)
Listing 2-2 Creating a new arc path
// pi is approximately equal to 3.14159265359.
#define DEGREES_TO_RADIANS(degrees) ((pi * degrees)/ 180)
- (UIBezierPath *)createArcPath
{
UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150,
150)
radius:75
startAngle:0
endAngle:DEGREES_TO_RADIANS(135)
clockwise:YES];
return aPath;
}
Drawing Shapes Using Bézier Paths
Adding Arcs to Your Path
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
33If you want to incorporate an arc segment into the middle of a path, you must modify the path object’s
CGPathRef data type directly. For more information about modifying the path using Core Graphics functions,
see “Modifying the Path Using Core Graphics Functions” (page 35).
Adding Curves to Your Path
The UIBezierPath class provides support for adding cubic and quadratic Bézier curves to a path. Curve
segments start at the current point and end at the point you specify. The shape of the curve is defined using
tangent lines between the start and end points and one or more control points. Figure 2-3 shows approximations
of both types of curve and the relationship between the control points and the shape of the curve. The exact
curvature of each segment involves a complex mathematical relationship between all of the points and is well
documented online and at Wikipedia.
Figure 2-3 Curve segments in a path
Start point
Control point 2
Endpoint
Control point 1
A Current point
B Control point
C Endpoint
Bézier curve Quad curve
To add curves to a path, you use the following methods:
● Cubic curve:addCurveToPoint:controlPoint1:controlPoint2:
● Quadratic curve:addQuadCurveToPoint:controlPoint:
Because curves rely on the current point of the path, you must set the current point before calling either of
the preceding methods. Upon completion of the curve, the current point is updated to the new end point you
specified.
Drawing Shapes Using Bézier Paths
Adding Curves to Your Path
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
34Creating Oval and Rectangular Paths
Ovals and rectangles are common types of pathsthat are built using a combination of curve and line segments.
The UIBezierPath class includes the bezierPathWithRect: and bezierPathWithOvalInRect:
convenience methods for creating paths with oval or rectangular shapes. Both of these methods create a new
path object and initialize it with the specified shape. You can use the returned path object right away or add
more shapes to it as needed.
If you want to add a rectangle to an existing path object, you must do so using the moveToPoint:,
addLineToPoint:, and closePath methods as you would for any other polygon. Using the closePath
method for the final side of the rectangle is a convenient way to add the final line of the path and also mark
the end of the rectangle subpath.
If you want to add an oval to an existing path, the simplest way to do so is to use Core Graphics. Although you
can use the addQuadCurveToPoint:controlPoint: to approximate an oval surface, the
CGPathAddEllipseInRect function is much simpler to use and more accurate. For more information, see
“Modifying the Path Using Core Graphics Functions” (page 35).
Modifying the Path Using Core Graphics Functions
The UIBezierPath class is really just a wrapper for a CGPathRef data type and the drawing attributes
associated with that path. Although you normally add line and curve segments using the methods of the
UIBezierPath class, the class also exposes a CGPath property that you can use to modify the underlying path
data type directly. You can use this property when you would prefer to build your path using the functions of
the Core Graphics framework.
There are two ways to modify the path associated with a UIBezierPath object. You can modify the path
entirely using Core Graphicsfunctions, or you can use a mixture of Core Graphicsfunctions and UIBezierPath
methods. Modifying the path entirely using Core Graphics calls is easier in some ways. You create a mutable
CGPathRef data type and call whatever functions you need to modify its path information. When you are
done you assign your path object to the corresponding UIBezierPath object, as shown in Listing 2-3.
Listing 2-3 Assigning a new CGPathRef to a UIBezierPath object
// Create the path data.
CGMutablePathRef cgPath = CGPathCreateMutable();
CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(0, 0, 300, 300));
CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(50, 50, 200, 200));
// Now create the UIBezierPath object.
Drawing Shapes Using Bézier Paths
Creating Oval and Rectangular Paths
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
35UIBezierPath *aPath = [UIBezierPath bezierPath];
aPath.CGPath = cgPath;
aPath.usesEvenOddFillRule = YES;
// After assigning it to the UIBezierPath object, you can release
// your CGPathRef data type safely.
CGPathRelease(cgPath);
If you choose to use a mixture of Core Graphics functions and UIBezierPath methods, you must carefully
move the path information back and forth between the two. Because a UIBezierPath object owns its
underlying CGPathRef data type, you cannot simply retrieve that type and modify it directly. Instead, you
must make a mutable copy, modify the copy, and then assign the copy back to the CGPath property as shown
in Listing 2-4.
Listing 2-4 Mixing Core Graphics and UIBezierPath calls
UIBezierPath *aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 300,
300)];
// Get the CGPathRef and create a mutable version.
CGPathRef cgPath = aPath.CGPath;
CGMutablePathRef mutablePath = CGPathCreateMutableCopy(cgPath);
// Modify the path and assign it back to the UIBezierPath object.
CGPathAddEllipseInRect(mutablePath, NULL, CGRectMake(50, 50, 200, 200));
aPath.CGPath = mutablePath;
// Release both the mutable copy of the path.
CGPathRelease(mutablePath);
Rendering the Contents of a Bézier Path Object
After creating a UIBezierPath object, you can render it in the current graphics context using its stroke and
fill methods. Before you call these methods, though, there are usually a few other tasksto perform to ensure
your path is drawn correctly:
Drawing Shapes Using Bézier Paths
Rendering the Contents of a Bézier Path Object
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
36● Set the desired stroke and fill colors using the methods of the UIColor class.
● Position the shape where you want it in the target view.
If you created your path relative to the point (0, 0), you can apply an appropriate affine transform to the
current drawing context. For example, to draw your shape starting at the point (10, 10), you would call the
CGContextTranslateCTM function and specify 10 for both the horizontal and vertical translation values.
Adjusting the graphics context (as opposed to the points in the path object) is preferred because you can
undo the change more easily by saving and restoring the previous graphics state.
● Update the drawing attributes of the path object. The drawing attributes of your UIBezierPath instance
override the values associated with the graphics context when rendering the path.
Listing 2-5 shows a sample implementation of a drawRect: method that draws an oval in a custom view. The
upper-left corner of the oval’s bounding rectangle is located at the point (50, 50) in the view’s coordinate
system. Because fill operations paint right up to the path boundary, this method fills the path before stroking
it. This prevents the fill color from obscuring half of the stroked line.
Listing 2-5 Drawing a path in a view
- (void)drawRect:(CGRect)rect
{
// Create an oval shape to draw.
UIBezierPath *aPath = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0, 0, 200, 100)];
// Set the render colors.
[[UIColor blackColor] setStroke];
[[UIColor redColor] setFill];
CGContextRef aRef = UIGraphicsGetCurrentContext();
// If you have content to draw after the shape,
// save the current state before changing the transform.
//CGContextSaveGState(aRef);
// Adjust the view's origin temporarily. The oval is
// now drawn relative to the new origin point.
CGContextTranslateCTM(aRef, 50, 50);
Drawing Shapes Using Bézier Paths
Rendering the Contents of a Bézier Path Object
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
37// Adjust the drawing options as needed.
aPath.lineWidth = 5;
// Fill the path before stroking it so that the fill
// color does not obscure the stroked line.
[aPath fill];
[aPath stroke];
// Restore the graphics state before drawing any other content.
//CGContextRestoreGState(aRef);
}
Doing Hit-Detection on a Path
To determine whether a touch event occurred on the filled portion of a path, you can use the containsPoint:
method of UIBezierPath. This method teststhe specified point against all closed subpathsin the path object
and returns YES if it lies on or inside any of those subpaths.
Important: The containsPoint: method and the Core Graphics hit-testing functions operate only on
closed paths. These methods always return NO for hits on open subpaths. If you want to do hit detection
on an open subpath, you must create a copy of your path object and close the open subpaths before testing
points.
If you want to do hit-testing on the stroked portion of the path (instead of the fill area), you must use Core
Graphics. The CGContextPathContainsPoint function lets you test points on either the fill orstroke portion
of the path currently assigned to the graphics context. Listing 2-6 shows a method that tests to see whether
the specified point intersects the specified path. The inFill parameter lets the caller specify whether the
point should be tested against the filled or stroked portion of the path. The path passed in by the caller must
contain one or more closed subpaths for the hit detection to succeed.
Listing 2-6 Testing points against a path object
- (BOOL)containsPoint:(CGPoint)point onPath:(UIBezierPath *)path
inFillArea:(BOOL)inFill
{
CGContextRef context = UIGraphicsGetCurrentContext();
Drawing Shapes Using Bézier Paths
Doing Hit-Detection on a Path
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
38CGPathRef cgPath = path.CGPath;
BOOL isHit = NO;
// Determine the drawing mode to use. Default to
// detecting hits on the stroked portion of the path.
CGPathDrawingMode mode = kCGPathStroke;
if (inFill)
{
// Look for hits in the fill area of the path instead.
if (path.usesEvenOddFillRule)
mode = kCGPathEOFill;
else
mode = kCGPathFill;
}
// Save the graphics state so that the path can be
// removed later.
CGContextSaveGState(context);
CGContextAddPath(context, cgPath);
// Do the hit detection.
isHit = CGContextPathContainsPoint(context, point, mode);
CGContextRestoreGState(context);
return isHit;
}
Drawing Shapes Using Bézier Paths
Doing Hit-Detection on a Path
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
39Most of the time, it is fairly straightforward to display images using standard views. However, there are two
situations in which you may need to do additional work:
●
If you want to display images as part of a custom view, you must draw the images yourself in your view’s
drawRect: method. “Drawing Images” (page 40) explains how.
●
If you want to render images offscreen (to draw later, or to save into a file), you must create a bitmap
image context. To learn more, read “Creating New Images Using Bitmap Graphics Contexts” (page 41).
Drawing Images
For maximum performance, if your image drawing needs can be met using the UIImageView class, you should
use this image object to initialize a UIImageView object. However, if you need to draw an image explicitly,
you can store the image and use it later in your view’s drawRect: method.
The following example shows how to load an image from your app’s bundle.
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage"
ofType:@"png"];
UIImage *myImageObj = [[UIImage alloc] initWithContentsOfFile:imagePath];
// Store the image into a property of type UIImage *
// for use later in the class's drawRect: method.
self.anImage = myImageObj;
To draw the resulting image explicitly in your view’s drawRect: method, you can use any of the drawing
methods available in UIImage. These methods let you specify where in your view you want to draw the image
and therefore do not require you to create and apply a separate transform prior to drawing.
The following snippet draws the image loaded above at the point (10, 10) in the view.
- (void)drawRect:(CGRect)rect
{
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
40
Drawing and Creating Images...
// Draw the image.
[self.anImage drawAtPoint:CGPointMake(10, 10)];
}
Important: If you use the CGContextDrawImage function to draw bitmap images directly, the image
data is inverted along the y axis by default. This is because Quartz images assume a coordinate system with
a lower-left corner origin and positive coordinate axes extending up and to the right from that point.
Although you can apply a transform before drawing, the simpler (and recommended) way to draw Quartz
images is to wrap them in a UIImage object, which compensates for this difference in coordinate spaces
automatically. For more information on creating and drawing images using Core Graphics, see Quartz 2D
Programming Guide .
Creating New Images Using Bitmap Graphics Contexts
Most of the time, when drawing, your goal is to show something onscreen. However, it is sometimes useful
to draw something to an offscreen buffer. For example, you might want to create a thumbnail of an existing
image, draw into a buffer so that you can save it to a file, and so on. To support those needs, you can create
a bitmap image context, use UIKit framework or Core Graphics functions to draw to it, and then obtain an
image object from the context.
In UIKit, the procedure is as follows:
1. Call UIGraphicsBeginImageContextWithOptions to create a bitmap context and push it onto the
graphics stack.
For the first parameter (size), pass a CGSize value to specify the dimensions of the bitmap context (in
points).
For the second parameter (opaque), if your image contains transparency (an alpha channel), pass NO.
Otherwise, pass YES to maximize performance.
For the final parameter (scale), pass 0.0 for a bitmap that is scaled appropriately for the main screen of
the device, or pass the scale factor of your choice.
For example, the following code snippet creates a bitmap that is 200 x 200 pixels. (The number of pixels
is determined by multiplying the size of the image by the scale factor.)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100.0,100.0), NO, 2.0);
Drawing and Creating Images
Creating New Images Using Bitmap Graphics Contexts
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
41Note: You should generally avoid calling the similarly named UIGraphicsBeginImageContext
function (except as a fallback for backwards compatibility), because it always creates images
with a scale factor of 1.0. If the underlying device has a high-resolution screen, an image created
with UIGraphicsBeginImageContext might not appear as smooth when rendered.
2. Use UIKit or Core Graphics routines to draw the content of the image into the newly created graphics
context.
3. Call the UIGraphicsGetImageFromCurrentImageContext function to generate and return a UIImage
object based on what you drew. If desired, you can continue drawing and call this method again to generate
additional images.
4. Call UIGraphicsEndImageContext to pop the context from the graphics stack.
The method in Listing 3-1 gets an image downloaded over the Internet and draws it into an image-based
context, scaled down to the size of an app icon. It then obtains a UIImage object created from the bitmap
data and assigns it to an instance variable. Note that the size of the bitmap (the first parameter of
UIGraphicsBeginImageContextWithOptions) and the size of the drawn content (the size of imageRect)
should match. If the content is larger than the bitmap, a portion of the content will be clipped and not appear
in the resulting image.
Listing 3-1 Drawing a scaled-down image to a bitmap context and obtaining the resulting image
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
if (image != nil && image.size.width != kAppIconHeight && image.size.height
!= kAppIconHeight) {
CGRect imageRect = CGRectMake(0.0, 0.0, kAppIconHeight, kAppIconHeight);
UIGraphicsBeginImageContextWithOptions(itemSize, NO, [UIScreen
mainScreen].scale);
[image drawInRect:imageRect];
self.appRecord.appIcon = UIGraphicsGetImageFromCurrentImageContext(); //
UIImage returned.
UIGraphicsEndImageContext();
} else {
self.appRecord.appIcon = image;
}
self.activeDownload = nil;
[image release];
Drawing and Creating Images
Creating New Images Using Bitmap Graphics Contexts
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
42self.imageConnection = nil;
[delegate appImageDidLoad:self.indexPathInTableView];
}
You can also call Core Graphics functions to draw the contents of the generated bitmap image; the code
fragment in Listing 3-2, which draws a scaled-down image of a PDF page, gives an example of this. Note that
the code flips the graphics context prior to calling CGContextDrawPDFPage to align the drawn image with
default coordinate system of UIKit.
Listing 3-2 Drawing to a bitmap context using Core Graphics functions
// Other code precedes...
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
pdfScale = self.frame.size.width/pageRect.size.width;
pageRect.size = CGSizeMake(pageRect.size.width * pdfScale, pageRect.size.height *
pdfScale);
UIGraphicsBeginImageContextWithOptions(pageRect.size, YES, pdfScale);
CGContextRef context = UIGraphicsGetCurrentContext();
// First fill the background with white.
CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
CGContextFillRect(context,pageRect);
CGContextSaveGState(context);
// Flip the context so that the PDF page is rendered right side up
CGContextTranslateCTM(context, 0.0, pageRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Scale the context so that the PDF page is rendered at the
// correct size for the zoom level.
CGContextScaleCTM(context, pdfScale,pdfScale);
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Drawing and Creating Images
Creating New Images Using Bitmap Graphics Contexts
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
43backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage];
// Other code follows...
If you prefer using Core Graphics entirely for drawing in a bitmap graphics context, you can use the
CGBitmapContextCreate function to create the context and draw your image contents into it. When you
finish drawing, call the CGBitmapContextCreateImage function to obtain a CGImageRef object from the
bitmap context. You can draw the Core Graphics image directly or use this it to initialize a UIImage object.
When finished, call the CGContextRelease function on the graphics context.
Drawing and Creating Images
Creating New Images Using Bitmap Graphics Contexts
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
44The UIKit framework provides a set of functions for generating PDF content using native drawing code. These
functions let you create a graphics context that targets a PDF file or PDF data object. You can then create one
or more PDF pages and draw into those pages using the same UIKit and Core Graphics drawing routines you
use when drawing to the screen. When you are done, what you are left with is a PDF version of what you drew.
The overall drawing process is similar to the process for creating any other image (described in “Drawing and
Creating Images” (page 40)). It consists of the following steps:
1. Create a PDF context and push it onto the graphics stack (as described in “Creating and Configuring the
PDF Context” (page 45)).
2. Create a page (as described in “Drawing PDF Pages” (page 48)).
3. Use UIKit or Core Graphics routines to draw the content of the page.
4. Add links if needed (as described in “Creating Links Within Your PDF Content” (page 50)).
5. Repeat steps 2, 3, and 4 as needed.
6. End the PDF context (as described in “Creating and Configuring the PDF Context” (page 45)) to pop the
context from the graphicsstack and, depending on how the context was created, either write the resulting
data to the specified PDF file or store it into the specified NSMutableData object.
The following sections describe the PDF creation processin more detail using a simple example. For information
about the functions you use to create PDF content, see UIKit Function Reference .
Creating and Configuring the PDF Context
You create a PDF graphics context using either the UIGraphicsBeginPDFContextToData or
UIGraphicsBeginPDFContextToFile function. These functions create the graphics context and associate
it with a destination for the PDF data. For the UIGraphicsBeginPDFContextToData function, the destination
is an NSMutableData object that you provide. And for the UIGraphicsBeginPDFContextToFile function,
the destination is a file in your app’s home directory.
PDF documents organize their content using a page-based structure. This structure imposes two restrictions
on any drawing you do:
● There must be an open page before you issue any drawing commands.
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
45
Generating PDF Content● You must specify the size of each page.
The functions you use to create a PDF graphics context allow you to specify a default page size but they do
not automatically open a page. After creating your context, you must explicitly open a new page using either
the UIGraphicsBeginPDFPage or UIGraphicsBeginPDFPageWithInfo function. And each time you want
to create a new page, you must call one of these functions again to mark the start of the new page. The
UIGraphicsBeginPDFPage function creates a page using the default size, while the
UIGraphicsBeginPDFPageWithInfo function lets you customize the page size and other page attributes.
When you are done drawing, you close the PDF graphics context by calling the UIGraphicsEndPDFContext.
This function closes the last page and writes the PDF content to the file or data object you specified at creation
time. This function also removes the PDF context from the graphics context stack.
Listing 4-1 shows the processing loop used by an app to create a PDF file from the text in a text view. Aside
from three function calls to configure and manage the PDF context, most of the code is related to drawing the
desired content. The textView member variable points to the UITextView object containing the desired
text. The app uses the Core Text framework (and more specifically a CTFramesetterRef data type) to handle
the text layout and management on successive pages. The implementations for the custom
renderPageWithTextRange:andFramesetter: and drawPageNumber: methods are shown in Listing
4-2 (page 48).
Listing 4-1 Creating a new PDF file
- (IBAction)savePDFFile:(id)sender
{
// Prepare the text using a Core Text Framesetter.
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL,
(CFStringRef)textView.text, NULL);
if (currentText) {
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString(currentText);
if (framesetter) {
NSString *pdfFileName = [self getPDFFileName];
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
CFRange currentRange = CFRangeMake(0, 0);
NSInteger currentPage = 0;
Generating PDF Content
Creating and Configuring the PDF Context
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
46BOOL done = NO;
do {
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
// Draw a page number at the bottom of each page.
currentPage++;
[self drawPageNumber:currentPage];
// Render the current page and update the current range to
// point to the beginning of the next page.
currentRange = [self renderPageWithTextRange:currentRange
andFramesetter:framesetter];
// If we're at the end of the text, exit the loop.
if (currentRange.location ==
CFAttributedStringGetLength((CFAttributedStringRef)currentText))
done = YES;
} while (!done);
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
// Release the framewetter.
CFRelease(framesetter);
} else {
NSLog(@"Could not create the framesetter needed to lay out the atrributed
string.");
}
// Release the attributed string.
CFRelease(currentText);
} else {
NSLog(@"Could not create the attributed string for the framesetter");
}
Generating PDF Content
Creating and Configuring the PDF Context
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
47}
Drawing PDF Pages
All PDF drawing must be done in the context of a page. Every PDF document has at least one page and many
may have multiple pages. You specify the start of a new page by calling the UIGraphicsBeginPDFPage or
UIGraphicsBeginPDFPageWithInfo function. These functions close the previous page (if one was open),
create a new page, and prepare it for drawing. The UIGraphicsBeginPDFPage creates the new page using
the default size while the UIGraphicsBeginPDFPageWithInfo function lets you customize the page size
or customize other aspects of the PDF page.
After you create a page, all of your subsequent drawing commands are captured by the PDF graphics context
and translated into PDF commands. You can draw anything you want in the page, including text, vectorshapes,
and images just as you would in your app’s custom views. The drawing commands you issue are captured by
the PDF context and translated into PDF data. Placement of content on the the page is completely up to you
but must take place within the bounding rectangle of the page.
Listing 4-2 shows two custom methods used to draw content inside a PDF page. The
renderPageWithTextRange:andFramesetter: method uses Core Text to create a text frame that fits the
page and then lay out some text inside that frame. After laying out the text, it returns an updated range that
reflectsthe end of the current page and the beginning of the next page. The drawPageNumber: method uses
the NSString drawing capabilities to draw a page number string at the bottom of each PDF page.
Note: This code snippet makes use of the Core Text framework. Be sure to add it to your project.
Listing 4-2 Drawing page-based content
// Use Core Text to draw the text in a frame on the page.
- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange
andFramesetter:(CTFramesetterRef)framesetter
{
// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Put the text matrix into a known state. This ensures
// that no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
Generating PDF Content
Drawing PDF Pages
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
48// Create a path object to enclose the text. Use 72 point
// margins all around the text.
CGRect frameRect = CGRectMake(72, 72, 468, 648);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
// Get the frame that will do the rendering.
// The currentRange variable specifies only the starting point. The framesetter
// lays out as much text as will fit into the frame.
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange,
framePath, NULL);
CGPathRelease(framePath);
// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, 792);
CGContextScaleCTM(currentContext, 1.0, -1.0);
// Draw the frame.
CTFrameDraw(frameRef, currentContext);
// Update the current range based on what was drawn.
currentRange = CTFrameGetVisibleStringRange(frameRef);
currentRange.location += currentRange.length;
currentRange.length = 0;
CFRelease(frameRef);
return currentRange;
}
- (void)drawPageNumber:(NSInteger)pageNum
{
NSString *pageString = [NSString stringWithFormat:@"Page %d", pageNum];
UIFont *theFont = [UIFont systemFontOfSize:12];
Generating PDF Content
Drawing PDF Pages
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
49CGSize maxSize = CGSizeMake(612, 72);
CGSize pageStringSize = [pageString sizeWithFont:theFont
constrainedToSize:maxSize
lineBreakMode:UILineBreakModeClip];
CGRect stringRect = CGRectMake(((612.0 - pageStringSize.width) / 2.0),
720.0 + ((72.0 - pageStringSize.height) / 2.0),
pageStringSize.width,
pageStringSize.height);
[pageString drawInRect:stringRect withFont:theFont];
}
Creating Links Within Your PDF Content
Besides drawing content, you can also include links that take the user to another page in the same PDF file or
to an external URL. To create a single link, you must add a source rectangle and a link destination to your PDF
pages. One of the attributes of the link destination is a string that serves as the unique identifier for that link.
To create a link to a specific destination, you specify the unique identifier for that destination when creating
the source rectangle.
To add a new link destination to your PDF content, you use the
UIGraphicsAddPDFContextDestinationAtPoint function. This function associates a named destination
with a specific point on the current page. When you want to link to that destination point, you use
UIGraphicsSetPDFContextDestinationForRect function to specify the source rectangle for the link.
Generating PDF Content
Creating Links Within Your PDF Content
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
50Figure 4-1 shows the relationship between these two function calls when applied to the pages of your PDF
documents. Tapping on the rectangle surrounding the “see Chapter 1” text takesthe user to the corresponding
destination point, which is located at the top of Chapter 1.
Figure 4-1 Creating a link destination and jump point
Chapter 1
UIGraphicsAddPDFContextDestinationAtPoint
Name: “Chapter_1”
Point: (72, 72)
see Chapter 1
UIGraphicsSetPDFContextDestinationForRect
Name: “Chapter_1”
Rect: (72, 528, 400, 44)
In addition to creating links within a document, you can also use the UIGraphicsSetPDFContextURLForRect
function to create links to content located outside of the document. When using this function to create links,
you specify the target URL and the source rectangle on the current page.
Generating PDF Content
Creating Links Within Your PDF Content
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
51In iOS 4.2 and later, apps can add support for printing content to local AirPrint-capable printers. Although not
all apps need printing support, it is often a useful feature if your app is used for creating content (such as a
word processor or a drawing program), making purchases(printing order confirmations), and other tasks where
the user might reasonably want a permanent record.
This chapter explains how to add printing support to your app. At a high level, your app creates a print job,
providing either an array of ready-to-print images and PDF documents, a single image or PDF document, an
instance of any of the built-in print formatter classes, or a custom page renderer.
Terminology Note: The notion of a print job comes up many times in this chapter. A print job is a
unit of work that includes not just the content to be printed but information used in the printing of
it, such as the identity of the printer, the name of the print job, and the quality and orientation of
printing.
Printing in iOS is Designed to be Simple and Intuitive
To print, users tap a button that is usually in a navigation bar or toolbar that is associated with the view or
selected item the user wants to print. The app then presents a view of printing options. The user selects a
printer and various options and then requests printing. The app is asked to generate printing output from its
content or provide printable data or file URLs. The requested print job is spooled and control returns to the
app. If the destination printer is currently not busy, printing beginsimmediately. If the printer is already printing
or if there are jobs before it in the queue, the print job remains in the iOS print queue until it moves to the top
of queue and is printed.
The Printing User Interface
The first thing a user sees related to printing is a print button. The print button is often a bar-button item on
a navigation bar or a toolbar. The print button should logically apply to the content the app is presenting; if
the user taps the button, the app should print that content. Although the print button can be any custom
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
52
Printingbutton, it is recommended that you use the system item-action button shown in Figure 5-1. This is a
UIBarButtonItem object, specified with the UIBarButtonSystemItemAction constant, that you create
either in Interface Builder or by calling initWithBarButtonSystemItem:target:action:.
Figure 5-1 System item action button—used for printing
When a user taps the print button, a controller object of the app receives the action message. The controller
responds by preparing for printing and displaying the printer-options view. The options always include the
destination printer (selected from a list of discoverable printers), the number of copies, and sometimes the
range of pages to print. If the selected printer is capable of duplex printing, users can choose single-sided or
double-sided output. If users decide not to print, they tap outside the options view (on iPad) or tap the Cancel
button (on iPhone and iPod touch) to dismiss the printer-options view.
The kind of user interface shown depends on the device. On iPad, the UIKit framework displays a popover view
containing the options, as shown in Figure 5-2. An app can animate this view to appear from the print button
or from an arbitrary area of the app’s user interface.
Figure 5-2 Printer-options popover view (iPad)
Printing
Printing in iOS is Designed to be Simple and Intuitive
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
53On iPhone and iPod touch devices, UIKit displays a sheet of printing options that an app can animate to slide
up from the bottom of the screen, as shown in Figure 5-3.
Figure 5-3 Printer-options sheet (iPhone)
Printing
Printing in iOS is Designed to be Simple and Intuitive
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
54Once a print job has been submitted and is either printing or waiting in the print queue, users can check on
itsstatus by double-tapping the Home button to accessthe Print Center in the multitasking UI. The Print Center
(shown in Figure 5-4) is a background system app that shows the order of jobs in the print queue, including
those that are currently printing. It is only available while a print job is in progress.
Figure 5-4 Print Center
Printing
Printing in iOS is Designed to be Simple and Intuitive
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
55Users can tap a print job in the Print Center to get detailed information about it (Figure 5-5) and cancel jobs
that are printing or waiting in the queue.
Figure 5-5 Print Center: detail of print job
How Printing Works in iOS
An app uses the UIKit printing API to assemble the elements of a print job, including the content to print and
information related to the print job. It then presents the printer-options view described in “The Printing User
Interface” (page 52). The user makes his or her choices and then taps Print. In some cases, the UIKit framework
then asks the app to draw the content to be printed; UIKit records what the app draws as PDF data. UIKit then
hands off the printing data to the printing subsystem.
The printing system does a few things. As UIKit passes the print data to the printing subsystem, it writes this
data to storage (that is, it spools the data). It also captures information about the print job. The printing system
manages the combined print data and metadata for each print job in a first-in-first-out print queue. Multiple
apps on a device can submit multiple print jobs to the printing subsystem, and all of these are placed in the
print queue. Each device has one queue for all print jobs regardless of originating app or destination printer.
Printing
Printing in iOS is Designed to be Simple and Intuitive
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
56When a print job risesto the top of the queue, the system printing daemon (printd) considersthe destination
printer's requirements and, if necessary, converts the print data to a form that is usable by the printer. The
printing system reports error conditions such as "Out of Paper" to the user as alerts. It also reports the progress
of print jobs programmatically to the Print Center, which displays information such as “page 2 of 5” for a print
job.
This overall architecture is shown in Figure 5-6.
Figure 5-6 Printing architecture
Application
UIKit
Print job
Print job
Print job
Print job
Printing subsystem
Print Queue
printd
Printer
The UIKit Printing API
The UIKit printing API includes eight classes and one formal protocol. Objects of these classes and the delegate
implementing the protocol have runtime relationships as depicted in Figure 5-7.
Figure 5-7 Relationships of UIKit printing objects
UIPrintFormatter
subclass
UIPrintPageRenderer
subclass
UIPrintInteractionController
printInfo
delegate
printPaper
printingItems
printingItem
printPageRenderer
printFormatter
UIPrintPaper
paperSize
printableRect
elements.
If your breaks are specifically intended as line breaks and not paragraph breaks, then you should typically use
NSLineSeparatorCharacter. Otherwise, you may use \n, \r, or \r\n depending on what other software
is likely to process your text. The default choice for Cocoa is usually \n.
Separating a String “by Paragraph”
A common approach to separating a string “by paragraph” is simply to use:
NSArray *arr = [myString componentsSeparatedByString:@"\n"];
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
28
Paragraphs and Line BreaksThis, however, ignores the fact that there are a number of other ways in which a paragraph or line break may
be represented in a string—\r, \r\n, or Unicode separators. Instead you can use methods—such as
lineRangeForRange: or getParagraphStart:end:contentsEnd:forRange:—that take into account
the variety of possible line terminations, as illustrated in the following example.
NSString *string = /* assume this exists */;
unsigned length = [string length];
unsigned paraStart = 0, paraEnd = 0, contentsEnd = 0;
NSMutableArray *array = [NSMutableArray array];
NSRange currentRange;
while (paraEnd < length) {
[string getParagraphStart:¶Start end:¶End
contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];
currentRange = NSMakeRange(paraStart, contentsEnd - paraStart);
[array addObject:[string substringWithRange:currentRange]];
}
Paragraphs and Line Breaks
Separating a String “by Paragraph”
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
29It's common to think of a string as a sequence of characters, but when working with NSString objects, or
with Unicode strings in general, in most cases it is better to deal with substrings rather than with individual
characters. The reason for this is that what the user perceives as a character in text may in many cases be
represented by multiple characters in the string. NSString has a large inventory of methods for properly
handling Unicode strings, which in general make Unicode compliance easy, but there are a few precautions
you should observe.
NSString objects are conceptually UTF-16 with platform endianness. That doesn't necessarily imply anything
about their internalstorage mechanism; what it meansisthat NSString lengths, character indexes, and ranges
are expressed in terms of UTF-16 units, and that the term “character” in NSString method names refers to
16-bit platform-endian UTF-16 units. This is a common convention for string objects. In most cases, clients
don't need to be overly concerned with this; aslong as you are dealing with substrings, the precise interpretation
of the range indexes is not necessarily significant.
The vast majority of Unicode code points used for writing living languages are represented by single UTF-16
units. However, some less common Unicode code points are represented in UTF-16 by surrogate pairs. A
surrogate pair is a sequence of two UTF-16 units, taken from specific reserved ranges, that together represent
a single Unicode code point. CFString has functions for converting between surrogate pairs and the UTF-32
representation of the corresponding Unicode code point. When dealing with NSString objects, one constraint
is that substring boundaries usually should not separate the two halves of a surrogate pair. This is generally
automatic for rangesreturned from most Cocoa methods, but if you are constructing substring ranges yourself
you should keep this in mind. However, this is not the only constraint you should consider.
In many writing systems, a single character may be composed of a base letter plus an accent or other decoration.
The number of possible letters and accents precludes Unicode from representing each combination as a single
code point, so in general such combinations are represented by a base character followed by one or more
combining marks. For compatibility reasons, Unicode does have single code points for a number of the most
common combinations; these are referred to as precomposed forms, and Unicode normalization transformations
can be used to convert between precomposed and decomposed representations. However, even if a string is
fully precomposed, there are still many combinations that must be represented using a base character and
combining marks. For most text processing, substring ranges should be arranged so that their boundaries do
not separate a base character from its associated combining marks.
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
30
Characters and Grapheme ClustersIn addition, there are writing systems in which characters represent a combination of parts that are more
complicated than accent marks. In Korean, for example, a single Hangul syllable can be composed of two or
three subparts known as jamo. In the Indic and Indic-influenced writing systems common throughout South
and Southeast Asia, single written characters often represent combinations of consonants, vowels, and marks
such as viramas, and the Unicode representations of these writing systems often use code points for these
individual parts,so that a single character may be composed of multiple code points. For most text processing,
substring ranges should also be arranged so that their boundaries do not separate the jamo in a single Hangul
syllable, or the components of an Indic consonant cluster.
In general, these combinations—surrogate pairs, base characters plus combining marks, Hangul jamo, and
Indic consonant clusters—are referred to as grapheme clusters. In order to take them into account, you can
use NSString’s rangeOfComposedCharacterSequencesForRange: or
rangeOfComposedCharacterSequenceAtIndex: methods, or
CFStringGetRangeOfComposedCharactersAtIndex. These can be used to adjuststring indexes orsubstring
ranges so that they fall on grapheme cluster boundaries, taking into account all of the constraints mentioned
above. These methods should be the default choice for programmatically determining the boundaries of
user-perceived characters.:
In some cases, Unicode algorithms deal with multiple charactersin waysthat go beyond even grapheme cluster
boundaries. Unicode casing algorithms may convert a single character into multiple characters when going
from lowercase to uppercase; for example, the standard uppercase equivalent of the German character “ß” is
the two-letter sequence “SS”. Localized collation algorithms in many languages consider multiple-character
sequences as single units; for example, the sequence “ch” is treated as a single letter for sorting purposes in
some European languages. In order to deal properly with cases like these, it is important to use standard
NSString methods for such operations as casing, sorting, and searching, and to use them on the entire string
to which they are to apply. Use NSString methods such as lowercaseString, uppercaseString,
capitalizedString, compare: and its variants, rangeOfString: and its variants, and
rangeOfCharacterFromSet: and its variants, or their CFString equivalents. These all take into account the
complexities of Unicode string processing, and the searching and sorting methods in particular have many
options to control the types of equivalences they are to recognize.
In some less common cases, it may be necessary to tailor the definition of grapheme clusters to a particular
need. The issues involved in determining and tailoring grapheme cluster boundaries are covered in detail in
Unicode Standard Annex #29, which gives a number of examples and some algorithms. The Unicode standard
in general is the best source for information about Unicode algorithms and the considerations involved in
processing Unicode strings.
If you are interested in grapheme cluster boundaries from the point of view of cursor movement and insertion
point positioning, and you are using the Cocoa text system, you should know that on OS X v10.5 and later,
NSLayoutManager has API support for determining insertion point positions within a line of text as it is laid
Characters and Grapheme Clusters
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
31out. Note that insertion point boundaries are not identical to glyph boundaries; a ligature glyph in some cases,
such as an “fi” ligature in Latin script, may require an internal insertion point on a user-perceived character
boundary. See Cocoa Text Architecture Guide for more information.
Characters and Grapheme Clusters
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
32An NSCharacterSet object represents a set of Unicode characters. NSString and NSScanner objects use
NSCharacterSet objects to group characters together for searching operations, so that they can find any of
a particular set of characters during a search.
Character Set Basics
A character set object represents a set of Unicode characters. Character sets are represented by instances of a
class cluster. The cluster’s two public classes, NSCharacterSet and NSMutableCharacterSet, declare the
programmatic interface for immutable and mutable character sets, respectively. An immutable character set is
defined when it is created and subsequently cannot be changed. A mutable character set can be changed
after it’s created.
A character set object doesn’t perform any tasks; it simply holds a set of character values to limit operations
on strings. The NSString and NSScanner classes define methods that take NSCharacterSet objects as
argumentsto find any ofseveral characters. For example, this code excerpt findsthe range of the first uppercase
letter in myString:.
NSString *myString = @"some text in an NSString...";
NSCharacterSet *characterSet = [NSCharacterSet uppercaseLetterCharacterSet];
NSRange letterRange = [myString rangeOfCharacterFromSet:characterSet];
After this fragment executes, letterRange.location is equal to the index of the first “N” in “NSString” after
rangeOfCharacterFromSet: isinvoked. If the first letter of the string were “S”, then letterRange.location
would be 0.
Creating Character Sets
NSCharacterSet defines class methodsthat return commonly used charactersets,such asletters(uppercase
or lowercase), decimal digits, whitespace, and so on. These “standard” character sets are always immutable,
even if created by sending a message to NSMutableCharacterSet. See “Standard Character Sets and Unicode
Definitions” (page 35) for more information on standard character sets.
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
33
Character SetsYou can use a standard character set as a starting point for building a custom set by making a mutable copy
of it and changing that. (You can also start from scratch by creating a mutable character set with alloc and
init and adding characters to it.) For example, this fragment creates a character set containing letters, digits,
and basic punctuation:
NSMutableCharacterSet *workingSet = [[NSCharacterSet alphanumericCharacterSet]
mutableCopy];
[workingSet addCharactersInString:@";:,."];
NSCharacterSet *finalCharacterSet = [workingSet copy];
To define a custom character set using Unicode code points, use code similar to the following fragment (which
creates a character set including the form feed and line separator characters):
UniChar chars[] = {0x000C, 0x2028};
NSString *string = [[NSString alloc] initWithCharacters:chars
length:sizeof(chars) / sizeof(UniChar)];
NSCharacterSet *characterSet = [NSCharacterSet
characterSetWithCharactersInString:string];
Performance considerations
Because character sets often participate in performance-critical code, you should be aware of the aspects of
their use that can affect the performance of your application. Mutable character sets are generally much more
expensive than immutable character sets. They consume more memory and are costly to invert (an operation
often performed in scanning a string). Because of this, you should follow these guidelines:
● Create as few mutable character sets as possible.
● Cache character sets (in a global dictionary, perhaps) instead of continually recreating them.
● When creating a custom set that doesn’t need to change after creation, make an immutable copy of the
final character set for actual use, and dispose of the working mutable character set. Alternatively, create
a character set file as described in “Creating a character set file” (page 35) and store it in your application’s
main bundle.
● Similarly, avoid archiving characterset objects;store them in characterset filesinstead. Archiving can result
in a character set being duplicated in different archive files, resulting in wasted disk space and duplicates
in memory for each separate archive read.
Character Sets
Performance considerations
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
34Creating a character set file
If your application frequently uses a custom character set, you should save its definition in a resource file and
load that instead of explicitly adding individual characters each time you need to create the set. You can save
a character set by getting its bitmap representation (an NSData object) and saving that object to a file:
NSData *charSetRep = [finalCharacterSet bitmapRepresentation];
NSURL *dataURL = <#URL for character set#>;
NSError *error;
BOOL result = [charSetRep writeToURL:dataURL options:NSDataWritingAtomic
error:&error];
By convention, characterset filenames use the extension .bitmap. If you intend for othersto use your character
set files, you should follow this convention. To read a character set file with a .bitmap extension, simply use
the characterSetWithContentsOfFile: method.
Standard Character Sets and Unicode Definitions
The standard character sets, such as that returned by letterCharacterSet, are formally defined in terms
of the normative and informative categories established by the Unicode standard, such as Uppercase Letter,
Combining Mark, and so on. The formal definition of a standard character set is in most cases given as one or
more of the categories defined in the standard. For example, the set returned by
lowercaseLetterCharacterSet include all characters in normative category Lowercase Letters, while the
set returned by letterCharacterSet includes the characters in all of the Letter categories.
Note that the definitions of the categoriesthemselves may change with new versions of the Unicode standard.
You can download the files that define category membership from http://www.unicode.org/.
Character Sets
Creating a character set file
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
35An NSScanner object scans the characters of an NSString object, typically interpreting the characters and
converting them into number and string values. You assign the scanner’s string on creation, and the scanner
progresses through the characters of that string from beginning to end as you request items.
Creating a Scanner
NSScanner is a class cluster with a single public class, NSScanner. Generally, you instantiate a scanner object
by invoking the class method scannerWithString: or localizedScannerWithString:. Either method
returns a scanner object initialized with the string you pass to it. The newly created scanner starts at the
beginning of its string. You scan components using the scan... methods such as scanInt:, scanDouble:,
and scanString:intoString:. If you are scanning multiple lines, you typically create a while loop that
continues until the scanner is at the end of the string, as illustrated in the following code fragment:
float aFloat;
NSScanner *theScanner = [NSScanner scannerWithString:aString];
while ([theScanner isAtEnd] == NO) {
[theScanner scanFloat:&aFloat];
// implementation continues...
}
You can configure a scanner to consider or ignore case using the setCaseSensitive: method. By default
a scanner ignores case.
Using a Scanner
Scan operationsstart at the scan location and advance the scanner to just past the last character in the scanned
value representation (if any). For example, after scanning an integer from the string “137 small cases of
bananas”, a scanner’s location will be 3, indicating the space immediately after the number. Often you need
to advance the scan location to skip characters in which you are not interested. You can change the implicit
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
36
Scannersscan location with the setScanLocation: method to skip ahead a certain number of characters (you can
also use the method to rescan a portion of the string after an error). Typically, however, you either want to
skip characters from a particular character set, scan past a specific string, or scan up to a specific string.
You can configure a scanner to skip a set of characters with the setCharactersToBeSkipped: method. A
scanner ignores characters to be skipped at the beginning of any scan operation. Once it finds a scannable
character, however, it includes all characters matching the request. Scanners skip whitespace and newline
characters by default. Note that case is always considered with regard to characters to be skipped. To skip all
English vowels, for example, you must set the characters to be skipped to those in the string “AEIOUaeiou”.
If you want to read content from the current location up to a particular string, you can use
scanUpToString:intoString: (you can pass NULL as the second argument if you simply want to skip the
intervening characters). For example, given the following string:
137 small cases of bananas
you can find the type of container and number of containers using scanUpToString:intoString: asshown
in the following example.
NSString *bananas = @"137 small cases of bananas";
NSString *separatorString = @" of";
NSScanner *aScanner = [NSScanner scannerWithString:bananas];
NSInteger anInteger;
[aScanner scanInteger:&anInteger];
NSString *container;
[aScanner scanUpToString:separatorString intoString:&container];
It is important to note that the search string (separatorString) is " of". By default a scanner ignores
whitespace, so the space character after the integer is ignored. Once the scanner begins to accumulate
characters, however, all characters are added to the output string until the search string is reached. Thus if the
search string is "of" (no space before), the first value of container is “small cases ” (includes the space
following); if the search string is " of" (with a space before), the first value of container is “small cases” (no
space following).
Scanners
Using a Scanner
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
37After scanning up to a given string, the scan location is the beginning of that string. If you want to scan past
thatstring, you must therefore firstscan in the string you scanned up to. The following code fragment illustrates
how to skip past the search string in the previous example and determine the type of product in the container.
Note the use of substringFromIndex: to in effect scan up to the end of a string.
[aScanner scanString:separatorString intoString:NULL];
NSString *product;
product = [[aScanner string] substringFromIndex:[aScanner scanLocation]];
// could also use:
// product = [bananas substringFromIndex:[aScanner scanLocation]];
Example
Suppose you have a string containing lines such as:
Product: Acme Potato Peeler; Cost: 0.98 73
Product: Chef Pierre Pasta Fork; Cost: 0.75 19
Product: Chef Pierre Colander; Cost: 1.27 2
The following example uses alternating scan operationsto extract the product names and costs(costs are read
as a float forsimplicity’ssake),skipping the expected substrings“Product:” and “Cost:”, as well asthe semicolon.
Note that because a scanner skips whitespace and newlines by default, the loop does no special processing
for them (in particular there is no need to do additional whitespace processing to retrieve the final integer).
NSString *string = @"Product: Acme Potato Peeler; Cost: 0.98 73\n\
Product: Chef Pierre Pasta Fork; Cost: 0.75 19\n\
Product: Chef Pierre Colander; Cost: 1.27 2\n";
NSCharacterSet *semicolonSet;
NSScanner *theScanner;
NSString *PRODUCT = @"Product:";
NSString *COST = @"Cost:";
NSString *productName;
float productCost;
Scanners
Example
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
38NSInteger productSold;
semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@";"];
theScanner = [NSScanner scannerWithString:string];
while ([theScanner isAtEnd] == NO)
{
if ([theScanner scanString:PRODUCT intoString:NULL] &&
[theScanner scanUpToCharactersFromSet:semicolonSet
intoString:&productName] &&
[theScanner scanString:@";" intoString:NULL] &&
[theScanner scanString:COST intoString:NULL] &&
[theScanner scanFloat:&productCost] &&
[theScanner scanInteger:&productSold])
{
NSLog(@"Sales of %@: $%1.2f", productName, productCost * productSold);
}
}
Localization
A scanner bases some of its scanning behavior on a locale, which specifies a language and conventions for
value representations. NSScanner uses only the locale’s definition for the decimal separator (given by the key
named NSDecimalSeparator). You can create a scanner with the user’s locale by using
localizedScannerWithString:, or set the locale explicitly using setLocale:. If you use a method that
doesn’t specify a locale, the scanner assumes the default locale values.
Scanners
Localization
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
39NSString provides a rich set of methodsfor manipulating strings asfile-system paths. You can extract a path’s
directory, filename, and extension, expand a tilde expression (such as “~me”) or create one for the user’s home
directory, and clean up paths containing symbolic links, redundant slashes, and references to “.” (current
directory) and “..” (parent directory).
Note: Where possible, you should use instances of NSURL to represent paths—the operating system
deals with URLs more efficiently than with string representations of paths.
Representing a Path
NSString represents paths generically with ‘/’ asthe path separator and ‘.’ asthe extension separator. Methods
that accept strings as path arguments convert these generic representations to the proper system-specific
form as needed. On systems with an implicit root directory, absolute paths begin with a path separator or with
a tilde expression (“~/...” or “~user/...”). Where a device must be specified, you can do that
yourself—introducing a system dependency—or allow the string object to add a default device.
You can create a standardized representation of a path using stringByStandardizingPath. This performs
a number of tasks including:
● Expansion of an initial tilde expression;
● Reduction of empty components and references to the current directory (“//” and “/./”) to single path
separators;
●
In absolute paths, resolution of references to the parent directory (“..”) to the real parent directory;
for example:
NSString *path = @"/usr/bin/./grep";
NSString *standardizedPath = [path stringByStandardizingPath];
// standardizedPath: /usr/bin/grep
path = @"~me";
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
40
String Representations of File PathsstandardizedPath = [path stringByStandardizingPath];
// standardizedPath (assuming conventional naming scheme): /Users/Me
path = @"/usr/include/objc/..";
standardizedPath = [path stringByStandardizingPath];
// standardizedPath: /usr/include
path = @"/private/usr/include";
standardizedPath = [path stringByStandardizingPath];
// standardizedPath: /usr/include
User Directories
The following examples illustrate how you can use NSString’s path utilities and other Cocoa functions to get
the user directories.
// Assuming that users’ home directories are stored in /Users
NSString *meHome = [@"~me" stringByExpandingTildeInPath];
// meHome = @"/Users/me"
NSString *mePublic = [@"~me/Public" stringByExpandingTildeInPath];
// mePublic = @"/Users/me/Public"
You can find the home directory for the current user and for a given user with NSHomeDirectory and
NSHomeDirectoryForUser respectively:
NSString *currentUserHomeDirectory = NSHomeDirectory();
NSString *meHomeDirectory = NSHomeDirectoryForUser(@"me");
Note that you should typically use the function NSSearchPathForDirectoriesInDomains to locate standard
directories for the current user. For example, instead of:
NSString *documentsDirectory =
[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
String Representations of File Paths
User Directories
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
41you should use:
NSString *documentsDirectory;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if ([paths count] > 0) {
documentsDirectory = [paths objectAtIndex:0];
}
Path Components
NSString provides a rich set of methods for manipulating strings as file-system paths, for example:
Interprets the receiver as a path and returns the
receiver’s extension, if any.
pathExtension
Returns a new string made by deleting the
extension (if any, and only the last) from the
receiver.
stringByDeletingPathExtension
Returns a new string made by deleting the last
path component from the receiver, along with any
final path separator.
stringByDeletingLastPathComponent
Using these and related methods described in NSString Class Reference , you can extract a path’s directory,
filename, and extension, as illustrated by the following examples.
NSString *documentPath = @"~me/Public/Demo/readme.txt";
NSString *documentDirectory = [documentPath stringByDeletingLastPathComponent];
// documentDirectory = @"~me/Public/Demo"
NSString *documentFilename = [documentPath lastPathComponent];
// documentFilename = @"readme.txt"
NSString *documentExtension = [documentPath pathExtension];
// documentExtension = @"txt"
String Representations of File Paths
Path Components
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
42File Name Completion
You can find possible expansions of file names using
completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:. For example, given
a directory ~/Demo that contains the following files:
ReadMe.txt readme.html readme.rtf recondite.txt test.txt
you can find all possible completions for the path ~/Demo/r as follows:
NSString *partialPath = @"~/Demo/r";
NSString *longestCompletion;
NSArray *outputArray;
unsigned allMatches = [partialPath completePathIntoString:&longestCompletion
caseSensitive:NO
matchesIntoArray:&outputArray
filterTypes:NULL];
// allMatches = 3
// longestCompletion = @"~/Demo/re"
// outputArray = (@"~/Demo/readme.html", "~/Demo/readme.rtf", "~/Demo/recondite.txt")
You can find possible completions for the path ~/Demo/r that have an extension “.txt” or “.rtf” as follows:
NSArray *filterTypes = @[@"txt", @"rtf"];
unsigned textMatches = [partialPath completePathIntoString:&outputName
caseSensitive:NO
matchesIntoArray:&outputArray
filterTypes:filterTypes];
// allMatches = 2
// longestCompletion = @"~/Demo/re"
// outputArray = (@"~/Demo/readme.rtf", @"~/Demo/recondite.txt")
String Representations of File Paths
File Name Completion
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
43You can draw string objects directly in a focused NSView using methods such as
drawAtPoint:withAttributes: (to draw a string with multiple attributes, such as multiple text fonts, you
must use an NSAttributedString object). These methods are described briefly in “Text” in Cocoa Drawing
Guide .
The simple methods, however, are designed for drawing small amounts of text or text that is only drawn
rarely—they create and dispose of various supporting objects every time you call them. To draw strings
repeatedly, it is more efficient to use NSLayoutManager, as described in “Drawing Strings”. For an overview of
the Cocoa text system, of which NSLayoutManager is a part, see Cocoa Text Architecture Guide .
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
44
Drawing StringsThis table describes the changes to String Programming Guide .
Date Notes
2012-07-17 Updated code snippets to adopt new Objective-C features.
Corrected string constant character set to UTF-8. Added guidance about
using localizedStandardCompare: for Finder-like sorting. Added caveat
to avoid using %s with RTL languages. Revised "String Format Specifiers"
article.
2012-06-11
2009-10-15 Added links to Cocoa Core Competencies.
Added new aricle on character clusters; updated list of string format
specifiers.
2008-10-15
2007-10-18 Corrected minor typographical errors.
Added notes regarding NSInteger and NSUInteger to "String Format
Specifiers".
2007-07-10
2007-03-06 Corrected minor typographical errors.
2007-02-08 Corrected sentence fragments and improved the example in "Scanners."
2006-12-05 Added code samples to illustrate searching and path manipulation.
2006-11-07 Made minor revisions to "Scanners" article.
2006-10-03 Added links to path manipulation methods.
2006-06-28 Corrected typographical errors.
Added a new article, "Reading Strings From and Writing Strings To Files
and URLs"; significantly updated "Creating and Converting Strings."
2006-05-23
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
45
Document Revision HistoryDate Notes
Included “Creating a Character Set” into “Character Sets” (page 33).
Changed title from "Strings" to conform to reference consistency
guidelines.
2006-01-10
Added “Formatting String Objects” (page 13) article. Added Data
Formatting and the Core Foundation Strings programming topics to the
introduction.
2004-06-28
Added information about custom Unicode character sets and retrieved
missing code fragments in “Creating a Character Set”. Added information
and cross-reference to “Drawing Strings” (page 44). Rewrote introduction
and added an index.
2004-02-06
Added NSNumericSearch description to “Searching, Comparing, and
Sorting Strings” (page 22).
2003-09-09
2003-03-17 Reinstated the sample code that was missing from “Scanners” (page 36).
Updated “Creating and Converting String Objects” (page 8) to
recommend the use of UTF8 encoding, and noted the pending deprecation
of the cString... methods.
2003-01-17
2002-11-12 Revision history was added to existing topic.
Document Revision History
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
46A
alloc method 34
archiving
character set objects 34
ASCII character encoding
converting string object contents 8
availableStringEncodings method 8
C
C strings
Cocoa string objects and 7
creating and converting 11
character encodings
string manipulation and 8
character sets
custom 34
example code 34
guidelines for use 34
mutable and immutable 33
saving to a file 35
standard 33, 35
characterAtIndex: method 7
characterSetWithContentsOfFile: method 35
compare: method 22
compare:options: method 22, 24
compare:options:range: method 22
comparing strings 22–23
comparison methods for strings 22
componentsSeparatedByString: method 11
current directories
resolving references to 40
D
dataUsingEncoding: method 11, 12
defaultCStringEncoding method 8
description method 13
descriptionWithLocale: method 13
directories
manipulating strings as paths 40, 42
E
encodings, character
string manipulation and 8
EUC character encoding 8
F
file-system paths and strings 42
format strings 13
G
getCharacters:length: method 12
I
init method
for mutable character sets 34
initWithData:encoding: method 8, 11, 12
initWithFormat: method 10
initWithFormat:locale: method 12
ISO Latin 1 character encoding 8
L
length method
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
47
Indexfor string objects 7
letterCharacterSet method 35
localization
scanning strings and 39
value formatting and 13
localizedScannerWithString: method 36, 39
localizedStringWithFormat: method 9, 12
lowercaseLetterCharacterSet method 35
M
myString: method 33
N
NSCharacterSet class 33
NSLayoutManager class 44
NSMutableCharacterSet class 33
NSMutableString class 7, 8
NSScanner class 23, 36–38
NSString class
creating string objects from 8
described 7
methods for representing file-system paths 40
scanners and 36
NSView class 44
P
parent directories
resolving references to 40
paths and strings 42
primitive methods
of NSString 7
printf function
NSString and 13
R
rangeOfCharacterFromSet: method 22, 33
rangeOfCharacterFromSet:options: method 22
rangeOfCharacterFromSet:options:range:
method 22
rangeOfComposedCharacterSequenceAtIndex:
method 23
rangeOfString: method 22
rangeOfString:options: method 22
rangeOfString:options:range: method 22
S
scan... methods 36
scanners 36, 38
instantiating 36
operation of 36
sample code 38
scannerWithString: method 36
scanUpToString:intoString: method 37
search methods
for strings 22
setCaseSensitive: method 36
setCharactersToBeSkipped: method 37
setLocale: method 39
setScanLocation: method 37
Shift-JIS character encoding 8
standard character sets 33, 35
string objects
combining and extracting 10
comparison methods 22
creating and converting 8–12
described 7
drawing 44
searching and comparing 22–23
stringByAppendingFormat: method 10, 12
stringByAppendingString: method 10, 12
stringWithCharacters:length: method 12
stringWithContentsOfFile: method 21
stringWithFormat: method 10
stringWithUTF8String: method 12
substringFromIndex: method 11
substringToIndex: method 11
Index
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
48substringWithRange: method 11
U
Unicode
characters in string objects 8
code points used to define character sets 34
in string objects 7
NSCharacterSet and 33
standard character sets 35
string comparison standard 22
UTF8 character encoding 11
UTF8String method 11, 12
V
value formatting
string conversion and 13
W
writeToFile:atomically: method 21
Index
2012-07-17 | © 1997, 2012 Apple Inc. All Rights Reserved.
49Apple Inc.
© 1997, 2012 Apple Inc.
All rights reserved.
No part of this publication may be reproduced,
stored in a retrievalsystem, or transmitted, in any
form or by any means, mechanical, electronic,
photocopying, recording, or otherwise, without
prior written permission of Apple Inc., with the
following exceptions: Any person is hereby
authorized to store documentation on a single
computer for personal use only and to print
copies of documentation for personal use
provided that the documentation contains
Apple’s copyright notice.
No licenses, express or implied, are granted with
respect to any of the technology described in this
document. Apple retains all intellectual property
rights associated with the technology described
in this document. This document is intended to
assist application developers to develop
applications only for Apple-labeled computers.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010
Apple, the Apple logo, Cocoa, Finder, Mac,
Macintosh, Objective-C, OS X, and Safari are
trademarks of Apple Inc., registered in the U.S.
and other countries.
Even though Apple has reviewed this document,
APPLE MAKES NO WARRANTY OR REPRESENTATION,
EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS
DOCUMENT, ITS QUALITY, ACCURACY,
MERCHANTABILITY, OR FITNESS FOR A PARTICULAR
PURPOSE.ASARESULT, THISDOCUMENT IS PROVIDED
“AS IS,” AND YOU, THE READER, ARE ASSUMING THE
ENTIRE RISK AS TO ITS QUALITY AND ACCURACY.
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL,OR CONSEQUENTIAL
DAMAGES RESULTING FROM ANY DEFECT OR
INACCURACY IN THIS DOCUMENT, even if advised of
the possibility of such damages.
THE WARRANTY AND REMEDIES SET FORTH ABOVE
ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL
OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer,
agent, or employee is authorized to make any
modification, extension, or addition to this warranty.
Some states do not allow the exclusion or limitation
of implied warranties or liability for incidental or
consequential damages, so the above limitation or
exclusion may not apply to you. This warranty gives
you specific legal rights, and you may also have other
rights which vary from state to state.
Apple AirPort Networks2
1 Contents
Chapter 1 3 Getting Started
5 Configuring an Apple Wireless Device for Internet Access Using AirPort Utility
6 Extending the Range of Your AirPort Network
6 Sharing a USB Hard Disk Connected to an AirPort Extreme Base Station or Time Capsule
6 Printing with an Apple Wireless Device
6 Sharing Your Computer’s Internet Connection
Chapter 2 9 AirPort Security
9 Security for AirPort Networks at Home
10 Security for AirPort Networks in Businesses and Classrooms
11 Wi-Fi Protected Access (WPA) and WPA2
Chapter 3 14 AirPort Network Designs
15 Using AirPort Utility
17 Setting Up the AirPort Extreme Network
24 Configuring and Sharing Internet Access
41 Setting Advanced Options
43 Extending the Range of an 802.11n Network
45 Keeping Your Network Secure
49 Directing Network Traffic to a Specific Computer on Your Network (Port Mapping)
51 Logging
52 Using Back to My Mac on your Wireless Network
53 Setting up IPv6
54 Sharing and Securing USB Hard Disks on Your Network
55 Using a Time Capsule in Your Network
55 Connecting a USB Printer to an Apple Wireless Device
56 Adding a Wireless Client to Your 802.11n Network
57 Solving Problems
Chapter 4 59 Behind the Scenes
59 Basic Networking
63 Items That Can Cause Interference with AirPort
Glossary 641
3
1 Getting Started
AirPort offers the easiest way to provide wireless Internet
access and networking anywhere in the home, classroom,
or office.
AirPort is based on the latest Institute of Electrical and Electronics Engineers (IEEE)
802.11n draft specification and provides fast and reliable wireless networking in the
home, classroom, or small office. You can enjoy data transfer rates of up to five times
faster than data rates provided by the 802.11g standard and more than twice the
network range.
The new AirPort Extreme Base Station and the new Time Capsule are based on
simultaneous dual-band technology, so they work in both the 2.4 gigahertz (GHz)
or 5 GHz spectrum at the same time. And they are 100 percent backward-compatible,
so Mac computers and PCs that use 802.11a, 802.11b, 802.11g, or IEEE draft specification
802.11n wireless cards can connect to an AirPort wireless network. They also work
flawlessly with the AirPort Express for wireless music streaming and more. The
AirPort Extreme Base Station and Time Capsule have three additional 10/100/1000BaseT Gigabit Ethernet ports, so you don’t need to include another router in your network.
To set up an AirPort Extreme Base Station, an AirPort Express, or a Time Capsule, you
use AirPort Utility, the easy-to-use setup and management application. AirPort Utility
has a simple user experience, with all software controls accessible from the same
application. It provides better management of several Apple wireless devices, with
client-monitoring features and logging.
If you’re using AirPort Utility version 5.4 or later, you can set up a guest network, in
both the 2.4 GHz and 5 GHz bands, so that guests can connect to the Internet using
your AirPort network, while you keep your private network secure. You can also choose
to set up guest accounts that expire, to grant temporary access to your network; you
no longer need to give your network password to visitors in your home or office.
You can even set up accounts with time constraints for the best in parental controls.
AirPort Utility supports IPv6 and Bonjour, so you can “advertise” network services such
as printing and sharing a hard disk over the Wide Area Network (WAN) port.4 Chapter 1 Getting Started
Note: When the features discussed in this document apply to the AirPort Extreme Base
Station, AirPort Express, and Time Capsule, the devices are referred to collectively as
Apple wireless devices.
With an AirPort Extreme Base Station or a Time Capsule, you can connect a USB hard
disk so that everyone on the network can back up, store, and share files. Every
Time Capsule includes an internal AirPort disk, so you don’t need to connect an
external one. If you want, you can connect additional USB disks to the USB port on
your Time Capsule. You can also connect a USB printer to the USB port on any
Apple wireless device, so that everyone on the network can access the printer or hub.
All Apple wireless devices provide strong, wireless security. They offer a built-in firewall
and support industry-standard encryption technologies. Yet the simple setup utility
and powerful access controls make it easy for authorized users to connect to the
AirPort network they create.
You can use an Apple wireless device to provide wireless Internet access and share a
single Internet connection among several computers in the following ways:
 Set up the device to act as a router and provide Internet Protocol (IP) addresses to
computers on the network using Dynamic Host Configuration Protocol (DHCP) and
Network Address Translation (NAT). When the wireless device is connected to a DSL
or cable modem that is connected to the Internet, it receives webpages and email
content from the Internet through its Internet connection, and then sends the
content to wireless-enabled computers, using the wireless network or using Ethernet
if there are computers connected to the Ethernet ports.
 Set up the Apple wireless device to act as a bridge on an existing network that
already has Internet access and a router providing IP addresses. The device passes
IP addresses and the Internet connection to AirPort or wireless-enabled computers,
or computers connected to the wireless device by Ethernet.
This document provides information about the latest AirPort Extreme Base Station,
AirPort Express, and Time Capsule, and detailed information about designing 802.11n
networks with AirPort Utility for computers using Mac OS X v10.5 or later, and
Windows Vista or Windows XP with Service Pack 2. If you’re using previous versions of
Mac OS X, or are setting up earlier versions of AirPort devices, you’ll find more
information at www.apple.com/support/airport.Chapter 1 Getting Started 5
You can set up an Apple wireless device and connect to the Internet wirelessly in
minutes. But because Apple wireless devices are flexible and powerful networking
products, you can also create an AirPort network that does much more. If you want to
design an AirPort network that provides Internet access to non-AirPort computers via
Ethernet, or take advantage of some of your wireless device’s more advanced features,
use this document to design and implement your network. You can find more general
wireless networking information and an overview of AirPort technology in the earlier
AirPort documents, located at www.apple.com/support/manuals/airport.
Note: The images of AirPort Utility in this document are from Mac OS X v10.5. If you’re
using a Windows computer, the images you see in this document may be slightly
different from what you see on your screen.
Configuring an Apple Wireless Device for Internet Access
Using AirPort Utility
Like your computer, Apple wireless devices must be set up with the appropriate
hardware and IP networking information to connect to the Internet. Install
AirPort Utility, which came on the CD with your wireless device, and use it to provide
Internet configuration information and other network settings.
AirPort Utility combines the ease of use of AirPort Setup Assistant and the power of
AirPort Admin Utility. It is installed in the Utilities folder in the Applications folder on
a Macintosh computer using Mac OS X, and in Start > All Programs > AirPort on
computers using Windows. AirPort Utility walks you through the setup process by
asking a series of questions to determine how the device’s Internet connection and
other interfaces should be set up. Enter the settings you received from your ISP or
network administrator for Ethernet, PPP over Ethernet (PPPoE), or your local area
network (LAN); give your AirPort network a name and password; set up a device as
a wireless bridge to extend the range of your existing AirPort network; and set other
options.
When you’ve finished entering the settings, AirPort Utility transfers the settings to your
wireless device. Then it connects to the Internet and shares its Internet connection with
computers that join its AirPort network.
You can also create an AirPort network that takes advantage of the more advanced
networking features of Apple wireless devices. To set more advanced AirPort options,
use AirPort Utility to manually set up your wireless device’s configuration, or make
quick adjustments to one you’ve already set up. Some of the AirPort advanced
networking features can be configured only using the manual setup features in
AirPort Utility. 6 Chapter 1 Getting Started
Set up your Apple wireless device manually using AirPort Utility when:
 You want to provide Internet access to computers that connect to the wireless device
using Ethernet
 you’ve already set up your device, but you need to change one setting, such as your
account information
 You need to configure advanced settings such as channel frequency, advanced
security options, closed networks, DHCP lease time, access control, WAN privacy,
power controls, or port mapping or other options
For instructions on using AirPort Utility to manually set up your wireless device and
network, see “Using AirPort Utility” on page 15.
Extending the Range of Your AirPort Network
You can extend the range of your network by using AirPort Utility to set up wireless
connections among several devices in your network, or to connect a device using
Ethernet to create a roaming network. For more information on extending the range of
your network, see “Connecting Additional Wireless Devices to Your AirPort Network” on
page 41.
Sharing a USB Hard Disk Connected to an AirPort Extreme
Base Station or Time Capsule
If you’re using an AirPort Extreme Base Station or a Time Capsule, you can connect a
USB hard disk to it, and computers connected to the network—wired or wireless, Mac
or Windows—can share files using the hard disk. Every Time Capsule includes an
internal AirPort disk, so you don’t need to connect an external one. If you want, you can
connect additional USB disks to the USB port on your Time Capsule. See “Sharing and
Securing USB Hard Disks on Your Network” on page 54.
Printing with an Apple Wireless Device
If you have a compatible USB printer connected to your Apple wireless device,
computers on the AirPort network can use Bonjour (Apple’s zero-configuration
networking technology) to print to the printer. For instructions about printing to a
USB printer from a computer, see “Connecting a USB Printer to an Apple Wireless
Device” on page 55.
Sharing Your Computer’s Internet Connection
If your computer is connected to the Internet, you can share your Internet connection
with other computers using Mac OS X version 10.2 or later, or Windows XP with Service
Pack 2. This is sometimes called using your computer as a software base station.Chapter 1 Getting Started 7
You can share your Internet connection as long as your computer is connected to the
Internet. If your computer goes to sleep or is restarted, or if you lose your Internet
connection, you need to restart Internet sharing.
To start Internet sharing on a computer using Mac OS X v10.5 or later:
1 Open System Preferences and click Sharing.
2 Choose the port you want to use to share your Internet connection from the “Share
your connection using” pop-up menu.
3 Select the port you want to use to share your Internet connection in the “To computers
using” list. You can choose to share your Internet connection with AirPort-enabled
computers or computers with built-in Ethernet, for example.
4 Select Internet Sharing in the Services list.
5 If you want to share your Internet connection with computers using AirPort, click
AirPort Options to give your network a name and password. 8 Chapter 1 Getting Started
To start Internet sharing on a computer using Windows:
1 Open Control Panel from the Start menu, and then click “Network and Internet.”
2 Click “Network and Sharing Center.”
3 Click “Manage network connections” in the Tasks list.
4 Right-click the network connection you want to share, and then select Properties.
5 Click Sharing and then select “Allow other network users to connect through this
computer’s Internet connection.”
Note: If your Internet connection and your local network use the same port (built-in
Ethernet, for example), contact your ISP before you turn on Internet sharing. In some
cases (if you use a cable modem, for example) you might unintentionally affect the
network settings of other ISP customers, and your ISP might terminate your service to
prevent you from disrupting its network.
The following chapters explain AirPort security options, AirPort network design and
setup, and other advanced options.2
9
2 AirPort Security
This chapter provides an overview of the security features
available in AirPort.
Apple has designed its wireless devices to provide several levels of security, so
you can enjoy peace of mind when you access the Internet, manage online financial
transactions, or send and receive email. The AirPort Extreme Base Station and
Time Capsule also include a slot for inserting a lock to deter theft.
For information and instructions for setting up these security features, see “Setting Up
the AirPort Extreme Network” on page 17.
Security for AirPort Networks at Home
Apple gives you ways to protect your wireless AirPort network as well as the data that
travels over it.
NAT Firewall
You can isolate your wireless network with firewall protection. Apple wireless devices
have a built-in Network Address Translation (NAT) firewall that creates a barrier
between your network and the Internet, protecting data from Internet-based IP attacks.
The firewall is automatically turned on when you set up the device to share a single
Internet connection. For computers with a cable or DSL modem, AirPort can actually be
safer than a wired connection.
Closed Network
Creating a closed network keeps the network name and the very existence of your
network private. Prospective users of your network must know the network name
and password to access it. Use AirPort Utility, located in the Utilities folder in the
Applications folder on a Macintosh computer using Mac OS X, or in Start > All
Programs > AirPort on a computer using Windows, to create a closed network.10 Chapter 2 AirPort Security
Password Protection and Encryption
AirPort uses password protection and encryption to deliver a level of security
comparable to that of traditional wired networks. Users can be required to enter a
password to log in to the AirPort network. When transmitting data and passwords,
the wireless device uses up to 128-bit encryption, through either Wi-Fi Protected Access
(WPA), WPA2, or Wired Equivalent Privacy (WEP), to scramble data and help keep
it safe. If you’re setting up an 802.11n-based AirPort device, you can also use WEP
(Transitional Security Network) if both WEP-compatible and WPA/WPA2-compatible
computers will join your network.
Note: WPA security is available only to AirPort Extreme wireless devices; AirPort and
AirPort Extreme clients using Mac OS X 10.3 or later and AirPort 3.3 or later; and to
non-Apple clients using other 802.11 wireless adapters that support WPA. WPA2
security requires firmware version 5.6 or later for an AirPort Extreme Base Station,
firmware version 6.2 or later for an AirPort Express, firmware version 7.3 or later for a
Time Capsule, and a Macintosh computer with an AirPort Extreme wireless card using
AirPort 4.2 or later. If your computer uses Windows XP or Windows Vista, check the
documentation that came with your computer to see if your computer supports WPA2.
Security for AirPort Networks in Businesses and Classrooms
Businesses and schools need to restrict network communications to authorized users
and keep data safe from prying eyes. To meet this need, Apple wireless devices and
software provide a robust suite of security mechanisms. Use AirPort Utility to set up
these advanced security features.
Transmitter Power Control
Because radio waves travel in all directions, they can extend outside the confines of a
specific building. The Transmit Power setting in AirPort Utility lets you adjust the
transmission range of your device’s network. Only users within the network vicinity
have access to the network.
MAC Address Access Control
Every AirPort and wireless card have a unique Media Access Control (MAC) address.
For AirPort Cards and AirPort Extreme Cards, the MAC address is sometimes referred to
as the AirPort ID. Support for MAC address access control lets administrators set up a
list of MAC addresses and restrict access to the network to only those users whose MAC
addresses are in the access control list.Chapter 2 AirPort Security 11
RADIUS Support
The Remote Authentication Dial-In User Service (RADIUS) makes securing a large
network easy. RADIUS is an access control protocol that allows a system administrator
to create a central list of the user names and passwords of computers that can access
the network. Placing this list on a centralized server allows many wireless devices to
access the list and makes it easy to update. If the MAC address of a user’s computer
(which is unique to each 802.11 wireless card) is not on your approved MAC address list,
the user cannot join your network.
Wi-Fi Protected Access (WPA) and WPA2
There has been increasing concern about the vulnerabilities of WEP. In response, the
Wi-Fi Alliance, in conjunction with the IEEE, has developed enhanced, interoperable
security standards called Wi-Fi Protected Access (WPA) and WPA2.
WPA and WPA2 use specifications that bring together standards-based, interoperable
security mechanisms that significantly increase the level of data protection and access
control for wireless LANs. WPA and WPA2 provide wireless LAN users with a high-level
assurance that their data remains protected and that only authorized network users
can access the network. A wireless network that uses WPA or WPA2 requires all
computers that access the wireless network to have WPA or WPA2 support. WPA
provides a high level of data protection and (when used in Enterprise mode) requires
user authentication.
The main standards-based technologies that constitute WPA include Temporal Key
Integrity Protocol (TKIP), 802.1X, Message Integrity Check (MIC), and Extensible
Authentication Protocol (EAP).
TKIP provides enhanced data encryption by addressing the WEP encryption
vulnerabilities, including the frequency with which keys are used to encrypt the
wireless connection. 802.1X and EAP provide the ability to authenticate a user on
the wireless network.
802.1X is a port-based network access control method for wired as well as wireless
networks. The IEEE adopted 802.1X as a standard in August 2001.
The Message Integrity Check (MIC) is designed to prevent an attacker from capturing
data packets, altering them, and resending them. The MIC provides a strong
mathematical function in which the receiver and the transmitter each compute and
then compare the MIC. If they do not match, the data is assumed to have been
tampered with and the packet is dropped. If multiple MIC failures occur, the network
may initiate countermeasures.12 Chapter 2 AirPort Security
The EAP protocol known as TLS (Transport Layer Security) presents a user’s information
in the form of digital certificates. A user’s digital certificates can comprise user names
and passwords, smart cards, secure IDs, or any other identity credentials that the IT
administrator is comfortable using. WPA uses a wide variety of standards-based EAP
implementations, including EAP-Transport Layer Security (EAP-TLS), EAP-Tunnel
Transport Layer Security (EAP-TTLS), and Protected Extensible Authentication Protocol
(PEAP). AirPort Extreme also supports the Lightweight Extensible Authentication
Protocol (LEAP), a security protocol used by Cisco access points to dynamically assign a
different WEP key to each user. AirPort Extreme is compatible with Cisco’s LEAP security
protocol, enabling AirPort users to join Cisco-hosted wireless networks using LEAP.
In addition to TKIP, WPA2 supports the AES-CCMP encryption protocol. Based on the
very secure AES national standard cipher, combined with sophisticated cryptographic
techniques, AES-CCMP was specifically designed for wireless networks. Migrating from
WEP to WPA2 requires new firmware for the AirPort Extreme Base Station (version 5.6 or
later), and for AirPort Express (version 6.2 or later). Devices using WPA2 mode are not
backward compatible with WEP.
WPA and WPA2 have two modes:
 Personal mode, which relies on the capabilities of TKIP or AES-CCMP without
requiring an authentication server
 Enterprise mode, which uses a separate server, such as a RADIUS server, for user
authentication
WPA and WPA2 Personal
 For home or Small Office/Home Office (SOHO) networks, WPA and WPA2 operates in
Personal mode, taking into account that the typical household or small office does
not have an authentication server. Instead of authenticating with a RADIUS server,
users manually enter a password to log in to the wireless network. When a user
enters the password correctly, the wireless device starts the encryption process using
TKIP or AES-CCMP. TKIP or AES-CCMP takes the original password and derives
encryption keys mathematically from the network password. The encryption key is
regularly changed and rotated so that the same encryption key is never used twice.
Other than entering the network password, the user isn’t required to do anything to
make WPA or WPA2 Personal work in the home.Chapter 2 AirPort Security 13
WPA and WPA2 Enterprise
WPA is a subset of the draft IEEE 802.11i standard and effectively addresses the wireless
local area network (WLAN) security requirements for the enterprise. WPA2 is a full
implementation of the ratified IEEE 802.11i standard. In an enterprise with IT resources,
WPA should be used in conjunction with an authentication server such as RADIUS to
provide centralized access control and management. With this implementation in
place, the need for add-on solutions such as virtual private networks (VPNs) may be
eliminated, at least for securing wireless connections in a network.
For more information about setting up a WPA or WPA2 protected network, see
“Using Wi-Fi Protected Access” on page 45.3
14
3 AirPort Network Designs
This chapter provides overview information and instructions
for the types of AirPort Extreme networks you can set up, and
some of the advanced options of AirPort Extreme.
Use this chapter to design and set up your AirPort Extreme network.
Configuring your Apple wireless device to implement a network design requires
three steps:
Step 1: Setting Up the AirPort Extreme Network
Computers communicate with the wireless device over the AirPort wireless network.
When you set up the AirPort network created by the wireless device, you can name the
wireless network, assign a password that will be needed to join the wireless network,
and set other options.
Step 2: Configuring and Sharing Internet Access
When computers access the Internet through the AirPort Extreme network, the wireless
device connects to the Internet and transmits information to the computers over the
AirPort Extreme network. You provide the wireless device with settings appropriate for
your ISP and configure how the device shares this connection with other computers.
Step 3: Setting Advanced Options
These settings are optional for most users. They include using the Apple wireless device
as a bridge between your AirPort Extreme network and an Ethernet network, setting
advanced security options, extending the AirPort network to other wireless devices,
and fine-tuning other settings.
For specific instructions on all these steps, refer to the sections later in this chapter.
You can do most of your setup and configuration tasks using AirPort Utility, and
following the onscreen instructions to enter your ISP and network information. To set
advanced options, you need to use AirPort Utility to manually set up your Apple
wireless device and AirPort network.Chapter 3 AirPort Network Designs 15
Using AirPort Utility
To set up and configure your computer or Apple wireless device to use AirPort Extreme
for basic wireless networking and Internet access, use AirPort Utility and answer
a series of questions about your Internet settings and how you would like to set up
your network.
1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac,
or in Start > All Programs > AirPort on a Windows computer.
2 Select your device in the list on the left if there is more than one device in your
network. Click Continue, and then follow the onscreen instructions to enter the settings
from your ISP or network administrator for the type of network you want to set up. See
the network diagrams later in this chapter for the types of networks you can set up
using AirPort Utility.
To set up a more complicated network, or to make adjustments to a network you’ve
already set up, use the manual setup features in AirPort Utility.
Setting AirPort preferences
Use AirPort preferences to set up your wireless device to alert you when there are
updates available for your device. You can also set it up to notify you if there are
problems detected, and to provide instructions to help solve the problems.
To set AirPort preferences:
1 Open AirPort Utility, located in the Utilities folder inside the Applications folder on
a Mac, and in Start > All Programs > AirPort on a Windows computer.
2 Do one of the following:
 On a Mac, choose AirPort Utility > Preferences
 On a Windows computer, choose File > Preferences16 Chapter 3 AirPort Network Designs
Select from the following checkboxes:
 Select “Check for Updates when opening AirPort Utility” to automatically check the
Apple website for software and firmware updates each time you open AirPort Utility.
 Select the “Check for updates” checkbox, and then choose a time interval from the
pop-up menu, such as weekly, to check for software and firmware updates in the
background. AirPort Utility opens if updates are available.
 Select “Monitor Apple wireless devices for problems” to investigate problems that
may cause the device’s status light to blink amber. With the checkbox selected,
AirPort Utility opens if a problem is detected, and then provides instructions to help
resolve the problem. This option monitors all of the wireless devices on the network.
 Select “Only Apple wireless devices that I have configured” to monitor only the
devices you’ve set up using this computer.
Monitoring devices for problems requires an AirPort wireless device that supports
firmware version 7.0 or later.
To set up your wireless device manually:
1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac, or
in Start > All Programs > AirPort on a Windows computer.
2 Select your device in the list.
3 Choose Base Station > Manual Setup and enter the password if necessary. The default
device password is public.
If you don’t see your wireless device in the list:
1 Open the AirPort status menu in the menu bar on a Mac and make sure that you’ve
joined the AirPort network created by your wireless device. On a Windows computer,
hover the cursor over the wireless network icon in the status tray to make sure the
computer is connected to the correct network.
The default network name for an Apple wireless device is AirPort Network XXXXXX,
where XXXXXX is replaced with the last six digits of the AirPort ID, (or MAC address).
The AirPort ID is printed on the bottom of Apple wireless devices.
2 Make sure your computer’s network and TCP/IP settings are configured properly.
On a computer using Mac OS X, choose AirPort from the Show pop-up menu in the
Network pane of System Preferences. Then choose Using DHCP from the Configure IPv4
pop-up menu in the TCP/IP pane.
On a computer using Windows, right-click the wireless connection icon that displays
the AirPort network, and choose Status. Click Properties, select Internet Protocol
(TCP/IP), and then click Properties. Make sure “Obtain an IP address automatically” is
selected.Chapter 3 AirPort Network Designs 17
If you can’t open the wireless device settings:
1 Make sure your network and TCP/IP settings are configured properly.
On a computer using Mac OS X, select AirPort from the network connection services list
in the Network pane of System Preferences. Click Advanced, and then choose Using
DHCP from the Configure IPv4 pop-up menu in the TCP/IP pane.
On a computer using Windows, right-click the wireless connection icon that displays
the AirPort network, and choose Status. Click Properties, select Internet Protocol
(TCP/IP), and then click Properties. Make sure “Obtain an IP address automatically”
is selected.
2 Make sure you entered the wireless device password correctly. The default password
is public. If you’ve forgotten the device password, you can reset it to public by resetting
the device.
To temporarily reset the device password to public, hold down the reset button for one
second. To reset the device back to its default settings, hold the reset button for five full
seconds.
If you’re on an Ethernet network that has other devices, or you’re using Ethernet to
connect to the device:
AirPort Utility scans the Ethernet network to create the list of devices. As a result, when
you open AirPort Utility, you may see devices that you cannot configure.
Setting Up the AirPort Extreme Network
The first step in configuring your Apple wireless device is setting up the device and the
network it will create. You can set up most features using AirPort Utility and following
the onscreen instructions to enter the information from your ISP or network
administrator.
To configure a network manually or set advanced options, open your wireless device’s
configuration in AirPort Utility and manually set up your device and network.
1 Choose the network of the wireless device you want to configure from the AirPort
status menu on a computer using Mac OS X, or from the wireless connection icon in
the status tray on a computer using Windows.
2 Open AirPort Utility and select the wireless device from the list. If you don’t see the
device you want to configure, click Rescan to scan for available wireless devices, and
then select the one you want from the list. 18 Chapter 3 AirPort Network Designs
3 Choose Base Station > Manual Setup and enter the password if necessary. The default
device password is public.
You can also double-click the name of the wireless device to open its configuration in
a separate window. When you open the manual setup window, the Summary pane is
displayed. The summary pane provides information and status about your wireless
device and network.Chapter 3 AirPort Network Designs 19
If the wireless device reports a problem, the status icon turns yellow. Click Base Station
Status to display the problem and suggestions to resolve it.
Wireless Device Settings
Click the AirPort button, and then click Base Station or Time Capsule, depending on the
device you’re setting up, to enter information about the wireless device.
Give the Device a Name
Give the device an easily identifiable name. This makes it easy for administrators
to locate a specific device on an Ethernet network with several devices.
Change the Device Password
The device password protects its configuration so that only the administrator can
modify it. The default password is public. It is a good idea to change the device
password to prevent unauthorized changes to it.
If the password is not changed from public, you’ll not be prompted for a password
when you select it from the list and click Configure.
Other Information
 Allow configuration over the WAN port. This allows you to administer the wireless
device remotely.
 Advertise the wireless device over the Internet using Bonjour. If you have an account
with a dynamic DNS service, you can connect to it over the Internet.
 Set the device time automatically. If you have access to a Network Time Protocol
server, whether on your network or on the Internet, choose it from the pop-up menu.
This ensures your wireless device is set to the correct time.20 Chapter 3 AirPort Network Designs
Set Device Options
Click Base Station Options and set the following:
 Enter a contact name and location for the wireless device. The name and location are
included in some logs the device generates. The contact and location fields may be
helpful if you’ve more than one wireless device on your network.
 Set status light behavior to either Always On or Flash On Activity. If you choose Flash
On Activity, the device status light blinks when there is network traffic.
 If your wireless device supports it, select “Check for firmware updates” and choose an
increment, such as Daily from the pop-up menu.
Wireless Network Settings
Click Wireless, and enter the network name, radio mode, and other wireless
information.
Setting the Wireless Mode
AirPort Extreme supports two wireless modes:
 Create a wireless network. Choose this option if you’re creating a new
AirPort Extreme network.
 Extend a wireless network. Choose this option if you plan to connect another Apple
wireless device to the network you’re setting up.
Naming the AirPort Extreme Network
Give your AirPort network a name. This name appears in the AirPort status menu on the
AirPort-enabled computers that are in range of your AirPort network.Chapter 3 AirPort Network Designs 21
Choosing the Radio Mode
Choose 802.11a/n - 802.11b/g from the Radio Mode pop-up menu if computers with
802.11a, 802.11n, 802.11g, or 802.11b wireless cards will join the network. Each client
computer will connect to the network and transmit network traffic at the highest
possible speed.
Choose 802.11n - 802.11b/g if only computers with 802.11n, 802.11b, or 802.11g
compatible wireless cards will join the network.
Note: If you don’t want to use an 802.11n radio mode, hold down the Option key and
chose a radio mode that doesn’t include 802.11n.
Changing the Channel
The “channel” is the radio frequency over which your wireless device communicates.
If you use only one device (for example, at home), you probably won’t need to change
the channel frequency. If you set up several wireless devices in a school or office,
use different channel frequencies for devices that are within approximately 150 feet of
each other.
Adjacent wireless devices should have at least 4 channels between their channel
frequencies. So if device A is set to channel 1, device B should be set to channel 6 or 11.
For best results, use channels 1, 6, or 11 when operating your device in the 2.4 GHz
range.
Choose Manually from the Radio Channel Selection pop-up menu, and then click Edit
to set the channels manually.
AirPort-enabled computers automatically tune to the channel frequency your wireless
device is using when they join the AirPort network. If you change the channel
frequency, AirPort client computers do not need to make any changes.
Password-protect Your Network
To password-protect your network, you can choose from a number of wireless security
options. In the AirPort pane of AirPort Utility, click Wireless and choose one of the
following options from the Wireless Security pop-up menu:
 None: Choosing this option turns off all password protection for the network. Any
computer with a wireless adapter or card can join the network, unless the network is
set up to use access control. See “Setting Up Access Control” on page 47.
 WEP: If your device supports it, choose this option and enter a password to protect
your network with a Wired Equivalent Privacy (WEP) password. Your Apple wireless
device supports 40-bit and 128-bit encryption. To use 40-bit WEP, don’t use an
802.11n radio mode.22 Chapter 3 AirPort Network Designs
 WPA/WPA2 Personal: Choose this option to protect your network with Wi-Fi
Protected Access. You can use a password between 8 and 63 ASCII characters or a
Pre-Shared Key of exactly 64 hexadecimal characters. Computers that support WPA
and computers that support WPA2 can join the network. Choose WPA2 Personal if
you want only computers that support WPA2 to join your network.
 WPA/WPA2 Enterprise: Choose this option if you’re setting up a network that
includes an authentication server, such as a RADIUS server, with individual user
accounts. Enter the IP address and port number for the primary and optional
secondary server, and enter a “shared secret,” which is the password for the server.
Choose WPA2 Enterprise if you want only computers that support WPA2 to join the
network.
 WEP (Transitional Security Network): If your device supports it, you can use this
option to allow computers using WPA or WPA2 to join the network. Computers or
devices that use WEP can also join the network. WEP (Transitional Security Network)
supports 128-bit encryption. To use this option, the wireless device use an 802.11n
radio mode. Hold the Option key on your keyboard while clicking the Wireless
Security pop-up menu to use WEP (Transitional Security Netowrk).
For more information and instructions for setting up WPA or WPA2 on your network,
see “Using Wi-Fi Protected Access” on page 45.
Setting Wireless Options
Click Wireless Options to set additional options for your network.Chapter 3 AirPort Network Designs 23
Setting Additional Wireless Options
Use the Wireless Options pane to set the following:
 5 GHz network name: Provide a name for the 5 GHz segment of the dual-band
network if you want it to have a different name than the 2.4 GHz network.
 Country: Choose the country for the location of your network from the Country
pop-up menu.
 Multicast rate: Choose a multicast rate from the pop-up menu. If you set the
multicast rate high, only clients on the network that are within range and can
achieve the speed you set will receive transmissions.
 Transmit power: Choose a setting from the Transmit Power pop-up menu to set the
network range (the lower the percentage, the shorter the network range).
 WPA Group Key Timeout: Enter a number in the text field, and choose an increment
from the pop-up menu to change the frequency of key rotation.
 Use Wide Channels: If you set up your network to use the 5 GHz frequency range,
you can use wide channels to provide higher network throughput.
Note: Using wide channels is not permitted in some countries.
 Create a closed network: Selecting a closed network hides the name of the
network so that users must enter the exact network name and password to join
the AirPort Extreme network.
 Use interference robustness: Interference robustness can solve interference
problems caused by other devices or networks.
To set more advanced security options, see “Keeping Your Network Secure” on page 45.24 Chapter 3 AirPort Network Designs
Setting up a Guest Network
Click Guest Network and then enter the network name and other options for the guest
network. When you set up a guest network, a portion of your connection to the
Internet is reserved for “guests”, wireless clients that can join the guest network and
connect to the Internet without accessing your private network.
Select “Allow guest network clients to communicate with each other” to allow client
computers to share files and services with each other while they’re connected to the
guest network. Make sure sharing services are set up on the client computers.
Configuring and Sharing Internet Access
The next step is setting up your wireless device’s Internet connection and sharing its
Internet access with client computers. The following sections tell you what to do,
depending on how your device connects to the Internet.
You’re Using a DSL or Cable Modem
In most cases, you can implement this network design using AirPort Utility and
following the onscreen instructions to set up your wireless device and network. You
need to use AirPort Utility to manually set up your device only if you want to set up
or adjust optional advanced settings.Chapter 3 AirPort Network Designs 25
What It Looks Like
How It Works
 The Apple wireless device (in this example, a Time Capsule) connects to the Internet
through its Internet WAN (<) connection to your DSL or cable modem.
 Computers using AirPort or computers connected to the wireless device’s Ethernet
LAN port (G) connect to the Internet through the device.
 The device is set up to use a single, public IP address to connect to the Internet, and
uses DHCP and NAT to share the Internet connection with computers on the network
using private IP addresses.
 AirPort computers and Ethernet computers communicate with one another through
the wireless device.
Important: Connect Ethernet computers that are not connected to the Internet to
the device’s LAN port (G) only. Since the device can provide network services, you
must set it up carefully to avoid interfering with other services on your Ethernet
network.
What You Need for a DSL or Cable Modem Connection
DSL or cable modem
to Internet
to Ethernet port
Time Capsule
< Ethernet WAN port
2.4 or 5 GHz
Components Check Comments
Internet account with DSL or
cable modem service provider
Does your service provider use a
static IP or DHCP configuration?
You can get this information
from your service provider or the
Network preferences pane on
the computer you use to access
the Internet through this service
provider.
Apple wireless device (an AirPort
Extreme Base Station, an AirPort
Express, or a Time Capsule)
Place the device near your DSL
or cable modem.26 Chapter 3 AirPort Network Designs
What to Do
If you’re using AirPort Utility to assist you with configuring the Apple wireless device
for Internet access:
1 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac,
or in Start > All Programs > AirPort on a Windows computer.
2 Follow the onscreen instructions and enter the settings you received from your service
provider to connect to the Internet, and then set up the device to share the Internet
connection with computers on the network.
If you’re using AirPort Utility to manually set up your wireless device:
1 Make sure that your DSL or cable modem is connected to the Ethernet WAN port (<)
on your Apple wireless device.
2 Open AirPort Utility, located in the Utilities folder in the Applications folder on a Mac,
or in Start > All Programs > AirPort on a Windows computer. Select your wireless device
and choose Base Station > Manual Setup, or double-click your device’s icon in the list to
open the configuration in a separate window.
3 Click the Internet button. Click Internet Connection and choose Ethernet or PPPoE from
the Connect Using pop-up menu, depending on which one your service provider
requires. If your service provider gave you PPPoE connection software, such as EnterNet
or MacPoET, choose PPPoE.
Note: If you’re connecting to the Internet through a router using PPPoE and your Apple
wireless device is connected to the router via Ethernet, you do not need to use PPPoE
on your wireless device. Choose Ethernet from the Connect Using pop-up menu in the
Internet pane, and deselect the “Distribute IP addresses” checkbox in the Network
pane. Contact your service provider if you aren’t sure which one to select.
4 Choose Manually or Using DHCP from the Configure IPv4 pop-up menu if you chose
Ethernet from the Connect Using pop-up menu, depending on how your service
provider provides IP addresses.
 If your provider gave you an IP address and other numbers with your subscription,
use that information to configure the wireless device IP address manually. If you
aren’t sure, ask your service provider. Enter the IP address information in the fields
below the Configure IPv4 pop-up menu.Chapter 3 AirPort Network Designs 27
 If you chose PPPoE, your ISP provides your IP address automatically using DHCP.
If your service provider asks you for the MAC address of your wireless device, use the
address of the Ethernet WAN port (<), printed on the label on the bottom of the
device.
If you’ve already used AirPort Utility to set up your wireless device, the fields below the
Configure IPv4 pop-up menu may already contain the information appropriate for your
service provider.
You can change the WAN Ethernet speed if you have specific requirements for the
network you’re connected to. In most cases, the settings that are configured
automatically are correct. Your service provider should be able to tell you if you need
to adjust these settings.
Changing the WAN Ethernet speed can affect the way the wireless device interacts with
the Internet. Unless your service provider has given you specific settings, use the
automatic settings. Entering the wrong settings can affect network performance.
Contact your service
provider for the
information you should
enter in these fields.
Use this pop-up menu
if you need to adjust
the speed of the
Ethernet WAN port.28 Chapter 3 AirPort Network Designs
If you configure TCP/IP using DHCP, choose Using DHCP from the Configure IPv4
pop-up menu. Your IP information is provided automatically by your ISP using DHCP.
5 If you chose PPPoE from the Connect Using pop-up menu, enter the PPPoE settings
your service provider gave you. Leave the Service Name field blank unless your service
provider requires a service name.
Note: With AirPort, you don’t need to use a third-party PPPoE connection application.
You can connect to the Internet using AirPort.
Your service provider
may require you to
enter information
in these fields.
Contact your
service provider
for the information
you should enter
in these fields.Chapter 3 AirPort Network Designs 29
If you’re connecting to the Internet through a router that uses PPPoE to connect to the
Internet, and your wireless device is connected to the router via Ethernet, you do not
need to use PPPoE on your device. Choose Ethernet from the Connect Using pop-up
menu in the Internet pane, and deselect the “Distribute IP addresses” checkbox in the
Network pane. Because your router is distributing IP addresses, your wireless device
doesn’t need to. More than one device on a network providing IP addresses can cause
problems.
6 Click PPPoE to set PPPoE options for your connection.
 Choose Always On, Automatic, or Manual, depending on how you want to control
when your wireless device is connected to the Internet.
If you choose Always On, your device stays connected to your modem and the
Internet as long as the modem is turned on. If you choose Automatic, the wireless
device connects to the modem, which connects to the Internet when you use an
application that requires an Internet connection, such as email or an instant message
or web application. If you choose Manual, you need to connect the modem to the
Internet when you use an application that requires an Internet connection.
If you chose Automatic or Manual from the Connection pop-up menu, you need to
choose an increment, such as “10 minutes,” from the “Disconnect if idle” pop-up
menu. If you don’t use an Internet application after the increment of time has passed,
you’ll be disconnected from the Internet.
Note: If your wireless device is connected to your modem using an Ethernet LAN
port, and your modem is connected to the Internet using PPPoE, you may not be
able to use the manual setting.30 Chapter 3 AirPort Network Designs
 Enter Domain Name System (DNS) server addresses and a specific domain name your
wireless device accesses when you connect to the Internet.
7 Click the Network button and configure how the device will share its Internet access
with AirPort and Ethernet computers.
If you chose Ethernet from the Connect Using pop-up menu, choose how your device
will share the Internet connection from the Connection Sharing pop-up menu.
 To share a single Internet connection with AirPort computers and computers
connected to the device with Ethernet using DHCP and NAT, choose “Share a public
IP address” from the Connection Sharing pop-up menu. Using DHCP and NAT lets the
wireless device dynamically and automatically assign IP addresses to client
computers, which simplifies each computer’s TCP/IP configuration. See “Setting
DHCP and NAT Options” on page 31.
By default, the wireless device allows other devices, computers using Ethernet, and
computers using AirPort to communicate with each other using non-IP protocols like
AppleTalk. If you want to connect an AppleTalk Ethernet printer to the Apple wireless
device or use AppleTalk between wired and wireless computers, make sure the
devices are connected to the Ethernet LAN port (G) on the device.
 To distribute a range of IP addresses using only DHCP, choose “Distribute a range of
IP addresses.” See “Setting DHCP Only Options” on page 33.Chapter 3 AirPort Network Designs 31
 If you don’t want your wireless device to share its IP address, choose “Off (Bridge
Mode).” If you set up your device in bridge mode, AirPort computers have access to
all services on the Ethernet network, and the device does not provide Internet
sharing services. See “You’re Using an Existing Ethernet Network” on page 37 for
more information about setting up your wireless device as a bridge.
Using the wireless device as a bridge can be a way to address incompatibilities
between the device’s Internet sharing features and your ISP’s connection method.
Setting DHCP and NAT Options
If you chose “Share a public IP address” from the Connection Sharing pop-up menu,
you can set DHCP and NAT options. Click DHCP.
 Choose a range of IP addresses from the DHCP Range pop-up menu. Choose 10.0,
192.168, or 172.16 and then enter a beginning and ending address in the DHCP
Beginning Address and the DHCP Ending Address fields, depending on which
addresses you want the wireless device to provide.
 Enter a number in the DHCP Lease field, and then choose minutes, hours, or days
from the pop-up menu.
 Type a welcome message in the DHCP Message field. This message is displayed when
a computer joins your network.
 If your network is set up to use a Lightweight Directory Access Protocol (LDAP) server
on your network, you can enter the address of the server in the LDAP Server field,
and computers on your network will have access to it.32 Chapter 3 AirPort Network Designs
 To provide specific IP addresses to specific computers on your wireless network,
click the Add (+) button below the DHCP Reservations list, and follow the onscreen
instructions to name the reservation and reserve the address by MAC address or
DHCP client ID. If you choose MAC address, click Continue and enter the MAC
address and specific IP address.
Next you can set NAT options for the network. Click NAT.
 You can set up a default host on your network. A default host (sometimes known as
a DMZ) is a computer on your network that is exposed to the Internet and receives
all inbound traffic. A default host may be useful if you use a computer on your
AirPort network to play network games, or want to route all Internet traffic through
a single computer.
 You can set up NAT Port Mapping Protocol (NAT-PMP). NAT-PMP is an Internet
Engineering Task Force Internet Draft, an alternative to the more common Universal
Plug and Play (UPnP) protocol implemented in many network address translation
(NAT) routers. NAT-PMP allows a computer in a private network (behind a NAT router)
to automatically configure the router to allow parties outside the private network to
contact this computer.
Included in the protocol is a method for retrieving the public IP address of a NAT
gateway, allowing a client to make this public IP address and port number known to
peers that may wish to communicate with it. This protocol is implemented in current
Apple products, including Mac OS X 10.4 Tiger and later, AirPort Extreme, AirPort
Express, and Time Capsule networking products, and Bonjour for Windows.Chapter 3 AirPort Network Designs 33
You can also set up port mapping. To ensure that requests are properly routed to your
web, AppleShare, or FTP server, or a specific computer on your network, you need to
establish a permanent IP address for the server or computer, and provide “inbound port
mapping” information to the Apple wireless device. See “Directing Network Traffic to a
Specific Computer on Your Network (Port Mapping)” on page 49.
Setting DHCP Only Options
If you chose “Distribute a range of IP addresses” from the Connection Sharing pop-up
menu, your wireless device is set up to use DHCP to distribute a range of IP addresses
using only DHCP. You cannot use NAT if you chose this option. Click DHCP and enter
the beginning and ending addresses you want to distribute to computers joining your
wireless network.
You can set the additional DHCP options, such as DHCP Lease, DHCP Message, and
other options following the instructions above.
Setting Up Client Computers
To configure TCP/IP on client computers using Mac OS X v10.5:
1 Open System Preferences on the client computer and then click Network.
2 Do one of the following:
a If the client computer is using AirPort, select AirPort in the network connection
services list, and then click Advanced.34 Chapter 3 AirPort Network Designs
Next, choose DHCP from the Configure IPv4 pop-up menu.
b If you enabled a DHCP server when you set up the wireless device’s network, and the
client computer is using Ethernet, select Ethernet in the network connection services
list, and then choose Using DHCP from the Configure pop-up menu.Chapter 3 AirPort Network Designs 35
c If you selected “Distribute a range of IP addresses” when you set up the wireless
device’s network, you can provide Internet access to client computers using
Ethernet by setting the client IP addresses manually. Select Ethernet in the
network connection services list, and then choose Manually from the Configure
pop-up menu.
When you configure Ethernet clients manually for a wireless device that provides
NAT over Ethernet, you can use IP addresses in the range 10.0.1.2 to 10.0.1.200.
In the Subnet Mask field, enter 255.255.255.0. In the Router field, enter 10.0.1.1.
Enter the same name server address and search domain information that you
entered in the wireless device configuration.
To configure TCP/IP on client computers using Windows
Make sure you’ve installed the wireless adapter in your computer and the software
necessary to set up the adapter.
To configure TCP/IP on client computers:
1 Open Control Panel from the Start menu, and then click “Network and Internet.”
2 Click “Network and Sharing Center.”
3 Click “Manage network connections” in the Tasks list.
4 Right-click the wireless connection you want to share, and then select Properties.
Enter the IP and router
addresses from the range
your device is providing.
Enter the DNS and Search
Domain addresses if
necessary.36 Chapter 3 AirPort Network Designs
5 Click Internet Protocol Version 4 (TCP/IPv4), and then click Properties.
 If you chose “Share a public IP address” in the Network pane of AirPort Utility, select
“Obtain an IP address automatically.”
 If you chose “Distribute a range of IP addresses” when you set up the wireless device’s
network, you can provide Internet access to client computers by setting the client IP
addresses manually. Select “Use the following IP address.”
When you configure clients manually for a wireless device that provides NAT service,
use IP addresses in the range 10.0.1.2 to 10.0.1.200, 172.16.1.2 to 172.16.1.200, or
192.168.1.2 to 192.168.1.200.
In the “Subnet mask” field, enter 255.255.255.0. In the “Default gateway” field, enter
10.0.1.1, 172.16.1.1, or 192.168.1.1, depending on which addressing scheme you used. Enter
the same name server address and search domain information that you entered in the
wireless device configuration.Chapter 3 AirPort Network Designs 37
You’re Using an Existing Ethernet Network
You can use AirPort Utility to easily set up the Apple wireless device for Internet access
through an existing Ethernet network that already has a router, switch, or other
network device providing IP addresses. Use the manual setup features of AirPort Utility
if you need to adjust optional advanced settings.
What It Looks Like
How It Works
 The Apple wireless device (in this example, a Time Capsule) uses your Ethernet
network to communicate with the Internet through the Ethernet WAN port (<).
 AirPort and Ethernet clients access the Internet and the Ethernet network through
the Apple wireless device.
What You Need for an Ethernet Connection
Router
to Internet
to Ethernet port
Time Capsule