Apple Cryptographic Services Guide Manuel
Apple sur Fnac.com
- Pour voir la liste complète des manuels APPLE, cliquez ici
TELECHARGER LE PDF sur :
http://developer.apple.com/library/ios/Documentation/Security/Conceptual/cryptoservices/cryptoservices.pdf
Commander un produit Apple sur Fnac.com
Voir également d'autres Guides APPLE :
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-Lecteur-Optique-Manuel
Apple-Carte-AirPort-Manuel
Apple-iPhone_Finger_Tips_Guide.pdf-Anglais-Manuel
Apple-Couvercle-Manuel
Apple-battery.cube.pdf-Manuel
Apple-Boitier-de-l-ordinateur-Manuel
Apple-Pile-Interne-Manuel
Apple-atacable.pdf-Manuel
Apple-videocard.pdf-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-iOS_Business.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-IntroductionXserve1.0.1
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-F034-2262AXerve-grappe
Apple-Mac_OS_X_Server_Glossaire_10.5
Apple-FRLogic_Pro_7_Guide_TDM
Apple-iphone_bluetooth_headset_userguide
Apple-Administration_des_services_reseau_10.5
Apple-imacg5_17inch_harddrive
Apple-iPod_nano_4th_gen_Manuale_utente
Apple-iBook-G4-Getting-Started
Apple-XsanGettingStarted
Apple-Mac_mini_UG-Early2006
Apple-Guide_des_fonctionnalites_de_l_iPod_classic
Apple-Guide_de_configuration_d_Xsan_2
Apple-MacBook_Late2006_UsersGuide
Apple-sur-Fnac.com
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-FRLogic_Pro_7_Guide_TDM
Apple-airportextreme_802.11n_userguide
Apple-iPod_shuffle_3rdGen_UG
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-imacG5_20inch_AirPort
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-Shake_4_User_Manual
Apple-aluminumAppleKeyboard_wireless2007_UserGuide
Apple-ipod_shuffle_features_guide
Apple-Color-User-Manual
Apple-XsanGettingStarted
Apple-Migration_10.4_2e_Ed
Apple-MacBook_Air_SuperDrive
Apple-MacBook_Late2007-f
ApplePowerMacG5_(Early_2005)_UserGuide
Apple-iSightUserGuide
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-eMac_2005UserGuide
Apple-imacg5_20inch_Inverter
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-StoreKitGuide.pdf-Japon
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-Mail_Service_v10.4.pdf
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-System_Image_Admin.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-AirMac-カード取り付け手順-Japon
Apple-iPhone開発ガイド-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_Component_AV_Cable.pdf
Apple-DVD_Studio_Pro_4_Installation_de_votre_logiciel
Apple-Windows_Services
Apple-Motion_3_New_Features_F
Apple-g4mdd-fw800-lowerfan
Apple-MacOSX10.3_Welcome
Apple-Print_Service
Apple-Xserve_Setup_Guide_F
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-boot_camp_install-setup
Apple-iBookG3_14inchUserGuideMultilingual
Apple-mac_pro_server_mid2010_ug_f
Apple-Motion_Supplemental_Documentation
Apple-imac_mid2011_ug_f
Apple-iphone_guide_de_l_utilisateur
Apple-macbook_air_11inch_mid2011_ug_fr
Apple-NouvellesfonctionnalitesdeLogicExpress7.2
Apple-QT_Streaming_Server
Apple-Web_Technologies_Admin
Apple-Mac_Pro_Early2009_4707_UG
Apple-guide_de_l_utilisateur_de_Numbers08
Apple-Decouverte_d_Aperture_2
Apple-Guide_de_configuration_et_d'administration
Apple-mac_integration_basics_fr_106.
Apple-iPod_shuffle_4thgen_Guide_de_l_utilisateur
Apple-ARA_Japan
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-RemoteSupportJP
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-Open_Directory.pdf
Apple-Nike_+_iPod_User_guide
Apple-ard_admin_guide_2.2_fr.pdf
Apple-systemoverviewj.pdf-Japon
Apple-Xserve_TO_J070411.pdf-Japon
Apple-Mac_Pro_User_Guide.pdf
Apple-iMacG5_iSight_UG.pdf
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-Logic_Pro_8.0_lbn_j.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-iMac_Mid2010_UG_BR.pdf
Apple-iMac_Late2009_UG_J.pdf
Apple-iphone_user_guide-For-iOS-6-Software
Apple-iDVD5_Getting_Started.pdf
Apple-guide_des_fonctionnalites_de_l_ipod_touch.pdf
Apple_iPod_touch_User_Guide
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_upute_za_uporabu
Apple_ipad_user_guide_ta
Apple_iPod_touch_User_Guide
apple_earpods_user_guide
apple_iphone_gebruikershandleiding
apple_iphone_5_info
apple_iphone_brukerhandbok
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-iMac_G5_de_lutilisateur
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
Liste-documentation-apple
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-Color_1.0_User_Manual_F
Apple-guide_de_configuration_airport_express_4.2
Apple-TimeCapsule_SetupGuide
Apple-Instruments_et_effets_Logic_Express_8
Apple-Manuel_de_l_utilisateur_de_WaveBurner
Apple-Macmini_Guide_de_l'utilisateur
Apple-PowerMacG5_UserGuide
Disque dur, ATA parallèle Instructions de remplacement
Apple-final_cut_pro_x_logic_effects_ref_f
Apple-Leopard_Installationshandbok
Manuale Utente PowerBookG4
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
AppleTV_Setup-Guide
Apple-livetype_2_user_manual_f
Apple-imacG5_17inch_harddrive
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-Workgroup-Server-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
Cryptographic Services
GuideContents
About Cryptographic Services 5
At a Glance 5
How to Use This Document 5
Prerequisites 5
See Also 6
Cryptography Concepts In Depth 7
What Is Encryption? 7
Types of Encryption 8
Symmetric Keys 8
Asymmetric Keys 9
Diffie-Hellman Key Exchange 11
Cryptographic Hash Functions 12
Digital Signatures 12
Digital Certificates 14
Encrypting and Hashing Data 19
Encryption Technologies Common to iOS and OS X 19
Keychain Services 19
Cryptographic Message Syntax Services 20
Certificate, Key, and Trust Services 20
Common Crypto 20
Encryption Technologies Specific to OS X 20
Security Transforms 20
CDSA/CSSM 21
OpenSSL 22
Encryption in iOS 22
Managing Keys, Certificates, and Passwords 23
Certificate, Key, and Trust Services 23
Keychain Services 24
To Learn More 24
Generating Random Numbers 25
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
2Generating Random Numbers in OS X 25
Generating Random Numbers in iOS 26
Transmitting Data Securely 27
Using the URL Loading System 28
CFNetwork 28
Secure Transport 29
OpenSSL 29
To Learn More 30
CDSA Overview 31
Apple CDSA Plug-ins 33
AppleCSP Module 33
AppleFileDL Module 33
AppleCSP/DL Module 34
AppleX509CL Module 34
AppleX509TP Module 34
CSSM Services 35
Cryptographic Services 35
Data Store Services 36
Certificate Services 36
Trust Policy Services 36
Authorization Computation Services 36
Document Revision History 37
Glossary 38
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
3
ContentsFigures
Cryptography Concepts In Depth 7
Figure 1-1 Asymmetric key encryption 10
Figure 1-2 Creating a digital signature 13
Figure 1-3 Verifying a digital signature 14
Figure 1-4 Anatomy of a digital certificate 15
Figure 1-5 Creating the certificates for the root CA and a secondary CA 16
Figure 1-6 Creating the certificate for an end user and signing a document with it 17
CDSA Overview 31
Figure A-1 OS X implementation of CDSA 32
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
4OS X and iOS provide a number of technologiesthat provide cryptographic services—encryption and decryption,
hashing, random number generation, secure network communication, and so on. These technologies can be
used to secure data at rest (when stored on your hard drive or other media), secure data in transit, determine
the identity of a third party, and build additional security technologies.
At a Glance
OS X and iOS provide a wide range of cryptographic services, including:
● Encryption and decryption (both general-purpose and special-purpose)
● Key management using keychains
● Cryptographically strong random number generation
● Secure communication (SSL and TLS)
● Secure storage using FileVault and iOS File Protection
How to Use This Document
“Cryptography Concepts In Depth” (page 7) provides a basic grounding in cryptographic concepts and
terminology. These concepts are not specific to OS X or iOS, but are necessary for understanding the rest of
the book.
“Encrypting Data” (page 19) describes the APIs available in OS X and iOS for general-purpose encryption.
Prerequisites
Before reading this document, you should be familiar with the conceptsin SecurityOverview and Secure Coding
Guide .
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
5
About Cryptographic ServicesSee Also
For more information about OS X authentication and authorization (built on top of encryption technologies),
read Authentication, Authorization, and Permissions Guide .
About Cryptographic Services
See Also
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
6The word cryptography (from Greek kryptos, meaning hidden) at its core refers to techniques for making data
unreadable to prying eyes. This is not a complete definition, however.
In practice, cryptography can includes a range of techniques that can be used for verifying the authenticity of
data (detecting modifications), determining the identity of a person or other entity, determining who sent a
particular message or created a particular piece of data, sending data securely across a network, locking files
securely behind a password or passphrase, and so on.
This chapter describes a number of these techniques, beginning with basic encryption, then moving on to
other cryptographic constructs built on top of it.
Note: This chapter repeats many of the concepts in Security Overview, but with additional detail
and depth. It may help to read that document before reading this chapter.
What Is Encryption?
Encryption is the transformation of data into a form in which it cannot be made sense of without the use of
some key. Such transformed data is referred to as ciphertext. Use of a key to reverse this process and return
the data to its original (cleartext or plaintext) form is called decryption. Most of the security APIs in OS X and
iOS rely to some degree on encryption of text or data. For example, encryption is used in the creation of
certificates and digital signatures, in secure storage of secrets in the keychain, and in secure transport of
information.
Encryption can be anything from a simple process of substituting one character for another—in which case
the key is the substitution rule—to a complex mathematical algorithm. For purposes of security, the more
difficult it is to decrypt the ciphertext, the better. On the other hand, if the algorithm is too complex, takes too
long to do, or requires keys that are too large to store easily, it becomes impractical for use in a personal
computer. Therefore,some balance must be reached between strength of the encryption (that is, how difficult
it is for someone to discover the algorithm and the key) and ease of use.
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
7
Cryptography Concepts In DepthFor practical purposes, the encryption need only be strong enough to protect the data for the amount of time
the data might be useful to a person with malicious intent. For example, if you need to keep your bid on a
contract secret only until after the contract has been awarded, an encryption method that can be broken in a
few weeks willsuffice. If you are protecting your credit card number, you probably want an encryption method
that cannot be broken for many years.
Types of Encryption
There are two main types of encryption in use in computer security, referred to as symmetric key encryption
and asymmetric key encryption . A closely related process to encryption, in which the data is transformed using
a key and a mathematical algorithm that cannot be reversed, is called cryptographic hashing. The remainder
of thissection discusses encryption keys, key exchange mechanisms(including the Diffie-Hellman key exchange
used in some OS X secure transport protocols), and cryptographic hash functions.
Symmetric Keys
Symmetric key cryptography (also called private key cryptography or secret key cryptography) is the classic
use of keysthat most people are familiar with: the same key is used to encrypt and decrypt the data. The classic,
and most easily breakable, version of this is the Caesar cipher (named for Julius Caesar), in which each letter
in a message is replaced by a letter that is a fixed number of positions away in the alphabet (for example, “a”
is replaced by “c”, “b” is replaced by “d”, and so forth). In this case, the key used to encrypt and decrypt the
message issimply the number of positionsin the alphabet to shift the letters. Modern symmetric key algorithms
are much more sophisticated and much harder to break. However, they share the property of using the same
key for encryption and decryption.
There are many different algorithms used for symmetric key cryptography, offering anything from minimal to
nearly unbreakable security. Some of these algorithms offer strong security, easy implementation in code, and
rapid encryption and decryption. Such algorithms are very useful for such purposes as encrypting files stored
on a computer to protect them in case an unauthorized individual uses the computer. They are somewhat less
useful forsending messagesfrom one computer to another, because both ends of the communication channel
must possess the key and must keep it secure. Distribution and secure storage of such keys can be difficult
and can open security vulnerabilities.
In 1968, the USS Pueblo , a U.S. Navy intelligence ship, was captured by the North Koreans. At the time, every
Navy ship carried symmetric keys for a variety of code machines at a variety of security levels. Each key was
changed daily. Because there was no way to know how many of these keys had not been destroyed by the
Pueblo’s crew and therefore were in the possession of North Korea, the Navy had to assume that all keys being
Cryptography Concepts In Depth
Types of Encryption
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
8carried by the Pueblo had been compromised. Every ship and shore station in the Pacific theater (that is,several
thousand installations, including ships at sea) had to replace all of their keys by physically carrying code books
and punched cards to each installation.
The Pueblo incident was an extreme case. However, it hassomething in common with the problem of providing
secure communication for commerce over the Internet. In both cases, codes are used for sending secure
messages, not between two locations, but between a server (the Internetserver or the Navy’s communications
center) and a large number of communicants (individual web users or ships and shore stations). The more end
users that are involved in the secure communications, the greater the problems of distribution and protection
of the secret symmetric keys.
Although secure techniques for exchanging or creating symmetric keys can overcome this problem to some
extent (for example, Diffie-Hellman key exchange, described later in this chapter), a more practical solution
for use in computer communications came about with the invention of practical algorithms for asymmetric
key cryptography.
Asymmetric Keys
In asymmetric key cryptography, different keys are used for encrypting and decrypting a message. The
asymmetric key algorithms that are most useful are those in which neither key can be deduced from the other.
In that case, one key can be made public while the other is kept secure. There are some distinct advantages
to this public-key–private-key arrangement, often referred to as public key cryptography: the necessity of
distributing secret keysto large numbers of usersis eliminated, and the algorithm can be used for authentication
as well as for cryptography.
The first public key algorithm to become widely available was described by Ron Rivest, Adi Shamir, and Len
Adleman in 1977, and is known as RSA encryption from their initials. Although other public key algorithms
have been created since, RSA is still the most commonly used. The mathematics of the method are beyond
the scope of this document, and are available on the Internet and in many books on cryptography. The algorithm
is based on mathematical manipulation of two large prime numbers and their product. Its strength is believed
to be related to the difficulty of factoring a very large number. With the current and foreseeable speed of
modern digital computers, the selection of long-enough prime numbers in the generation of the RSA keys
should make this algorithm secure indefinitely. However, this belief has not been proved mathematically, and
either a fast factorization algorithm or an entirely different way of breaking RSA encryption might be possible.
Also, if practical quantum computers are developed, factoring large numbers will no longer be an intractable
problem.
Other public key algorithms, based on different mathematics of equivalent complexity to RSA, include ElGamal
encryption and elliptic curve encryption. Their use issimilar to RSA encryption (though the mathematics behind
them differs), and they will not be discussed further in this document.
Cryptography Concepts In Depth
Types of Encryption
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
9To see how public key algorithms address the problem of key distribution, assume that Alice wants to receive
a secure communication from Bob. The procedure is illustrated in Figure 1-1.
Figure 1-1 Asymmetric key encryption
The secure message exchange illustrated in Figure 1-1 has the following steps:
1. Alice uses one of the public key algorithms to generate a pair of encryption keys: a private key, which she
keeps secret, and a public key. She also prepares a message to send to Bob.
2. Alice sends the public key to Bob, unencrypted. Because her private key cannot be deduced from the
public key, doing so does not compromise her private key in any way.
3. Alice can now easily prove her identity to Bob (a process known as authentication ). To do so, she encrypts
her message (or any portion of the message) using her private key and sends it to Bob.
4. Bob decrypts the message with Alice’s public key. This proves the message must have come from Alice,
as only she has the private key used to encrypt it.
Cryptography Concepts In Depth
Types of Encryption
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
105. Bob encrypts his message using Alice’s public key and sends it to Alice. The message is secure, because
even if it is intercepted, no one but Alice has the private key needed to decrypt it.
6. Alice decrypts the message with her private key.
Since encryption and authentication are subjects of great interest in nationalsecurity and protecting corporate
secrets, some extremely smart people are engaged both in creating secure systems and in trying to break
them. Therefore, itshould come as no surprise that actualsecure communication and authentication procedures
are considerably more complex than the one just described. For example, the authentication method of
encrypting the message with your private key can be got around by a man-in-the-middle attack, where
someone with malicious intent (usually referred to as Eve in books on cryptography) intercepts Alice’s original
message and replacesit with their own,so that Bob is using not Alice’s public key, but Eve’s. Eve then intercepts
each of Alice’s messages, decrypts it with Alice’s public key, alters it (if she wishes), and reencrypts it with her
own private key. When Bob receives the message, he decrypts it with Eve’s public key, thinking that the key
came from Alice.
Although this is a subject much too broad and technical to be covered in detail in this document, digital
certificates and digital signatures can help address these security problems. These techniques are described
later in this chapter.
Diffie-Hellman Key Exchange
The Diffie-Hellman key exchange protocol is a way for two ends of a communication session to generate
symmetric private keys through the exchange of public keys. The two sides agree beforehand on the exact
algorithm to use and certain parameters, such as the size of the keys. Then each side selects a random number
as a private key and uses that number to generate a public key, according to the algorithm. The security of
this algorithm dependsin part on it being extremely difficult to derive or guessthe private key from this public
key.
The two sides exchange public keys and then each generates a session key using their own private key and
the other side’s public key. The mathematics of the algorithm is such that, even though neither side knows
the other side’s private key, both sides’ session keys are identical. A third party intercepting the public keys
but lacking knowledge of either private key cannot generate a session key. Therefore, data encrypted with the
session key is secure while in transit.
Although Diffie-Hellman key exchange provides strong protection against compromise of intercepted data, it
provides no mechanism for ensuring that the entity on the other end of the connection is who you think it is.
That is, this protocol is vulnerable to a man-in-the-middle attack. Therefore, it is sometimes used together with
some other authentication method to ensure the integrity of the data.
Cryptography Concepts In Depth
Diffie-Hellman Key Exchange
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
11Diffie-Hellman key exchange is supported by Apple Filing Protocol (AFP) version 3.1 and later and by Apple’s
Secure Transport API. Because RSA encryption tends to be slower than symmetric key methods, Diffie-Hellman
(and other systems where public keys are used to generate symmetric private keys) can be useful when a lot
of encrypted data must be exchanged.
Cryptographic Hash Functions
A cryptographic hash function takes any amount of data and applies an algorithm that transforms it into a
fixed-size output value. For a cryptographic hash function to be useful, it has to be extremely difficult or
impossible to reconstruct the original data from the hash value, and it must be extremely unlikely that the
same output value could result from any other input data.
Sometimes it is more important to verify the integrity of data than to keep it secret. For example, if Alice sent
a message to Bob instructing him to shred some records (legally, of course), it would be important to Bob to
verify that the list of documents was accurate before proceeding with the shredding. Since the shredding is
legal, however, there is no need to encrypt the message, a computationally expensive and time-consuming
process. Instead, Alice could compute a hash of the message (called a message digest) and encrypt the digest
with her private key. When Bob receives the message, he decrypts the message digest with Alice’s public key
(thus verifying that the message is from Alice) and computes his own message digest from the message text.
If the two digests match, Bob knows the message has not been corrupted or tampered with.
The most common hash function you will use is SHA-1, an algorithm developed and published by the U.S.
Government that produces a 160-bit hash value from any data up to 2**64 bits in length. There are also a
number of more exotic algorithms such as SHA-2, elliptic-curve-based algorithms, and so on.
For compatibility with existing systems and infrastructure, you may occasionally need to use older algorithms
such as MD5, but they are not recommended for use in new designs because of known weaknesses.
Digital Signatures
Digital signatures are a way to ensure the integrity of a message or other data using public key cryptography.
Like traditionalsignatures written with ink on paper, they can be used to authenticate the identity of the signer
of the data. However, digital signatures go beyond traditional signatures in that they can also ensure that the
data itself has not been altered. This is like signing a check in such a way that if someone changes the amount
of the sum written on the check, an “Invalid” stamp becomes visible on the face of the check.
To create a digital signature, the signer generates a message digest of the data and then uses a private key to
encrypt the digest. The signature includes the encrypted digest and information about the signer’s digital
certificate. The certificate is used to verify the signature; it includesthe public key needed to decrypt the digest
Cryptography Concepts In Depth
Cryptographic Hash Functions
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
12and the algorithm used to create the digest. To verify that the signed document has not been altered, the
recipient uses the algorithm to create their own message digest and uses the public key to decrypt the digest
in the signature. If the two digests are identical, then the message cannot have been altered and must have
been sent by the owner of the public key.
To ensure that the person who provided the signature is not only the same person who provided the data but
is also who they say they are, the certificate is also signed—in this case by the certification authority who issued
the certificate.
Digital signatures play a key role in code signing. Developers are encouraged to sign their applications. On
execution, each application’ssignature is checked for validity. Digitalsignatures are required on all applications
for iOS. Read Code Signing Guide for details about how code signing is used by OS X and iOS.
Figure 1-2 illustrates the creation of a digital signature.
Figure 1-2 Creating a digital signature
CA signature CA signature
Cryptography Concepts In Depth
Digital Signatures
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
13Figure 1-3 illustrates the verification of a digital signature. The recipient gets the signer’s public key from the
signer’s certificate and uses that to decrypt the digest. Then, using the algorithm indicated in the certificate,
the recipient creates a new digest of the data and compares the new digest to the decrypted copy of the one
delivered in the signature. If they match, then the received data must be identical to the original data created
by the signer.
Figure 1-3 Verifying a digital signature
Hash
CA signature
Digital Certificates
A digital certificate is a collection of data used to verify the identity of the holder or sender of the certificate.
For example, an X.509 certificate contains such information as:
● Structural information—version,serial number, the message digest algorithm used to create the signature,
and so on
● A digital signature from the certificate authority to ensure that the certificate has not been altered and to
indicate the identity of the issuer
●
Information about the certificate holder—name, email address, company name, the owner’s public key,
and so on
● Validity period (the certificate is not valid before or after this period)
Cryptography Concepts In Depth
Digital Certificates
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
14● Attributes, known as certificate extensions, that contain additional information such as allowable uses
for this certificate
The careful reader will have noticed that a digital signature includes the certificate of the signer, and that the
signer’s certificate, in turn, contains a digital signature that includes another certificate. In general, each
certificate is verified through the use of another certificate, creating a chain of trust—a certificate chain that
ends with a root certificate. The issuer of a certificate is called a certification authority (CA). The owner of the
root certificate is the root certification authority. Figure 1-4 illustrates the anatomy of a digital certificate.
Figure 1-4 Anatomy of a digital certificate
Cryptography Concepts In Depth
Digital Certificates
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
15The root certificate is self-signed, meaning the signature of the root certificate was created by the root
certification authority themselves. Figure 1-5 and Figure 1-6 illustrate how a chain of certificates is created and
used. Figure 1-5 shows how the root certification authority creates its own certificate and then creates a
certificate for a secondary certification authority.
Figure 1-5 Creating the certificates for the root CA and a secondary CA
Cryptography Concepts In Depth
Digital Certificates
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
16Figure 1-6 shows how the secondary certification authority creates a certificate for an end user and how the
end user uses it to sign a document.
Figure 1-6 Creating the certificate for an end user and signing a document with it
In Figure 1-6, the creator of the document has signed the document. The signature indicates the certificate of
the document’s creator (labeled User in the figure). The document’s creator signs the document with a private
key, and the signing certificate contains the corresponding public key, which can be used to decrypt the
message digest to verify the signature (described earlier in “Digital Signatures”). This certificate—together with
the private and public keys—was provided by a certification authority (CA).
In order to verify the validity of the user’s certificate, the certificate is signed using the certificate of the CA.
The certificate of the CA includes the public key needed to decrypt the message digest of the user’s certificate.
Continuing the certificate chain, the certificate of the CA is signed using the certificate of the authority who
issued that certificate. The chain can go on through any number of intermediate certificates, but in Figure 1-5
Cryptography Concepts In Depth
Digital Certificates
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
17the issuer of the CA’s certificate is the root certification authority. Note that the certificate of the root CA, unlike
the others, is self-signed—that is, it does not refer to a further certification authority but is signed using the
root CA’s own private key.
When a CA creates a certificate, it uses its private key to encrypt the certificate’s message digest. The signature
of every certificate the CA issues refers to its own signing certificate. The CA’s public key is in this certificate,
and the application verifying the signature must extract this key to verify the certificate of the CA. So it continues,
on down the certificate chain, to the certificate of the root CA. When a root CA issues a certificate, it, too, signs
the certificate. However, this signing certificate was not issued by another CA; the chain stops here. Rather,
the root CA issues its own signing certificate, as shown in Figure 1-5.
The certificate of the root CA can be verified by creating a digest and comparing it with one widely available.
Typically, the root certificate and root CA’s public key are already stored in the application or on the computer
that needs to verify the signature.
It’s possible to end a certificate chain with a trusted certificate that is not a root certificate. For example, a
certificate can be certified as trusted by the user, or can be cross certified—that is, signed with more than one
certificate chain. The general term for a certificate trusted to certify other certificates—including root certificates
and others—is anchor certificate. Because most anchor certificates are root certificates, the two terms are
often used interchangeably.
The confidence you can have in a given certificate depends on the confidence you have in the anchor certificate;
for example, the trust you have in the certificate authorities and in their proceduresfor ensuring thatsubsequent
certificate recipients in the certificate chain are fully authenticated. For this reason, it is always a good idea to
examine the certificate that comes with a digital signature, even when the signature appears to be valid. In
OS X and iOS, all certificates you receive are stored in your keychain. In OS X, you can use the Keychain Access
utility to view them.
Certain attributes of a digital certificate (known as certificate extensions) are said to establish a level of trust
for a digital certificate. A trust policy is a set of rules that specify the appropriate uses for a certificate that has
a specific level of trust. In other words, the level of trust for a certificate is used to answer the question “Should
I trust this certificate for this action?”
For example, in order to be trusted to verify a digitally signed email message, a certificate must contain an
email address that matches the address of the sender of the email.
Cryptography Concepts In Depth
Digital Certificates
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
18Both symmetric and asymmetric key encryption schemes can be used to encrypt data. Asymmetric encryption
is most commonly used for sending data across trust boundaries, such as one person sending another person
an encrypted email. It is also often used forsending a symmetric session key across an insecure communication
channel so that symmetric encryption can then be used for future communication. Symmetric encryption is
most commonly used for data at rest (on your hard drive for example) and as a session key in a number of
encrypted networking schemes.
OS X and iOS provide a number of different APIs for encryption and decryption. This chapter describes the
recommended APIs.
Encryption Technologies Common to iOS and OS X
OS X and iOS provide a number of encryption technologies. Of these, three APIs are available on both iOS and
OS X:
● Keychain Services API—provides secure storage for passwords, keys, and so on
● Cryptographic Message Syntax—provides (non-streaming) symmetric and asymmetric encryption and
decryption
● Certificate, Key, and Trust Services—provides cryptographic support services and trust validation
The sections that follow describe these technologies.
Keychain Services
The Keychain Services API is commonly used to store passwords, keys, certificates, and othersecretsin a special
encrypted file called a keychain. You should always use the keychain to store passwords and othershort pieces
of data (such as cookies) that are used to grant access to secure web sites, as otherwise this data might be
compromised if an unauthorized person gains access to a user’s computer, mobile device, or a backup thereof.
Although this is mostly used for storing passwords and keys, the keychain can also store small amounts of
arbitrary data. The keychain is described further in the next chapter.
OS X also includes a utility that allows users to store and read the data in the keychain, called Keychain Access.
For more information, see “Keychain Access” in Security Overview.
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
19
Encrypting and Hashing DataCryptographic Message Syntax Services
The Cryptographic Message Syntax Services programming interface allows you to encrypt or add a digital
signature to S/MIME messages. It is a good API to use when signing or encrypting data for store-and-forward
applications, such as email. See Cryptographic Message Syntax Services Reference for details.
Certificate, Key, and Trust Services
The Certificate, Key, and Trust Services API provides trust validation and support functions for cryptography.
These features are described further in “Managing Keys, Certificates, and Passwords” (page 23).
In iOS, this API also provides basic encryption capabilities, as described in “Encryption in iOS” (page 22).
Common Crypto
In OS X v10.5 and later and iOS 5.0 and later, Common Crypto provides low-level C support for encryption and
decryption. Common Crypto is not as straightforward as Security Transforms, but provides a wider range of
features, including additional hashing schemes, cipher modes, and so on.
For more information, see the manual page for CommonCrypto.
Encryption Technologies Specific to OS X
In addition to Keychain Services and Cryptographic Message Syntax Services, OS X provides four additional
APIs for performing encryption:
● Security Transforms API—a Core-Foundation-level API that provides support for signing and verifying,
symmetric cryptography, and Base64 encoding and decoding
● Common Crypto—a C-level API that can perform most symmetric encryption and decryption tasks
● CDSA/CSSM—a legacy API thatshould be used only to perform tasks notsupported by the other two APIs,
such as asymmetric encryption
These APIs are described in the sections that follow.
Security Transforms
In OS X v10.7 and later, the Security Transforms API provides efficient and easy-to-use support for performing
cryptographic tasks. Security transforms are the recommended way to perform symmetric encryption and
decryption, asymmetric signing and verifying, and Base64 encoding and decoding in OS X.
Encrypting and Hashing Data
Encryption Technologies Specific to OS X
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
20Based on the concept of data flow programming, the Security Transforms API lets you construct graphs of
transformationsthat feed into one another, transparently using Grand Central Dispatch to schedule the resulting
work efficiently across multiple CPUs. As the CFDataRef (or NSData) objects pass through the object graph,
callbacks within each individual transform operate on that data, then pass it on to the transform’s output,
which may be connected to the input of another transform object, and so on.
The transform API also provides a file reader transform (based on CFReadStreamRef or NSInputStream
objects) that can be chained to the input of other transforms.
Out of the box, the Security Transforms API allows you to read files, perform symmetric encryption and
decryption, perform asymmetric signing and verifying, and perform Base64 encoding. The Security Transforms
API also provides support for creating custom transforms that perform other operations on data. For example,
you might create a transform that byte swaps data prior to encrypting it or a transform that encodes the
resulting encrypted data for transport.
For more information, read Security Transforms Programming Guide and Security Transforms Reference .
CDSA/CSSM
Important: CDSA (including CSSM) is deprecated and should not be used for new development. It is not
available in iOS.
CDSA is an Open Source security architecture adopted as a technical standard by the Open Group. Apple has
developed its own Open Source implementation of CDSA, available as part of Darwin at Apple’s Open Source
site. This API provides a wide array ofsecurity services, including fine-grained access permissions, authentication
of users’ identities, encryption, and secure data storage.
Although CDSA has its own standard application programming interface (API), it is complex and does not
follow standard Apple programming conventions. For thisreason, the CDSA API is deprecated as of OS X version
10.7 (Lion) and is not available in iOS. Fortunately, OS X and iOS include their own higher-level security APIs
that abstract away much of that complexity.
Where possible, you should use one of the following instead of using CDSA directly:
● The Security Objective-C API for authentication (in OS X). See “Security Objective-C API” in Security Overview
for details.
● The Security Transforms API for symmetric encryption and decryption, asymmetric signing and verifying,
and other supported tasks in OS X v10.7 and later. See “Security Transforms” (page 20) for details.
● The Certificate, Key, and Trust Services API for general encryption, key management, and other tasks. See
“Encryption in iOS” (page 22) for details.
Encrypting and Hashing Data
Encryption Technologies Specific to OS X
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
21If these APIs do not meet your needs, you can still use CDSA in OS X, but please file bugs at http://bugreport.apple.com/ to request the additional functionality that you need. For more information, read “CDSA
Overview” (page 31).
OpenSSL
Although OpenSSL is commonly used in the open source community, OpenSSL does not provide a stable API
from version to version. For this reason, although OS X provides OpenSSL libraries, the OpenSSL libraries in OS
X are deprecated, and OpenSSL has never been provided as part of iOS. Use of the OS X OpenSSL libraries by
applications is strongly discouraged.
If your application depends on OpenSSL, you should compile OpenSSL yourself and statically link a known
version of OpenSSL into your application. This use of OpenSSL is possible on both OS X and iOS. However,
unless you are trying to maintain source compatibility with an existing open source project, you should generally
use a different API.
Common Crypto and Security Transforms are the recommended alternativesfor general encryption. CFNetwork
and Secure Transport are the recommended alternatives for secure communications.
Encryption in iOS
In iOS, in addition to providing support functions for encoding and decoding keys, the Certificate, Key, and
Trust Services API also provides basic encryption, decryption, signing, and verifying of blocks of data using the
following SecKey functions:
SecKeyEncrypt—encrypts a block of data using the specified key.
SecKeyDecrypt—decrypts a block of data using the specified key.
SecKeyRawSign—signs a block of data using the specified key.
SecKeyRawVerify—verifies a signature against a block of data and a specified key.
You can find examples of how to use these functions in “Certificate, Key, and Trust Services Tasks for iOS” in
Certificate, Key, and Trust Services Programming Guide .
For detailed reference content, read Certificate, Key, and Trust Services Reference .
Encrypting and Hashing Data
Encryption in iOS
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
22The keychain provides storage for passwords, encryption keys, certificates, and other small pieces of data.
After an application requests access to a keychain, it can store and retrieve sensitive data, confident that
untrusted applications cannot access that data without explicit action by the user.
In OS X, the user is prompted for permission when an application needs to access the keychain; if the keychain
is locked, the user is asked for a password to unlock it.
In iOS, an application can access only its own items in the keychain—the user is never asked for permission or
for a password.
There are two recommended APIs for accessing the keychain:
● Certificate, Key, and Trust Services
● Keychain Services
Certificate, Key, and Trust Services
Certificate, Key, and Trust Services is a C API for managing certificates, public and private keys, and trust
policies in iOS and OS X. You can use these services in your application to:
● Create certificates and asymmetric keys
● Add certificates and keys to keychains, remove them from keychains, and use keys to encrypt and decrypt
data
● Retrieve information about a certificate, such as the private key associated with it, the owner, and so on
● Convert certificates to and from portable representations
● Create and manipulate trust policies and evaluate a specific certificate using a specified set of trust policies
● Add anchor certificates
In OS X, functions are also available to retrieve anchor certificates and set user-specified settings for trust
policies for a given certificate.
In iOS, additional functions are provided to:
● Use a private key to generate a digital signature for a block of data
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
23
Managing Keys, Certificates, and Passwords● Use a public key to verify a signature
● Use a public key to encrypt a block of data
● Use a private key to decrypt a block of data
Certificate, Key, and Trust Services operates on certificates that conform to the X.509 ITU standard, uses the
keychain for storage and retrieval of certificates and keys, and uses the trust policies provided by Apple.
Because certificates are used by SSL and TLS for authentication, the OS X Secure Transport API includes a variety
of functions to manage the use of certificates and root certificates in a secure connection.
To display the contents of a certificate in an OS X user interface, you can use the SFCertificatePanel and
SFCertificateView classes in the Security Objective-C API. In addition, the SFCertificateTrustPanel
class displays trust decisions and lets the user edit trust decisions.
Keychain Services
In OS X and iOS, Keychain Services allows you to create keychains, add, delete, and edit keychain items, and—in
OS X only—manage collections of keychains. In most cases, a keychain-aware application does not have to do
any keychain management and only has to call a few functions to store or retrieve passwords.
By default, backups of iOS data are stored in cleartext, with the exception of passwords and other secrets on
the keychain, which remain encrypted in the backup. It is therefore important to use the keychain to store
passwords and other data (such as cookies) that are used to accesssecure web sites. Otherwise, this data might
be compromised if an unauthorized person gains access to the backup data.
To get started using Keychain Services, see Keychain Services Programming Guide and Keychain Services
Reference .
In OS X, the Keychain Access application provides a user interface to the keychain. See “Keychain Access” in
Security Overview for more information about this application.
To Learn More
For more information about using Keychain Servicesto store and retrieve secrets and certificates, read Keychain
Services Programming Guide and Keychain Services Reference .
Tor more information about Secure Transport, read “Secure Transport” (page 29).
For more information about the certificate user interface API, read “SecurityObjective-C API” in SecurityOverview.
Managing Keys, Certificates, and Passwords
Keychain Services
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
24Cryptographically secure pseudorandomnumbers are required for a number of encryption algorithms. Because
these pseudorandom numbers are generated by a computer algorithm, they are not truly random. However,
the algorithm is not discernible from the sequence.
The way you generate random numbers depends on whether you are writing code for OS X or iOS.
Generating Random Numbers in OS X
In OS X, you can get cryptographically secure pseudorandom numbers by reading from /dev/random.
Important: Numbers generated by the rand and random APIs are not cryptographically secure. In OS X,
given the same initial seed value, both functions reproducibly generate a consistent sequence of values
each time you run them, and neither generates an equally distributed set of possible values.
For example, if you need a random 64-bit integer value, you could write code like this:
FILE *fp = fopen("/dev/random", "r");
if (!fp) {
perror("randgetter");
exit(-1);
}
uint64_t value = 0;
int i;
for (i=0; i Add Keychain menu item to add them to your list of keychains) to see
what they contain and how the certificate chains are constructed.
A trust policy (TP) plug-in performs two main functions: it assembles the chain of certificates needed to verify
a given certificate, and it determines the level of trust that can be accorded the certificate.
The AppleX509TP module performs these functions on X.509 certificates, using trust policies established by
Apple.
CSSM Services
Although the OS X security APIs provide all the capabilities you are ever likely to need for developing secure
applications, nearly all the standard CSSM APIs are also available for your use. This section briefly describes
the functions provided by each CSSM service. For details, see Common Security: CDSA and CSSM, version 2
(with corrigenda), from the Open Group.
Cryptographic Services
Cryptographic Services in CSSM provides functions to perform the following tasks:
● Encrypting and decrypting text and data
● Creating and verifying digital signatures
● Creating a cryptographic hash (used for message digests and other purposes)
● Generating symmetric and asymmetric pairs of cryptographic keys
● Generating pseudorandom numbers
● Controlling access to the CSP for creation of keys
To see exactly which security protocols and algorithms are supported by Apple’s CSP implementation, see the
documentation provided with the Open Source security code, which you can download at Apple’s Open Source
site, and the Security Release Notes in the latest Xcode Tools from Apple.
CDSA Overview
CSSM Services
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
35Data Store Services
CSSM Data Store Services provides an API for storing and retrieving data that is independent of the type of
storage used. If there is more than one DL module installed, the caller can query Data Store Services to learn
the capabilities of each and select which one to use in a particular call. The Apple implementation of Data
Store Services supports any standard CDSA DL plug-in module. The AppleFileDL Data Storage Library and
AppleCSP/DL Encrypted Data Storage module both implement functions called by Data Store Services.
Certificate Services
Certificate Services as specified by CDSA performs the following functions:
● Verifies the signatures on certificates and certificate revocation lists
● Creates certificates and certificate revocation lists
● Signs certificates and certificate revocation lists
● Extracts values of fields from certificates and certificate revocation lists
● Searches certificate revocation lists for specified certificates
Apple’s implementation of Certificate Services supports all of the CL API functions in the CDSA/CSSM
specification.
Trust Policy Services
The OS X implementation of CSSM Trust Policy Services provides functions to verify certificates, to determine
what attributes they contain and therefore the level of trust they can be given, and to construct a chain of
related certificates. It does not implement other trust policy functions in the CSSM standard. Documentation
for the CSSM trust policy functions supported by Apple’s TP implementation can be found with the Open
Source security code, which you can download at Apple’s Open Source site.
Authorization Computation Services
Apple’s implementation of CSSM does not include the Authorization Computation Services defined in the
CDSA standard. Instead, the Authorization Services API calls the Security Server daemon directly (see Figure
A-1 (page 32)).
CDSA Overview
CSSM Services
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
36This table describes the changes to Cryptographic Services Guide .
Date Notes
2012-09-19 Updated artwork and made minor editorial fixes.
New document that describesthe encryption, decryption,signing, hashing,
and other cryptographic technologies in OS X and iOS.
2012-01-09
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
37
Document Revision Historyalgorithm A sequence of actions to accomplish
some task. In cryptography, refers to a sequence of
actions, usually mathematical calculations,
performed on data to encrypt or decrypt it.
anchor certificate A digital certificate trusted to be
valid, which can then be used to verify other
certificates. An anchor certificate can be a root
certificate, a cross-certified certificate (that is, a
certificate signed with more than one certificate
chain), or a locally defined source of trust.
asymmetric keys A pair of related but dissimilar
keys, one used for encrypting and the other used
for decrypting a message or other data. See also
public key cryptography. Compare symmetric keys.
authentication The process by which a person or
other entity (such as a server) proves that it is who
(or what) it says it is. Compare authorization;
identification.
authorization The process by which an entity such
as a user or a server gets the right to perform a
operation that only specific entities are allowed to
perform. (Authorization can also refer to the right
itself, as in “Bob has the authorization to run that
program.”) Authorization usually involves first
authenticating the entity and then determining
whether it hasthe appropriate permissions. Compare
authentication.
BSD Berkeley Software Distribution. BSD is a form
of the UNIX operating system and providesthe basis
for the OS X file system, including file access
permissions.
CA See certification authority (CA).
CDSA Abbreviation for Common Data Security
Architecture. An open software standard for a
security infrastructure that provides a wide array of
security services, including fine-grained access
permissions, authentication of users, encryption, and
secure data storage. CDSA has a standard application
programming interface, called CSSM. In addition, OS
X includes its own security APIs that call the CDSA
API for you. See also CDSA plug-in.
CDSA plug-in A software module that connects to
CDSA through a standard interface and that
implements or extends CDSA security services for a
particular operating system and hardware
environment.
certificate See digital certificate.
certificate authority See certification authority (CA).
certificate chain A sequence of related digital
certificates that are used to verify the validity of a
digital certificate. Each certificate is digitally signed
using the certificate of its certification authority (CA).
This creates a chain of certificates ending in an
anchor certificate.
certificate extension A data field in a digital
certificate containing information such as allowable
uses for the certificate.
Certificate, Key, and Trust Services An API you can
use to create, manage, and read certificates; add
certificates to a keychain; create encryption keys;
and manage trust policies. In iOS, you can also use
this API to encrypt, decrypt, and sign data.
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
38
Glossarycertification authority (CA) The issuer of a digital
certificate. In order for the digital certificate to be
trusted, the certification authority must be a trusted
organization that authenticates an applicant before
issuing a certificate.
CFHTTP An API that you can use to create,serialize,
deserialize, and manage HTTP protocol messages,
including secure HTTPS messages. This component
lets you add authentication information to a
message. CFHTTP is a component of CFNetwork and
is built on top of CFStream.
CFNetwork A high-level API used for creating,
sending, and receiving serialized messages over a
network. CFNetwork is built on top of Secure
Transport, and so can use the Secure Sockets Layer
(SSL) and Transport Layer Security (TLS) secure
networking protocols.
CFStream An API that creates and manages the
read and write streams that CFHTTP depends on.
CFStream is a component of CFNetwork and is built
on top of Secure Transport. You can specify a Secure
Sockets Layer (SSL) or Transport Layer Security (TLS)
protocol version to encrypt and decrypt the data
stream.
chain of trust See certificate chain.
cipher A scheme for encrypting data.
ciphertext Text or other data that has been
encrypted. Compare cleartext.
cleartext Ordinary, unencrypted data. Compare
ciphertext.
code signing The addition of a digital signature to
an application or block of code.
credentials Data that can be used to identify,
authenticate, or authorize an entity. For example, a
user name and password constitute authentication
credentials. A Kerberos ticket, consisting of an
encrypted session key and other information, is an
example of an identification credential.
cryptographic hash function An algorithm that
takes any amount of data and transforms it into a
fixed-size output value. For a cryptographic hash
function to be useful for security, it has to be
extremely difficult or impossible to reconstruct the
original data from the hash value, and it must be
extremely unlikely that the same output value could
result from any other input data. See also message
digest.
cryptographic hashing The process whereby data
is transformed using a cryptographic hash function.
CSSM Abbreviation for Common Security Services
Manager. A public application programming
interface for CDSA. CSSM also defines an interface
for plug-ins that implement security services for a
particular operating system and hardware
environment.
decryption The transformation of ciphertext back
into the original cleartext. Compare encryption. See
also asymmetric keys; symmetric keys.
Diffie-Hellman key exchange A protocol that
provides a way for two ends of a communication
session to generate symmetric private keys through
the exchange of public keys.
digest See message digest.
digital certificate A collection of data used to verify
the identity of the holder orsender of the certificate.
OS X and iOS support the X.509 standard for digital
certificates. See also certificate chain.
digital ID See digital certificate.
Glossary
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
39digital signature A way to ensure the integrity of
a message or other data using public key
cryptography. To create a digitalsignature, the signer
generates a message digest of the data and then
uses a private key to encrypt the digest. The
signature includes the encrypted digest and
identifies the signer. Anyone wanting to verify the
signature uses the signer’s digital certificate, which
containsthe public key needed to decrypt the digest
and specifiesthe algorithm used to create the digest.
encryption The transformation of data into a form
in which it cannot be made sense of without the use
of some key. Such transformed data is referred to as
ciphertext. Use of a key to reverse this process and
return the data to its original (or cleartext) form is
called decryption.
hash algorithm See cryptographic hash function.
identification The process by which a process
verifies that a person or entity is the same one it
communicated with previously. Identification is in
general faster than authentication and does not
require interaction with the user.
identity A digital certificate together with an
associated private key.
key A piece of secret information required to
decode an encrypted message. In modern
cryptographic methods, it is usually a lengthy
integer.
keychain A database in OS X and iOS used to store
encrypted passwords, private keys, and othersecrets.
It is also used to store certificates and other
non-secret information that is used in cryptography
and authentication. Applications can use the
keychain services API (or the legacy keychain
manager API) to manipulate data in the keychain.
Users can also access keychain data using the
Keychain Access utility.
Keychain Access An OS X utility that enables users
to view and modify the data stored in the keychain.
Keychain Services An API forsecurely storing small
amounts of data on the keychain.
level of trust The confidence you can have in the
validity of a certificate, based on the certificates in
its certificate chain and on the certificate extensions
the certificate contains. The level of trust for a
certificate is used together with the trust policy to
answer the question “Should I trust this certificate
for this action?”
man-in-the-middle attack An attack on a
communication channel in which the attacker can
intercept messages going between two parties
without the communicating parties’ knowledge.
Typically, the man in the middle substitutes
messages and even cryptographic keys to
impersonate one party to the other.
message digest The result of applying a
cryptographic hash function to a message or other
data. A cryptographically secure message digest
cannot be transformed back into the original
message and cannot (or is very unlikely to) be
created from a different input. Message digests are
used to ensure that a message has not been
corrupted or altered. For example, they are used for
this purpose in digital signatures. The digital
signature includes a digest of the original message,
and the recipient prepares their own digest of the
received message. If the two digests are identical,
then the recipient can be confident that the message
has not been altered or corrupted.
MIME Acronym for Multipurpose Internet Mail
Extensions. A standard for transmitting formatted
text, hypertext, graphics, and audio in electronic mail
messages over the Internet.
PKI See public key infrastructure (PKI).
Glossary
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
40plaintext See cleartext.
plug-in A code module that uses a standard
interface to implement certain features of a program
or extend the program. See also CDSA plug-in.
private key A cryptographic key that must be kept
secret. Whereas a pair of identical private keys can
be used as symmetric keys, asymmetric keys consist
of one private key and one public key.
pseudorandom number A number generated by
an algorithm that produces a series of numbers with
no discernible pattern. It should be impossible or
nearly impossible to deduce the algorithm from such
a series. However, unlike a truly random number
generator, a pseudorandom number generator
always produces the same series if the algorithm is
given the same starting value or values.
public key A cryptographic key that can be shared
or made public without compromising the
cryptographic method. See also public key
cryptography.
public key certificate See digital certificate.
public key cryptography A cryptographic method
using asymmetric keys in which one key is made
public while the other (the private key ) is kept
secure. Data encrypted with one key must be
decrypted with the other. If the public key is used
to encrypt the data, only the holder of the private
key can decrypt it; therefore the data is secure from
unauthorized use. If the private key is used to
encrypt the data, anyone with the public key can
decrypt it. Because only the holder of the private
key could have encrypted it, however,such data can
be used for authentication. See also digital certificate;
digital signature.
public key infrastructure (PKI) As defined by the
X.509 standard, a PKI isthe set of hardware,software,
people, policies, and procedures needed to create,
manage, store, distribute, and revoke digital
certificates that are based on public key
cryptography.
quantum computer A computer in which the logic
gates are based on quantum phenomena such as
electron spin rather than mechanical or conventional
electronic components. Because of the superposition
of quantum states(a consequence of the Heisenberg
Uncertainty Principle), a properly designed quantum
computer can in principle perform simultaneously
certain types of calculations that require a huge
number of sequential operations in a classic
computer. Consequently, factoring large numbers
should be several orders of magnitude faster on a
quantum computer than on present-day
supercomputers. Because the strength of most
modern cryptographic methods depends on the
difficulty of making such calculations, a practical
quantumcomputer would breakmost cryptographic
schemes in common use. Although small
proof-of-concept quantum computers have been
constructed, no such machine capable of solving
practical problems has yet been demonstrated.
Randomization Services An iOS API that produces
cryptographically secure pseudorandom numbers.
root certificate A certificate that can be verified
without recourse to another certificate. Rather than
being signed by a further certification authority (CA),
a root certificate is verified using the widely available
public key of the CA that issued the root certificate.
Compare anchor certificate.
root certification authority The certification
authority that owns the root certificate.
Glossary
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
41RSA encryption A system of public key
cryptography, named for its inventors: Ron Rivest,
Adi Shamir, and Leonard Adleman. The RSA
algorithm takestwo large prime numbers, findstheir
product, and then derives asymmetric keysfrom the
prime numbers and their product. Because the public
key includes the product, the private key could be
derived from the public key if the product could be
factored. No easy method for factoring products of
large prime numbers is currently known, but it has
not been mathematically proven that no such
method is possible. Therefore, the discovery of a fast
way to factor such numbers, or the development of
quantum computers, would break RSA.
secret key A cryptographic key that cannot be made
public without compromising the security of the
cryptographic method. In symmetric key
cryptography , the secret key is used both to encrypt
and decrypt the data. In asymmetric key
cryptography , a (secret) private key is paired with a
public key. Whichever one is used to encrypt the
data, the other is used to decrypt it. See also public
key; public key cryptography.
Secure Sockets Layer(SSL) A protocol that provides
secure communication over a TCP/IP connection
such as the Internet. It uses digital certificates for
authentication and digital signatures to ensure
message integrity, and can use public key
cryptography to ensure data privacy. An SSL service
negotiates a secure session between two
communicating endpoints. SSL is built into all major
browsers and web servers. SSL has been superseded
by Transport Layer Security (TLS).
secure storage Storage of encrypted data on disk
or another medium that persists when the power is
turned off.
Secure Transport The OS X and iPhone
implementation of Secure Sockets Layer (SSL) and
Transport Layer Security (TLS), used to create secure
connections over TCP/IP connections such as the
Internet. On OS X, Secure Transport includes an API
that is independent of the underlying transport
protocol. The CFNetwork and URL Loading System
APIs use the services of Secure Transport.
session key A cryptographic key calculated or
issued for use only for the duration of a specific
communication session. Session keys are used, for
example, by the Diffie-Hellman key exchange and
Kerberos protocols.
S/MIME Acronym for Secure Multipurpose Internet
Mail Extensions. A specification that adds digital
signature authentication and encryption to electronic
mail messages in MIME format.
SSL See Secure Sockets Layer (SSL).
strength A measure of the amount of effort
required to break a security system. For example,
the strength of RSA encryption is believed to be
related to the difficulty of factoring the product of
two large prime numbers.
symmetric keys A pair of identical keys used to
encrypt and decrypt data. See also private key.
Compare asymmetric keys.
TLS See Transport Layer Security (TLS).
Transport Layer Security (TLS) A protocol that
provides secure communication over a TCP/IP
connection such as the Internet. It uses digital
certificates for authentication and digital signatures
to ensure message integrity, and can use public key
cryptography to ensure data privacy. A TLS service
negotiates a secure session between two
communicating endpoints. TLS is built into recent
versions of all major browsers and web servers. TLS
Glossary
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
42is the successor to SSL. Although the TLS and SSL
protocols are not interoperable, Secure Transport
can back down to SSL 3.0 if a TLS session cannot be
negotiated.
trust See level of trust.
trust policy A set of rules that specify the
appropriate uses for a certificate that has a specific
level of trust. For example, the trust policy for a
browser might state that if a certificate has an SSL
certificate extension, but the certificate has expired,
the user should be prompted for permission before
a secure session is opened with a web server.
URL Loading System An API that you can use to
access the contents of http://, https://, and ftp://
URLs. Because https:// websites use Secure Sockets
Layer (SSL) or Transport Layer Security (TLS) to
protect data transfers, you can use the URL Loading
System as a secure transport API. The URL Loading
System is layered on top of CFNetwork.
X.509 A standard for digital certificates promulgated
by the International Telecommunication Union (ITU).
The X.509 ITU standard is widely used on the Internet
and throughout the information technology industry
for designing secure applications based on a public
key infrastructure (PKI).
Glossary
2012-09-19 | © 2012 Apple Inc. All Rights Reserved.
43Apple Inc.
© 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, FileVault, iPhone,
Keychain, Numbers, Objective-C, OS X, and Xcode
are trademarks of Apple Inc., registered in the
U.S. and other countries.
UNIX is a registered trademark of The Open
Group.
iOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
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.
Resource Programming
GuideContents
About Resources 5
At a Glance 5
Nib Files Store the Objects of Your Application’s User Interface 6
String Resources Containing Localizable Text 6
Images, Sounds, and Movies Represent Pre-rendered Content 6
Property Lists and Data Files Separate Data from Code 7
iOS Supports Device-Specific Resources 7
See Also 8
Nib Files 9
Anatomy of a Nib File 9
About Your Interface Objects 10
About the File’s Owner 10
About the First Responder 10
About the Top-Level Objects 11
About Image and Sound Resources 11
Nib File Design Guidelines 11
The Nib Object Life Cycle 12
The Object Loading Process 12
Managing the Lifetimes of Objects from Nib Files 15
Top-level Objects in OS X May Need Special Handling 17
Legacy Patterns 17
Action Methods 20
Built-In Support For Nib Files 21
The Application Loads the Main Nib File 22
Each View Controller Manages its Own Nib File 22
Document and Window Controllers Load Their Associated Nib File 22
Loading Nib Files Programmatically 23
Loading Nib Files Using NSBundle 23
Getting a Nib File’s Top-Level Objects 25
Loading Nib Files Using UINib and NSNib 27
Replacing Proxy Objects at Load Time 28
Accessing the Contents of a Nib File 30
Connecting Menu Items Across Nib Files 30
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
2String Resources 32
Creating Strings Resource Files 33
Choosing Which Strings to Localize 33
About the String-Loading Macros 34
Using the genstrings Tool to Create Strings Files 35
Creating Strings Files Manually 36
Detecting Non-localizable Strings 37
Loading String Resources Into Your Code 37
Using the Core Foundation Framework 38
Using the Foundation Framework 39
Examples of Getting Strings 39
Advanced Strings File Tips 40
Searching for Custom Functions With genstrings 40
Formatting String Resources 41
Using Special Characters in String Resources 41
Debugging Strings Files 42
Image, Sound, and Video Resources 43
Images and Sounds in Nib Files 43
Loading Image Resources 43
Loading Images in Objective-C 44
Loading Images Using Quartz 45
Specifying High-Resolution Images in iOS 46
Data Resource Files 48
Property List Files 48
OS X Data Resource Files 48
Document Revision History 50
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
3
ContentsTables and Listings
Nib Files 9
Listing 1-1 Loading a nib file from the current bundle 24
Listing 1-2 Loading a nib in an iPhone application 25
Listing 1-3 Using outlets to get the top-level objects 25
Listing 1-4 Getting the top-level objects from a nib file at runtime 26
Listing 1-5 Loading a nib file using NSNib 28
Listing 1-6 Replacing placeholder objects in a nib file 29
String Resources 32
Table 2-1 Common parameters found in string-loading routines 37
Listing 2-1 A simple strings file 32
Listing 2-2 Strings localized for English 36
Listing 2-3 Strings localized for German 36
Listing 2-4 Strings with formatting characters 41
Image, Sound, and Video Resources 43
Listing 3-1 Loading an image resource 44
Listing 3-2 Using data providers to load image resources 45
Data Resource Files 48
Table 4-1 Other resource types 49
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
4Applied to computer programs, resources are data filesthat accompany a program’s executable code. Resources
simplify the code you have to write by moving the creation of complex sets of data or graphical content outside
of your code and into more appropriate tools. For example, rather than creating images pixel by pixel using
code, it is much more efficient (and practical) to create them in an image editor. To take advantage of a resource,
all your code has to do is load it at runtime and use it.
In addition to simplifying your code, resources are also an intimate part of the internationalization process for
all applications. Rather than hard-coding strings and other user-visible content in your application, you can
place that content in external resource files. Localizing your application then becomes a simple process of
creating new versions of each resource file for each supported language. The bundle mechanism used in both
OS X and iOS provides a way to organize localized resources and to facilitate the loading of resource files that
match the user’s preferred language.
This document provides information about the types of resources supported in OS X and iOS and how you
use those resources in your code. This document does not focus on the resource-creation process. Most
resources are created using either third-party applications or the developer tools provided in the
/Developer/Applications directory. In addition, although this document refers to the use of resources in
applications, the information also applies to other types of bundled executables, including frameworks and
plug-ins.
Before reading this document, you should be familiar with the organizationalstructure imposed by application
bundles. Understanding this structure makes it easier to organize and find the resource files your application
uses. For information on the structure of bundles, see Bundle Programming Guide .
At a Glance
Applications can contain many types of resources but there are several that are supported directly by iOS and
OS X.
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
5
About ResourcesNib Files Store the Objects of Your Application’s User Interface
Nib files are the quintessential resource type used to create iOS and Mac apps. A nib file is a data archive that
essentially contains a set of freeze-dried objects that you want to recreate at runtime. Nib files are used most
commonly to store preconfigured windows, views, and other visually oriented objects but they can also store
nonvisual objects such as controllers.
You create nib files using the Interface Builder application, which provides a graphical assembly area for
assembling your objects. When you subsequently load a nib file into your application, the nib-loading code
instantiates each object in the file and restores it to the state you specified in Interface Builder. Thus, what you
see in Interface Builder is really what you get in your application at runtime.
Relevant Chapters: “Nib Files” (page 9)
String Resources Containing Localizable Text
Text is a prominent part of most user interfaces but also a resource that is most affected by localization changes.
Rather than hard-coding text into your code, iOS and OS X support the storage of user-visible text in strings
files, which are human-readable text files (in the UTF-16 encoding) containing a set of string resources for an
application. (The use of the plural “strings” in is deliberate and due to the .strings filename extension used
by files of that type.) Strings files greatly simplify the internationalization and localization process by allowing
you to write your code once and then load the appropriately localized text from resource files that can be
changed easily.
The Core Foundation and Foundation frameworks provide the facilities for loading text from strings files.
Applications that use these facilities can also take advantage of tools that come with Xcode to generate and
maintain these resource files throughout the development process.
Relevant Chapters: “String Resources” (page 32)
Images, Sounds, and Movies Represent Pre-rendered Content
Images, sound, and movie resources play an important role in iOS and Mac apps. Images are responsible for
creating the unique visual style used by each operating system; they also help simplify your drawing code for
complex visual elements. Sound and movie files similarly help enhance the overall user experience of your
application while simplifying the code needed to create that experience. Both operating systems provide
extensive support for loading and presenting these types of resources in your applications.
About Resources
At a Glance
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
6Relevant Chapters: “Image, Sound, and Video Resources” (page 43)
Property Lists and Data Files Separate Data from Code
A property list file is a structured file used to store string, number, Boolean, date, and raw data values. Data
items in the file are organized using array and dictionary structures with most items associated with a unique
key. The system uses property lists to store simple data sets. For example, the Info.plist file found in nearly
every application is an example of a property list file. You can also use property list files for simple data storage
needs.
In addition to property lists, OS X supports some specially structured files for specific uses. For example,
AppleScript data and user help are stored using specially formatted data files. You can also create custom data
files of your own.
Relevant Chapters: “Data Resource Files” (page 48)
iOS Supports Device-Specific Resources
In iOS 4.0 and later, it is possible to mark individual resource files as usable only on a specific type of device.
This capability simplifies the code you have to write for Universal applications. Rather than creating separate
code paths to load one version of a resource file for iPhone and a different version of the file for iPad, you can
let the bundle-loading routines choose the correct file. All you have to do is name your resource files
appropriately.
To associate a resource file with a particular device, you add a custom modifier string to its filename. The
inclusion of this modifier string yields filenames with the following format:
.
The string represents the original name of the resource file. It also represents the name you use
when accessing the file from your code. Similarly, the string is the standard filename
extension used to identify the type of the file. The string is a case-sensitive string that can be one of
the following values:
● ~ipad - The resource should be loaded on iPad devices only.
● ~iphone - The resource should be loaded on iPhone or iPod touch devices only.
About Resources
At a Glance
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
7You can apply device modifiers to any type of resource file. For example, suppose you have an image named
MyImage.png. To specify different versions of the image for iPad and iPhone, you would create resource files
with the names MyImage~ipad.png and MyImage~iphone.png and include them both in your bundle. To
load the image, you would continue to refer to the resource as MyImage.png in your code and let the system
choose the appropriate version, as shown here:
UIImage* anImage = [UIImage imageNamed:@"MyImage.png"];
On an iPhone or iPod touch device, the system loads the MyImage~iphone.png resource file, while on iPad,
it loadsthe MyImage~ipad.png resource file. If a device-specific version of a resource is not found, the system
falls back to looking for a resource with the original filename, which in the preceding example would be an
image named MyImage.png.
See Also
The following Apple Developer documents are conceptually related to Resource Programming Guide :
● Bundle Programming Guide describes the bundle structure used by applications to store executable code
and resources.
●
Internationalization Programming Topics describes the process of preparing an application (and its
resources) for translation into other languages.
●
Interface Builder User Guide describes the application used to create nib file resources.
● Property List Programming Guide describes the facilities in place for loading property-list resource files
into a Cocoa application.
● Property List Programming TopicsforCore Foundation describesthe facilitiesinplace forloadingproperty-list
resource files into a C-based application.
About Resources
See Also
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
8Nib files play an important role in the creation of applications in OS X and iOS. With nib files, you create and
manipulate your user interfaces graphically, using Xcode, instead of programmatically. Because you can see
the results of your changesinstantly, you can experiment with different layouts and configurations very quickly.
You can also change many aspects of your user interface later without rewriting any code.
For applications built using the AppKit or UIKit frameworks, nib files take on an extra significance. Both of these
frameworks support the use of nib files both for laying out windows, views, and controls and for integrating
those items with the application’s event handling code. Xcode works in conjunction with these frameworks
to help you connect the controls of your user interface to the objects in your project that respond to those
controls. This integration significantly reduces the amount of setup that is required after a nib file is loaded
and also makes it easy to change the relationships between your code and user interface later.
Note: Although you can create an Objective-C application without using nib files, doing so is very
rare and not recommended. Depending on your application, avoiding nib files might require you to
replace large amounts of framework behavior to achieve the same results you would get using a
nib file.
Anatomy of a Nib File
A nib file describes the visual elements of your application’s user interface, including windows, views, controls,
and many others. It can also describe non-visual elements,such asthe objectsin your application that manage
your windows and views. Most importantly, a nib file describes these objects exactly as they were configured
in Xcode. At runtime, these descriptions are used to recreate the objects and their configuration inside your
application. When you load a nib file at runtime, you get an exact replica of the objectsthat were in your Xcode
document. The nib-loading code instantiates the objects, configures them, and reestablishes any inter-object
connections that you created in your nib file.
The following sections describe how nib files used with the AppKit and UIKit frameworks are organized, the
types of objects found in them, and how you use those objects effectively.
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
9
Nib FilesAbout Your Interface Objects
Interface objects are what you add to an nib file to implement your user interface. When a nib is loaded at
runtime, the interface objects are the objects actually instantiated by the nib-loading code. Most new nib files
have at least one interface object by default, typically a window or menu resource, and you add more interface
objects to a nib file as part of your interface design. This is the most common type of object in a nib file and
is typically why you create nib files in the first place.
Besides representing visual objects, such as windows, views, controls, and menus, interface objects can also
represent non-visual objects. In nearly all cases, the non-visual objects you add to a nib file are extra controller
objects that your application uses to manage the visual objects. Although you could create these objects in
your application, it is often more convenient to add them to a nib file and configure them there. Xcode provides
a generic object that you use specifically when adding controllers and other non-visual objects to a nib file. It
also provides the controller objects that are typically used to manage Cocoa bindings.
About the File’s Owner
One of the most important objects in a nib file is the File’s Owner object. Unlike interface objects, the File’s
Owner object is a placeholder object that is not created when the nib file is loaded. Instead, you create this
object in your code and pass it to the nib-loading code. The reason this object is so important is that it is the
main link between your application code and the contents of the nib file. More specifically, it is the controller
object that is responsible for the contents of the nib file.
In Xcode, you can create connections between the File’s Owner and the other interface objects in your nib file.
When you load the nib file, the nib-loading code recreates these connections using the replacement object
you specify. This allows your object to reference objects in the nib file and receive messages from the interface
objects automatically.
About the First Responder
In a nib file, the First Responder is a placeholder object that represents the first object in your application’s
dynamically determined responder chain. Because the responder chain of an application cannot be determined
at design time, the First Responder placeholder acts as a stand-in target for any action messages that need to
be directed at the application’sresponder chain. Menu items commonly target the First Responder placeholder.
For example, the Minimize menu item in the Window menu hides the frontmost window in an application,
not just a specific window, and the Copy menu item should copy the current selection, not just the selection
of a single control or view. Other objects in your application can target the First Responder as well.
When you load a nib file into memory, there is nothing you have to do to manage or replace the First Responder
placeholder object. The AppKit and UIKit frameworks automatically set and maintain the first responder based
on the application’s current configuration.
Nib Files
Anatomy of a Nib File
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
10For more information about the responder chain and how it is used to dispatch events in AppKit–based
applications,see “Event Architecture” inCocoa Event Handling Guide . For information about the responder chains
and handling actions in iPhone applications, see Event Handling Guide for iOS .
About the Top-Level Objects
When your program loads a nib file, Cocoa recreates the entire graph of objects you created in Xcode. This
object graph includes all of the windows, views, controls, cells, menus, and custom objects found in the nib file.
The top-level objects are the subset of these objects that do not have a parent object. The top-level objects
typically include only the windows, menubars, and custom controller objects that you add to the nib file.
(Objects such as File’s Owner, First Responder, and Application are placeholder objects and not considered
top-level objects.)
Typically, you use outlets in the File’s Owner object to store references to the top-level objects of a nib file. If
you do not use outlets, however, you can retrieve the top-level objects from the nib-loading routines directly.
You should always keep a pointer to these objects somewhere because your application is responsible for
releasing them when it is done using them. For more information about the nib object behavior at load time,
see “Managing the Lifetimes of Objects from Nib Files” (page 15).
About Image and Sound Resources
In Xcode, you can refer to external image and sound resources from within the contents of your nib files. Some
controls and views are able to display images or play sounds as part of their default configuration. The Xcode
library provides access to the image and sound resources of your Xcode projects so that you can link your nib
files to these resources. The nib file does not store these resources directly. Instead, it stores the name of the
resource file so that the nib-loading code can find it later.
When you load a nib file that contains references to image or sound resources, the nib-loading code reads the
actual image or sound file into memory and and caches it. In OS X, image and sound resources are stored in
named caches so that you can access them later if needed. In iOS, only image resources are stored in named
caches. To access images, you use the imageNamed: method of NSImage or UIImage, depending on your
platform. To access cached sounds in OS X, use the soundNamed: method of NSSound.
Nib File Design Guidelines
When creating your nib files, it is important to think carefully about how you intend to use the objects in that
file. A very simple application might be able to store all of its user interface components in a single nib file,
but for most applications, it is better to distribute components across multiple nib files. Creating smaller nib
files lets you load only those portions of your interface that you need immediately. They also make it easier to
debug any problems you might encounter, since there are fewer places to look for problems.
Nib Files
Nib File Design Guidelines
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
11When creating your nib files, try to keep the following guidelines in mind:
● Design your nib files with lazy loading in mind. Plan on loading nib files that contain only those objects
you need right away.
●
In the main nib file for an OS X application, considerstoring only the application menu bar and an optional
application delegate object in the nib file. Avoid including any windows or user-interface elements that will
not be used until after the application has launched. Instead, place those resources in separate nib files
and load them as needed after launch.
● Store repeated user-interface components (such as document windows) in separate nib files.
● For a window or menu that is used only occasionally,store it in a separate nib file. By storing it in a separate
nib file, you load the resource into memory only if it is actually used.
● Make the File’s Owner the single point-of-contact for anything outside of the nib file; see “Accessing the
Contents of a Nib File” (page 30).
The Nib Object Life Cycle
When a nib file is loaded into memory, the nib-loading code takes several steps to ensure the objects in the
nib file are created and initialized properly. Understanding these steps can help you write better controller
code to manage your user interfaces.
The Object Loading Process
When you use the methods of NSNib or NSBundle to load and instantiate the objectsin a nib file, the underlying
nib-loading code does the following:
1. It loads the contents of the nib file and any referenced resource files into memory:
● The raw data for the entire nib object graph is loaded into memory but is not unarchived.
● Any custom image resources associated with the nib file are loaded and added to the Cocoa image
cache; see “About Image and Sound Resources” (page 11).
● Any custom sound resources associated with the nib file are loaded and added to the Cocoa sound
cache; see “About Image and Sound Resources” (page 11).
2. It unarchives the nib object graph data and instantiates the objects. How it initializes each new object
depends on the type of the object and how it was encoded in the archive. The nib-loading code uses the
following rules (in order) to determine which initialization method to use.
a. By default, objects receive an initWithCoder: message.
Nib Files
The Nib Object Life Cycle
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
12In OS X, the list of standard objects includes the views, cells, menus, and view controllers that are
provided by the system and available in the default Xcode library. It also includes any third-party
objects that were added to the library using a custom plug-in. Even if you change the class of such
an object, Xcode encodes the standard object into the nib file and then tells the archiver to swap in
your custom class when the object is unarchived.
In iOS, any object that conforms to the NSCoding protocol is initialized using the initWithCoder:
method. This includes all subclasses of UIView and UIViewController whether they are part of
the default Xcode library or custom classes you define.
b. Custom views in OS X receive an initWithFrame: message.
Custom views are subclasses of NSView for which Xcode does not have an available implementation.
Typically, these are viewsthat you define in your application and use to provide custom visual content.
Custom views do not include standard system views(like NSSlider) that are part of the default library
or part of an integrated third-party plug-in.
When it encounters a custom view, Xcode encodes a special NSCustomView object into your nib file.
The custom view object includesthe information it needsto build the real view subclass you specified.
At load time, the NSCustomView object sends an alloc and initWithFrame: message to the real
view class and then swaps the resulting view object in for itself. The net effect is that the real view
object handles subsequent interactions during the nib-loading process.
Custom views in iOS do not use the initWithFrame: method for initialization.
c. Custom objects other than those described in the preceding steps receive an init message.
3. It reestablishes all connections(actions, outlets, and bindings) between objectsin the nib file. Thisincludes
connections to File’s Owner and other placeholder objects. The approach for establishing connections
differs depending on the platform:
● Outlet connections
●
In OS X, the nib-loading code tries to reconnect outlets using the object’s own methods first. For
each outlet, Cocoa looks for a method of the form setOutletName: and calls it if such a method
is present. If it cannot find such a method, Cocoa searchesthe object for an instance variable with
the corresponding outlet name and tries to set the value directly. If the instance variable cannot
be found, no connection is created.
In OS X v10.5 and later, setting an outlet also generates a key-value observing (KVO) notification
for any registered observers. These notifications may occur before all inter-object connections
are reestablished and definitely occur before any awakeFromNib methods of the objects have
been called. Prior to v10.5, these notifications are not generated. For more information about
KVO notifications, see Key-Value Observing Programming Guide .
Nib Files
The Nib Object Life Cycle
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
13●
In iOS, the nib-loading code uses the setValue:forKey: method to reconnect each outlet.
That method similarly looks for an appropriate accessor method and falls back on other means
when that fails. For more information about how this method sets values, see its description in
NSKeyValueCoding Protocol Reference .
Setting an outlet in iOS also generates a KVO notification for any registered observers. These
notifications may occur before all inter-object connections are reestablished and definitely occur
before any awakeFromNib methods of the objects have been called. For more information about
KVO notifications, see Key-Value Observing Programming Guide .
● Action connections
●
In OS X, the nib-loading code uses the source object’s setTarget: and setAction: methods
to establish the connection to the target object. If the target object does not respond to the
action method, no connection is created. If the target object is nil, the action is handled by the
responder chain.
●
In iOS, the nib-loading code uses the addTarget:action:forControlEvents: method of
the UIControl object to configure the action. If the target is nil, the action is handled by the
responder chain.
● Bindings
●
In OS X, Cocoa usesthe bind:toObject:withKeyPath:options: method of the source object
to create the connection between it and its target object.
● Bindings are not supported in iOS.
4. It sends an awakeFromNib message to the appropriate objects in the nib file that define the matching
selector:
●
In OS X, this message is sent to any interface objects that define the method. It is also sent to the File’s
Owner and any placeholder objects that define it as well.
●
In iOS, this message is sent only to the interface objects that were instantiated by the nib-loading
code. It is not sent to File’s Owner, First Responder, or any other placeholder objects.
5. It displays any windows whose “Visible at launch time” attribute was enabled in the nib file.
The order in which the nib-loading code calls the awakeFromNib methods of objects is not guaranteed. In
OS X, Cocoa tries to call the awakeFromNib method of File’s Owner last but does not guarantee that behavior.
If you need to configure the objects in your nib file further at load time, the most appropriate time to do so is
after your nib-loading call returns. At that point, all of the objects are created, initialized, and ready for use.
Nib Files
The Nib Object Life Cycle
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
14Managing the Lifetimes of Objects from Nib Files
Each time you ask the NSBundle or NSNib class to load a nib file, the underlying code creates a new copy of
the objects in that file and returns them to you. (The nib-loading code does not recycle nib file objects from a
previous load attempt.) You need to ensure that you maintain the new object graph as long as necessary, and
disown it when you are finished with it. You typically need strong references to top-level objects to ensure
that they are not deallocated; you don’t need strong references to objects lower down in the graph because
they’re owned by their parents, and you should minimize the risk of creating strong reference cycles.
From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should
generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard
scene) which should be strong. Outlets that you create should therefore typically be weak, because:
● Outlets that you create to subviews of a view controller’s view or a window controller’s window, for
example, are arbitrary references between objects that do not imply ownership.
● The strong outlets are frequently specified by framework classes (for example, UIViewController’s
view outlet, or NSWindowController’s window outlet).
@property (weak) IBOutlet MyView *viewContainerSubview;
@property (strong) IBOutlet MyOtherClass *topLevelObject;
Note: InOS X, not all classessupport weak references; these are NSATSTypesetter, NSColorSpace,
NSFont, NSFontManager, NSFontPanel, NSImage, NSMenuView, NSParagraphStyle,
NSSimpleHorizontalTypesetter, NSTableCellView, NSTextView, NSViewController,
NSWindow, and NSWindowController, and all classes in the AV Foundation framework.
In cases where you cannot therefore specify weak, you should instead use assign:
@property (assign) IBOutlet NSTextView *textView;
Outlets may be considered private to the defining class; if you prefer, you can hide the property declarations
a class extension. For example:
// MyClass.h
@interface MyClass : MySuperclass
@end
Nib Files
Managing the Lifetimes of Objects from Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
15// MyClass.m
@interface MyClass ()
@property (weak) IBOutlet MyView *viewContainerSubview;
@property (strong) IBOutlet MyOtherClass *topLevelObject;
@end
These patterns extend to references from a container view to its subviews where you have to consider the
internal consistency of your object graph. For example, in the case of a table view cell, outlets to specific
subviews should again typically be weak. If a table view contains an image view and a text view, then these
remain valid so long as they are subviews of the table view cell itself.
Outlets should be changed to strong when the outlet should be considered to own the referenced object:
● Asindicated previously, thisis often the case with File’s Owner—top level objectsin a nib file are frequently
considered to be owned by the File’s Owner.
● You may in some situations need an object from a nib file to exist outside of its original container. For
example, you might have an outlet for a view that can be temporarily removed from itsinitial view hierarchy
and must therefore be maintained independently.
Classes that you expect to be subclassed (in particular abstract classes) expose outlets publicly so that they
can be used appropriately by subclasses (e.g. UIViewController’s view outlet). Outlets might also be
exposed where there is an expectation that consumers of the class will need to interact with the property; for
example a table view cell might expose subviews. In thislatter case, it may be appropriate to expose a read-only
public outlet that is redefined privately as read-write, for example:
// MyClass.h
@interface MyClass : UITableViewCell
@property (weak, readonly) MyType *outletName;
@end
// MyClass.m
@interface MyClass ()
@property (weak, readwrite) IBOutlet MyType *outletName;
@end
Nib Files
Managing the Lifetimes of Objects from Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
16Top-level Objects in OS X May Need Special Handling
For historical reasons, in OS X the top-level objects in a nib file are created with an additional reference count.
The Application Kit offers a couple of features that help to ensure that nib objects are properly released:
● NSWindow objects (including panels) have an isReleasedWhenClosed attribute, which if set to YES
instructs the window to release itself (and consequently all dependent objects in its view hierarchy) when
it is closed. In the nib file, you set this option through the “Release when closed” check box in the Attributes
pane of the Xcode inspector.
●
If the File’s Owner of a nib file is an NSWindowController object (the default in document nibs in
document-based applications—recall that NSDocument manages an instance of NSWindowController)
or an NSViewController object, it automatically disposes of the windows it manages.
If the File’s Owner is not an instance of NSWindowController or NSViewController, then you need to
decrement the reference count of the top level objects yourself. With manual reference counting, it was possible
to achieve this by sending top-level objects a release message. You cannot do this with ARC. Instead, you
cast references to top-level objects to a Core Foundation type and use CFRelease. (If you don’t want to have
outlets to all top-level objects, you can use the instantiateNibWithOwner:topLevelObjects: method
of the NSNib class to get an array of a nib file’s top-level objects.)
Legacy Patterns
Prior to ARC, the rules for managing nib objects are different from those described above. How you manage
the objects depends on the platform and on the memory model in use. Whichever platform you develop for,
you should define outlets using the Objective-C declared properties feature.
The general form of the declaration should be:
@property (attributes) IBOutlet UserInterfaceElementClass *anOutlet;
Because the behavior of outlets depends on the platform, the actual declaration differs:
● For iOS, you should use:
@property (nonatomic, retain) IBOutlet UserInterfaceElementClass *anOutlet;
● For OS X, you should use:
@property (assign) IBOutlet UserInterfaceElementClass *anOutlet;
Nib Files
Managing the Lifetimes of Objects from Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
17You should then either synthesize the corresponding accessor methods, or implement them according to the
declaration, and (in iOS) release the corresponding variable in dealloc.
This pattern also works if you use the modern runtime and synthesize the instance variables, so it remains
consistent across all situations.
Managing Nib Objects in iOS
Top-Level Objects
Objects in the nib file are created with a retain count of 1 and then autoreleased. As it rebuilds the object
hierarchy, UIKit reestablishes connections between the objects using setValue:forKey:, which uses the
available setter method or retains the object by default if no setter method is available. This means that
(assuming you follow the pattern shown above) any object for which you have an outlet remains valid. If there
are any top-level objects you do not store in outlets, however, you must retain either the array returned by
the loadNibNamed:owner:options: method or the objects inside the array to prevent those objects from
being released prematurely.
Memory Warnings
When a view controller receives a memory warning (didReceiveMemoryWarning), it should relinquish
ownership of resources that are currently not needed and that can be recreated later if required. One such
resource is the view controller's view itself. If it does not have a superview, the view is disposed of (in its
implementation of didReceiveMemoryWarning, UIViewController invokes [self setView:nil]).
Because outlets to elements within the nib file are typically retained, however, even though the main view is
disposed of, absent any further action the outlets are not disposed of. This is not in and of itself a problem—if
and when the main view is reloaded, they will simply be replaced—but it does mean that the beneficial effect
of the didReceiveMemoryWarning is reduced. To ensure that you properly relinquish ownership of outlets,
in your custom view controller class you can implement viewDidUnload to invoke your accessor methods
to set outlets to nil.
- (void)viewDidUnload {
self.anOutlet = nil;
[super viewDidUnload];
}
Nib Files
Managing the Lifetimes of Objects from Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
18Managing Nib Objects in OS X
In OS X, the File’s Owner of a nib file is by default responsible for releasing the top-level objects in a nib file as
well as any non-object resources created by the objects in the nib. The release of the root object of an object
graph sets in motion the release of all dependent objects. The File’s Owner of an application’s main nib file
(which containsthe application menu and possibly other items) isthe global application object NSApp. However,
when a Cocoa application terminates, top level objects in the main nib do not automatically get dealloc
messages just because NSApp is being deallocated. In other words, even in the main nib file, you have to
manage the memory of top-level objects.
The Application Kit offers a couple of features that help to ensure that nib objects are properly released:
● NSWindow objects (including panels) have an isReleasedWhenClosed attribute, which if set to YES
instructs the window to release itself (and consequently all dependent objects in its view hierarchy) when
it is closed. In the nib file, you set this option through the “Release when closed” check box in the Attributes
pane of the inspector.
●
If the File’s Owner of a nib file is an NSWindowController object (the default in document nibs in
document-based applications—recall that NSDocument manages an instance of NSWindowController),
it automatically disposes of the windows it manages.
So in general, you are responsible for releasing top-level objects in a nib file. But in practice, if your nib file’s
owner is an instance of NSWindowController it releases the top-level object for you. If one of your objects
loads the nib itself (and the owner is not an instance of NSWindowController), you can define outlets to
each top-level object so that at the appropriate time you can release them using those references. If you don’t
wantto have outletsto alltop-level objects, you can use the instantiateNibWithOwner:topLevelObjects:
method of the NSNib class to get an array of a nib file’s top-level objects.
The issue of responsibility for nib object disposal becomes clearer when you consider the various kinds of
applications. Most Cocoa applications are of two kinds: single window applications and document-based
applications. In both cases, memory management of nib objects is automatically handled for you to some
degree. With single-window applications, objects in the main nib file persist through the runtime life of the
application and are released when the application terminates; however, dealloc is not guaranteed to be
automatically invoked on objects from the main nib file when an application terminates. In document-based
applications each document window is managed by an NSWindowController object which handles memory
management for a document nib file.
Some applications may have a more complex arrangement of nib files and top-level objects. For example, an
application could have multiple nib files with multiple window controllers, loadable panels, and inspectors.
But in most of these cases, if you use NSWindowController objects to manage windows and panels or if you
set the “released when closed” window attribute, memory management is largely taken care of. If you decide
against using window controllers and do not want to set the “release when closed” attribute, you should
Nib Files
Managing the Lifetimes of Objects from Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
19explicitly free your nib file’s windows and other top-level objects when the window is closed. Also, if your
application uses an inspector panel, (after being lazily loaded) the panel should typically persist throughout
the lifetime of the application—there is no need to dispose of the inspector and its resources.
Action Methods
Broadly speaking, action methods(see Target-Action in OS X or Target-Action in iOS) are methodsthat are typically
invoked by another object in a nib file. Action methods use type qualifier IBAction, which is used in place of
the void return type, to flag the declared method as an action so that Xcode is aware of it.
@interface MyClass
- (IBAction)myActionMethod:(id)sender;
@end
You may choose to regard action methods as being private to your class and thus not declare them in the
public @interface. (Because Xcode parses implementation files, there is no need to declare them in the
header.)
// MyClass.h
@interface MyClass
@end
// MyClass.m
@implementation MyClass
- (IBAction)myActionMethod:(id)sender {
// Implementation.
}
@end
You should typically not invoke an action method programmatically. If your class needs to perform the work
associated with the action method, then you should factor the implementation into a different method that
is then invoked by the action method.
// MyClass.h
Nib Files
Action Methods
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
20@interface MyClass
@end
// MyClass.m
@interface MyClass (PrivateMethods)
- (void)doSomething;
- (void)doWorkThatRequiresMeToDoSomething;
@end
@implementation MyClass
- (IBAction)myActionMethod:(id)sender {
[self doSomething];
}
- (void)doSomething {
// Implementation.
}
- (void)doWorkThatRequiresMeToDoSomething {
// Pre-processing.
[self doSomething];
// Post-processing.
}
@end
Built-In Support For Nib Files
The AppKit and UIKit frameworks both provide a certain amount of automated behavior for loading and
managing nib files in an application. Both frameworks provide infrastructure for loading an application’s main
nib file. In addition, the AppKit framework providessupport for loading other nib filesthrough the NSDocument
and NSWindowController classes. The following sections describe the built-in support for nib files, how you
can take advantage of it, and ways to modify that support in your own applications.
Nib Files
Built-In Support For Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
21The Application Loads the Main Nib File
Most of the Xcode project templates for applications come preconfigured with a main nib file already in place.
All you have to do is modify this default nib file in the nib file and build your application. At launch time, the
application’s default configuration data tells the application object where to find this nib file so that it can load
it. In applications based on either AppKit and UIKit, this configuration data is located in the application’s
Info.plist file. When an application is first loaded, the default application startup code looks in the
Info.plist file for the NSMainNibFile key. If it findsit, it looksin the application bundle for a nib file whose
name (with or without the filename extension) matches the value of that key and loads it.
Each View Controller Manages its Own Nib File
The UIViewController (iOS) and NSViewController (OS X) classessupport the automatic loading of their
associated nib file. If you specify a nib file when creating the view controller, that nib file isloaded automatically
when you try to access the view controller’s view. Any connections between the view controller and the nib
file objects are created automatically, and in iOS, the UIViewController object also receives additional
notifications when the views are finally loaded and displayed on screen. To help manage memory better, the
UIViewController class also handles the unloading of its nib file (as appropriate) during low-memory
conditions.
For more information about how you use the UIViewController class and how you configure it, see View
Controller Programming Guide for iOS .
Document and Window Controllers Load Their Associated Nib File
In the AppKit framework, the NSDocument class works with the default window controller to load the nib file
containing your document window. The windowNibName method of NSDocument is a convenience method
that you can use to specify the nib file containing the corresponding document window. When a new document
is created, the document object passes the nib file name you specify to the default window controller object,
which loads and manages the contents of the nib file. If you use the standard templates provided by Xcode,
the only thing you have to do is add the contents of your document window to the nib file.
The NSWindowController class also provides automatic support for loading nib files. If you create custom
window controllers programmatically, you have the option of initializing them with an NSWindow object or
with the name of a nib file. If you choose the latter option, the NSWindowController class automatically
loads the specified nib file the first time a client tries to access the window. After that, the window controller
keeps the window around in memory; it does not reload it from the nib file, even if the window’s “Release
when closed” attribute is set.
Nib Files
Built-In Support For Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
22Important: When using either NSWindowController or NSDocument to load windows automatically, it
is important that your nib file be configured correctly. Both classes include a window outlet that you must
connect to the window you want them to manage. If you do not connect this outlet to a window object,
the nib file is loaded but the document or window controller does not display the window. For more
information about the Cocoa document architecture, see Document-Based App Programming Guide for
Mac .
Loading Nib Files Programmatically
Both OS X and iOS provide convenience methods for loading nib files into your application. Both the AppKit
and UIKit framework define additional methods on the NSBundle class that support the loading of nib files.
In addition, the AppKit framework also provides the NSNib class, which provides similar nib-loading behavior
as NSBundle but offers some additional advantages that might be useful in specific situations.
As you plan out your application, make sure any nib files you plan to load manually are configured in a way
that simplifies the loading process. Choosing an appropriate object for File’s Owner and keeping your nib files
small can greatly improve their ease of use and memory efficiency. For more tips on configuring your nib files,
see “Nib File Design Guidelines” (page 11).
Loading Nib Files Using NSBundle
The AppKit and UIKit frameworks define additional methods on the NSBundle class (using Objective-C
categories) to support the loading of nib file resources. The semantics for how you use the methods differs
between the two platforms as doesthe syntax for the methods. In AppKit, there are more optionsfor accessing
bundles in general and so there are correspondingly more methods for loading nib files from those bundles.
In UIKit, applications can load nib files only from their main bundle and so fewer options are needed. The
methods available on the two platforms are as follows:
● AppKit
● loadNibNamed:owner: class method
● loadNibFile:externalNameTable:withZone: class method
● loadNibFile:externalNameTable:withZone: instance method
● UIKit
● loadNibNamed:owner:options: instance method
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
23Whenever loading a nib file, you should always specify an object to act as File’s Owner of that nib file. The role
of the File’s Owner is an important one. It is the primary interface between your running code and the new
objects that are about to be created in memory. All of the nib-loading methods provide a way to specify the
File’s Owner, either directly or as a parameter in an options dictionary.
One of the semantic differences between the way the AppKit and UIKit frameworks handle nib loading is the
way the top-level nib objects are returned to your application. In the AppKit framework, you must explicitly
request them using one of the loadNibFile:externalNameTable:withZone: methods. In UIKit, the
loadNibNamed:owner:options: method returns an array of these objects directly. The simplest way to
avoid having to worry about the top-level objects in either case is to store them in outlets of your File’s Owner
object and to make sure the setter methods for those outlets retain their values. Because each platform uses
different retain semantics, however, you must be sure to send the proper retain or release messages when
appropriate. For information about the retention semantics for nib objects, see “Managing the Lifetimes of
Objects from Nib Files” (page 15).
Listing 1-1 shows a simple example of how to load a nib file using the NSBundle class in an AppKit–based
application. As soon as the loadNibNamed:owner: method returns, you can begin using any outlets that
refer to the nib file objects. In other words, the entire nib-loading process occurs within the confines of that
single call. The nib-loading methods in the AppKit framework return a Boolean value to indicate whether the
load operation was successful.
Listing 1-1 Loading a nib file from the current bundle
- (BOOL)loadMyNibFile
{
// The myNib file must be in the bundle that defines self's class.
if (![NSBundle loadNibNamed:@"myNib" owner:self])
{
NSLog(@"Warning! Could not load myNib file.\n");
return NO;
}
return YES;
}
Listing 1-2 shows an example of how to load a nib file in a UIKit–based application. In this case, the method
checks the returned array to see if the nib objects were loaded successfully. (Every nib file should have at least
one top-level object representing the contents of the nib file.) This example shows the simple case when the
nib file contains no placeholder objects other than the File’s Owner object. For an example of how to specify
additional placeholder objects, see “Replacing Proxy Objects at Load Time” (page 28).
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
24Listing 1-2 Loading a nib in an iPhone application
- (BOOL)loadMyNibFile
{
NSArray* topLevelObjs = nil;
topLevelObjs = [[NSBundle mainBundle] loadNibNamed:@"myNib" owner:self
options:nil];
if (topLevelObjs == nil)
{
NSLog(@"Error! Could not load myNib file.\n");
return NO;
}
return YES;
}
Note: If you are developing a Universal application for iOS, you can use the device-specific naming
conventionsto load the correct nib file for the underlying device automatically. For more information
about how to name your nib files, see “iOS Supports Device-Specific Resources” (page 7).
Getting a Nib File’s Top-Level Objects
The easiest way to get the top-level objects of your nib file is to define outlets in the File’s Owner object along
with setter methods (or better yet, properties) for accessing those objects. This approach ensures that the
top-level objects are retained by your object and that you always have references to them.
Listing 1-3 shows the interface and implementation of a simplified Cocoa class that uses an outlet to retain
the nib file’s only top-level object. In this case, the only top-level object in the nib file is an NSWindow object.
Because top-level objects in Cocoa have an initial retain count of 1, an extra release message is included. This
is fine because by the time the release call is made, the property has already been retained the window. You
would not want to release top-level objects in this manner in an iPhone application.
Listing 1-3 Using outlets to get the top-level objects
// Class interface
@interface MyController : NSObject {
NSWindow *window;
}
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
25@property(retain) IBOutlet NSWindow *window;
- (void)loadMyWindow;
@end
// Class implementation
@implementation MyController
// The synthesized property retains the window automatically.
@synthesize window;
- (void)loadMyWindow
{
[NSBundle loadNibNamed:@"myNib" owner:self];
// The window starts off with a retain count of 1
// and is then retained by the property, so add an extra release.
[window release];
}
@end
If you do not want to use outlets to store references to your nib file’s top-level objects, you must retrieve those
objects manually in your code. The technique for obtaining the top-level objects differs depending on the
target platform. In OS X, you must ask for the objects explicitly, whereas in iOS they are returned to you
automatically.
Listing 1-4 showsthe processfor getting the top-level objects of a nib file in OS X. This method places a mutable
array into the nameTable dictionary and associatesit with the NSNibTopLevelObjects key. The nib-loading
code looks for this array object and, if present, places the top-level objects in it. Because each object starts
with a retain count of 1 before it is added to the array, simply releasing the array is not enough to release the
objects in the array as well. As a result, this method sends a release message to each of the objects to ensure
that the array is the only entity holding a reference to them.
Listing 1-4 Getting the top-level objects from a nib file at runtime
- (NSArray*)loadMyNibFile
{
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
26NSBundle* aBundle = [NSBundle mainBundle];
NSMutableArray* topLevelObjs = [NSMutableArray array];
NSDictionary* nameTable = [NSDictionary dictionaryWithObjectsAndKeys:
self, NSNibOwner,
topLevelObjs, NSNibTopLevelObjects,
nil];
if (![aBundle loadNibFile:@"myNib" externalNameTable:nameTable withZone:nil])
{
NSLog(@"Warning! Could not load myNib file.\n");
return nil;
}
// Release the objects so that they are just owned by the array.
[topLevelObjs makeObjectsPerformSelector:@selector(release)];
return topLevelObjs;
}
Obtaining the top-level objects in an iPhone application is much simpler and is shown in Listing 1-2 (page 25).
In the UIKit framework, the loadNibNamed:owner:options: method of NSBundle automatically returns
an array with the top-level objects. In addition, by the time the array is returned, the retain counts on the
objects are adjusted so that you do not need to send each object an extra release message. The returned array
is the only owner of the objects.
Loading Nib Files Using UINib and NSNib
The UINib (iOS) and NSNib (OS X) classes provide better performance in situations where you want to create
multiple copies of a nib file’s contents. The normal nib-loading process involves reading the nib file from disk
and then instantiating the objects it contains. However, with the UINib and NSNib classes, the nib file is read
from disk once and the contents are stored in memory. Because they are in memory, creating successive sets
of objects takes less time because it does not require accessing the disk.
Using the UINib and NSNib classes is always a two-step process. First, you create an instance of the class and
initialize it with the nib file’s location information. Second, you instantiate the contents of the nib file to load
the objects into memory. Each time you instantiate the nib file, you specify a different File’s Owner object and
receive a new set of top-level objects.
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
27Listing 1-5 shows one way to load the contents of a nib file using the NSNib class in OS X. The array returned
to you by the instantiateNibWithOwner:topLevelObjects: method comes already autoreleased. If
you intend to use that array for any period of time, you should make a copy of it.
Listing 1-5 Loading a nib file using NSNib
- (NSArray*)loadMyNibFile
{
NSNib* aNib = [[NSNib alloc] initWithNibNamed:@"MyPanel" bundle:nil];
NSArray* topLevelObjs = nil;
if (![aNib instantiateNibWithOwner:self topLevelObjects:&topLevelObjs])
{
NSLog(@"Warning! Could not load nib file.\n");
return nil;
}
// Release the raw nib data.
[aNib release];
// Release the top-level objects so that they are just owned by the array.
[topLevelObjs makeObjectsPerformSelector:@selector(release)];
// Do not autorelease topLevelObjs.
return topLevelObjs;
}
Replacing Proxy Objects at Load Time
In iOS, it is possible to create nib files that include placeholder objects besides the File’s Owner. Proxy objects
represent objects created outside of the nib file but which have some connection to the nib file’s contents.
Proxies are commonly used to support navigation controllers in iPhone applications. When working with
navigation controllers, you typically connect the File’s Owner object to some common object such as your
application delegate. Proxy objects therefore represent the parts of the navigation controller object hierarchy
that are already loaded in memory, because they were created programmatically or loaded from a different
nib file.
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
28Note: Custom placeholder objects (other than File’s Owner) are not supported in OS X nib files.
Each placeholder object you add to a nib file must have a unique name. To assign a name to an object, select
the object in Xcode and open the inspector window. The Attributes pane of the inspector contains a Name
field, which you use to specify the name for your placeholder object. The name you assign should be descriptive
of the object’s behavior or type, but really it can be anything you want.
When you are ready to load a nib file containing placeholder objects, you mustspecify the replacement objects
for any proxies when you call the loadNibNamed:owner:options: method. The options parameter of
this method accepts a dictionary of additional information. You use this dictionary to pass in the information
about your placeholder objects. The dictionary must contain the UINibExternalObjects key whose value
is another dictionary containing the name and object for each placeholder replacement.
Listing 1-6 shows a sample version of an applicationDidFinishLaunching: method that loads the
application’s main nib file manually. Because the application’s delegate object is created by the
UIApplicationMain function, this method uses a placeholder (with the name “AppDelegate”) in the main
nib file to represent that object. The proxies dictionary stores the placeholder object information and the
options dictionary wraps that dictionary.
Listing 1-6 Replacing placeholder objects in a nib file
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
NSArray* topLevelObjs = nil;
NSDictionary* proxies = [NSDictionary dictionaryWithObject:self
forKey:@"AppDelegate"];
NSDictionary* options = [NSDictionary dictionaryWithObject:proxies
forKey:UINibExternalObjects];
topLevelObjs = [[NSBundle mainBundle] loadNibNamed:@"Main" owner:self
options:options];
if ([topLevelObjs count] == 0)
{
NSLog(@"Warning! Could not load myNib file.\n");
return;
}
// Show window
[window makeKeyAndVisible];
Nib Files
Loading Nib Files Programmatically
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
29}
For more information about the options dictionary of the loadNibNamed:owner:options: method, see
NSBundle UIKit Additions Reference .
Accessing the Contents of a Nib File
Upon the successful loading a nib file, its contents become ready for you to use immediately. If you configured
outlets in your File’s Owner to point to nib file objects, you can now use those outlets. If you did not configure
your File’s Owner with any outlets, you should make sure you obtain a reference to the top-level objects in
some manner so that you can release them later.
Because outlets are populated with real objects when a nib file is loaded, you can subsequently use outlets as
you would any other object you created programmatically. For example, if you have an outlet pointing to a
window, you could send that window a makeKeyAndOrderFront: message to show it on the user’s screen.
When you are done using the objects in your nib file, you must release them like any other objects.
Important: You are responsible for releasing the top-level objects of any nib files you load when you are
finished with those objects. Failure to do so is a cause of memory leaksin many applications. After releasing
the top-level objects, it is a good idea to clear any outlets pointing to objects in the nib file by setting them
to nil. You should clear outlets associated with all of the nib file’s objects, not just the top-level objects.
Connecting Menu Items Across Nib Files
The items in an OS X application’s menu bar often need to interact with many different objects, including your
application’s documents and windows. The problem is that many of these objects cannot (or should not) be
accessed directly from the main nib file. The File’s Owner of the main nib file is always set to an instance of the
NSApplication class. And although you might be able to instantiate a number of custom objects in your
main nib file, doing so is hardly practical or necessary. In the case of document objects, connecting directly to
a specific document object is not even possible because the number of document objects can change
dynamically and can even be zero.
Most menu items send action messages to one of the following:
● A fixed object that always handles the command
● A dynamic object, such as a document or window
Nib Files
Connecting Menu Items Across Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
30Messaging fixed objects is a relatively straightforward process that is usually best handled through the
application delegate. The application delegate object assiststhe NSApplication objectin running the application
and is one of the few objects that rightfully belongs in the main nib file. If the menu item refers to an
application-level command, you can implement that command directly in the application delegate or just have
the delegate forward the message to the appropriate object elsewhere in your application.
If you have a menu item that acts on the contents of the frontmost window, you need to link the menu item
to the First Responder placeholder object. If the action method associated with the menu item is specific to
one of your objects(and not defined by Cocoa), you must add that action to the First Responder before creating
the connection.
After creating the connection, you need to implement the action method in your custom class. That object
should also implement the validateMenuItem: method to enable the menu item at appropriate times. For
more information about how the responder chain handles commands, see Cocoa Event Handling Guide .
Nib Files
Connecting Menu Items Across Nib Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
31An important part of the localization process is to localize all of the text strings displayed by your application.
By their nature, strings located in nib files can be readily localized along with the rest of the nib file contents.
Strings embedded in your code, however, must be extracted, localized, and then reinserted back into your
code. To simplify this process—and to make the maintenance of your code easier—OS X and iOS provide the
infrastructure needed to separate strings from your code and place them into resource files where they can
be localized easily.
Resource filesthat contain localizable strings are referred to as strings files because of their filename extension,
which is .strings. You can create strings files manually or programmatically depending on your needs. The
standard strings file format consists of one or more key-value pairs along with optional comments. The key
and value in a given pair are strings of text enclosed in double quotation marks and separated by an equal
sign. (You can also use a property list format for strings files. In such a case, the top-level node is a dictionary
and each key-value pair of that dictionary is a string entry.)
Listing 2-1 shows a simple strings file that contains non-localized entries for the default language. When you
need to display a string, you pass the string on the left to one of the available string-loading routines. What
you get back isthe matching value string containing the text translation that is most appropriate for the current
user. For the development language, it is common to use the same string for both the key and value, but doing
so is not required.
Listing 2-1 A simple strings file
/* Insert Element menu item */
"Insert Element" = "Insert Element";
/* Error string used for unknown error types. */
"ErrorString_1" = "An unknown error occurred.";
A typical application has at least one strings file per localization, that is, one strings file in each of the bundle’s
.lproj subdirectories. The name of the default strings file is Localizable.strings but you can create
stringsfiles with any file name you choose. Creating stringsfilesis discussed in more depth in “Creating Strings
Resource Files” (page 33).
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
32
String ResourcesNote: It is recommended that you save strings files using the UTF-16 encoding, which is the default
encoding forstandard stringsfiles. It is possible to create stringsfiles using other property-list formats,
including binary property-list formats and XML formats that use the UTF-8 encoding, but doing so
is not recommended. For more information about the standard strings file format, see “Creating
Strings Resource Files” (page 33). For more information about Unicode and its text encodings, go
to http://www.unicode.org/ or http://en.wikipedia.org/wiki/Unicode.
The loading of string resources (both localized and nonlocalized) ultimately relies on the bundle and
internationalization supportfound in bothOS X and iOS. Forinformation about bundles,see Bundle Programming
Guide . For more information about internationalization and localization,see Internationalization Programming
Topics.
Creating Strings Resource Files
Although you can create strings files manually, it is rarely necessary to do so. The easiest way to create strings
files is to write your code using the appropriate string-loading macros and then use the genstrings
command-line tool to extract those strings and create strings files for you.
The following sections describe the process of how to set up your source files to facilitate the use of the
genstrings tool. For detailed information about the tool, see genstrings man page.
Choosing Which Strings to Localize
When it comes to localizing your application’s interface, it is not always appropriate to localize every string
used by your application. Translation is a costly process, and translating strings that are never seen by the user
is a waste of time and money. Strings that are not displayed to the user, such as notification names used
internally by your application, do not need to be translated. Consider the following example:
if (CFStringHasPrefix(value, CFSTR("-")) { CFArrayAppendValue(myArray, value);};
In this example, the string “-” is used internally and is never seen by the user; therefore, it does not need to
be placed in a strings file.
The following code shows another example of a string the user would not see. The string "%d %d %s" does
not need to be localized, since the user never sees it and it has no effect on anything that the user does see.
matches = sscanf(s, "%d %d %s", &first, &last, &other);
String Resources
Creating Strings Resource Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
33Because nib files are localized separately, you do not need to include strings that are already located inside of
a nib file. Some of the strings you should localize, however, include the following:
● Strings that are programmatically added to a window, panel, view, or control and subsequently displayed
to the user. This includes strings you pass into standard routines, such as those that display alert boxes.
● Menu item title strings if those strings are added programmatically. For example, if you use custom strings
for the Undo menu item, those strings should be in a strings file.
● Error messages that are displayed to the user.
● Any boilerplate text that is displayed to the user.
● Some stringsfromyour application’sinformation property list(Info.plist) file;see Runtime Configuration
Guidelines.
● New file and document names.
About the String-Loading Macros
The Foundation and Core Foundation frameworks define the following macros to make loading strings from a
strings file easier:
● Core Foundation macros:
● CFCopyLocalizedString
● CFCopyLocalizedStringFromTable
● CFCopyLocalizedStringFromTableInBundle
● CFCopyLocalizedStringWithDefaultValue
● Foundation macros:
● NSLocalizedString
● NSLocalizedStringFromTable
● NSLocalizedStringFromTableInBundle
● NSLocalizedStringWithDefaultValue
You use these macrosin yoursource code to load stringsfrom one of your application’sstringsfiles. The macros
take the user’s current language preferences into account when retrieving the actual string value. In addition,
the genstrings tool searches for these macros and uses the information they contain to build the initial set
of strings files for your application.
For additional information about how to use these macros,see “Loading String ResourcesInto Your Code” (page
37).
String Resources
Creating Strings Resource Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
34Using the genstrings Tool to Create Strings Files
At some point during your development, you need to create the strings files needed by your code. If you wrote
your code using the Core Foundation and Foundation macros, the simplest way to create your strings files is
using the genstrings command-line tool. You can use thistool to generate a new set ofstringsfiles or update
a set of existing files based on your source code.
To use the genstrings tool, you typically provide at least two arguments:
● A list of source files
● An optional output directory
The genstrings tool can parse C, Objective-C, and Java code files with the .c, .m, or .java filename extensions.
Although not strictly required, specifying an output directory is recommended and is where genstrings
places the resulting strings files. In most cases, you would want to specify the directory containing the project
resources for your development language.
The following example shows a simple command for running the genstrings tool. This command causes
the tool to parse all Objective-C source files in the current directory and put the resulting strings files in the
en.lproj subdirectory, which must already exist.
genstrings -o en.lproj *.m
The first time you run the genstrings tool, it creates a set of new stringsfilesfor you. Subsequent runsreplace
the contents of those strings files with the current string entries found in your source code. For subsequent
runs, it is a good idea to save a copy of your current strings files before running genstrings. You can then
diff the new and old versions to determine which strings were added to (or changed in) your project. You can
then use this information to update any already localized versions of your strings files, rather than replacing
those files and localizing them again.
Within a single strings file, each key must be unique. Fortunately, the genstrings tool is smart enough to
coalesce any duplicate entries it finds. When it discovers a key string used more than once in a single strings
file, the tool merges the comments from the individual entries into one comment string and generates a
warning. (You can suppressthe duplicate entries warning with the -q option.) If the same key string is assigned
to strings in different strings files, no warning is generated.
For more information about using the genstrings tool, see the genstrings man page.
String Resources
Creating Strings Resource Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
35Creating Strings Files Manually
Although the genstrings tool is the most convenient way to create strings files, you can also create them
manually. To create a stringsfile manually, create a new file in TextEdit (or your preferred text-editing application)
and save it using the Unicode UTF-16 encoding. (When saving files, TextEdit usually chooses an appropriate
encoding by default. To force a specific encoding, you must change the save options in the application
preferences.) The contents of thisfile consists of a set of key-value pairs along with optional comments describing
the purpose of each key-value pair. Key and value strings are separated by an equal sign, and the entire entry
must be terminated with a semicolon character. By convention, comments are enclosed inside C-style comment
delimiters (/* and */) and are placed immediately before the entry they describe.
Listing 2-2 shows the basic format of a strings file. The entries in this example come from the English version
of the Localizable.strings file from the TextEdit application. The string on the left side of each equal sign
representsthe key, and the string on the rightside representsthe value. A common convention when developing
applications is to use a key name that equals the value in the language used to develop the application.
Therefore, because TextEdit was developed using the English language, the English version of the
Localizable.strings file has keys and values that match.
Listing 2-2 Strings localized for English
/* Menu item to make the current document plain text */
"Make Plain Text" = "Make Plain Text";
/* Menu item to make the current document rich text */
"Make Rich Text" = "Make Rich Text";
Listing 2-3 shows the German translation of the same entries. These entries also live inside a file called
Localizable.strings, but this version of the file is located in the German language project directory of
the TextEdit application. Notice that the keys are still in English, but the values assigned to those keys are in
German. This is because the key strings are never seen by end users. They are used by the code to retrieve the
corresponding value string, which in this case is in German.
Listing 2-3 Strings localized for German
/* Menu item to make the current document plain text */
"Make Plain Text" = "In reinen Text umwandeln";
/* Menu item to make the current document rich text */
"Make Rich Text" = "In formatierten Text umwandeln";
String Resources
Creating Strings Resource Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
36Detecting Non-localizable Strings
AppKit–based applications can take advantage of built-in support to detect strings that do not need to be
localized and those that need to be localized but currently are not. To use this built-in support, you must launch
your application from the command line. In addition to entering the path to your executable, you must also
include the name of the desired setting along with a Boolean value to indicate whether the setting should be
enabled or disabled. The available settings are as follows:
● The NSShowNonLocalizableStrings setting identifies strings that are not localizable. The strings are
logged to the shell in upper case. This option occasionally generates some false positives but is still useful
overall.
● The NSShowNonLocalizedStrings setting locates strings that were meant to be localized but could
not be found in the application’s existing strings files. You can use this setting to catch problems with
out-of-date localizations.
For example, to use the NSShowNonLocalizedStrings setting with the TextEdit application, you would
enter the following in Terminal:
/Applications/TextEdit.app/Contents/MacOS/TextEdit -NSShowNonLocalizedStrings YES
Loading String Resources Into Your Code
The Core Foundation and Foundation frameworks provide macrosfor retrieving both localized and nonlocalized
strings stored in strings files. Although the main purpose of these macros is to load strings at runtime, they
also serve a secondary purpose by acting as markers that the genstrings tool can use to locate your
application’s string resources. It is this second purpose that explains why many of the macros let you specify
much more information than would normally be required for loading a string. The genstrings tool uses the
information you provide to create or update your application’s strings files automatically. Table 2-1 lists the
types of information you can specify for these routines and describes how that information is used by the
genstrings tool.
Table 2-1 Common parameters found in string-loading routines
Parameter Description
The string used to look up the corresponding value. This string must not contain any
characters from the extended ASCII character set, which includes accented versions of
ASCII characters. If you want the initial value string to contain extended ASCII characters,
use a routine that lets you specify a default value parameter. (For information about
the extended ASCII character set, see the corresponding Wikipedia entry.)
Key
String Resources
Loading String Resources Into Your Code
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
37Parameter Description
The name of the strings file in which the specified key is located. The genstrings tool
interprets this parameter as the name of the strings file in which the string should be
placed. If no table name is provided, the string is placed in the default
Localizable.strings file. (When specifying a value for this parameter, include the
filename without the .strings extension.)
Table name
The default value to associate with a given key. If no default value is specified, the
genstrings tool uses the key string as the initial value. Default value strings may
contain extended ASCII characters.
Default
value
Translation comments to include with the string. You can use comments to provide
clues to the translation team about how a given string is used. The genstrings tool
putsthese commentsin the stringsfile and enclosesthem in C-style comment delimiters
(/* and */) immediately above the associated entry.
Comment
An NSBundle object or CFBundleRef type corresponding to the bundle containing
the stringsfile. You can use thisto load stringsfrom bundles other than your application’s
main bundle. For example, you might use this to load localized strings from a framework
or plug-in.
Bundle
When you request a string from a strings file, the string that is returned depends on the available localizations
(if any). The Cocoa and Core Foundation macros use the built-in bundle internationalization support to retrieve
the string whose localization matchesthe user’s current language preferences. Aslong as your localized resource
files are placed in the appropriate language-specific project directories, loading a string with these macros
should yield the appropriate string automatically. If no appropriate localized string resource is found, the
bundle’s loading code automatically chooses the appropriate nonlocalized string instead.
For information about internationalization in general and how to create language-specific project directories,
see Internationalization Programming Topics. For information about the bundle structure and how resource
files are chosen from a bundle directory, see Bundle Programming Guide .
Using the Core Foundation Framework
The Core Foundation framework defines a single function and several macrosfor loading localized stringsfrom
your application bundle. The CFBundleCopyLocalizedString function provides the basic implementation
for retrieving the strings. However, it is recommended that you use the following macros instead:
● CFCopyLocalizedString(key, comment)
● CFCopyLocalizedStringFromTable(key, tableName, comment)
● CFCopyLocalizedStringFromTableInBundle(key, tableName, bundle, comment)
String Resources
Loading String Resources Into Your Code
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
38● CFCopyLocalizedStringWithDefaultValue(key, tableName, bundle, value, comment)
There are several reasons to use the macros instead of the CFBundleCopyLocalizedString function. First,
the macros are easier to use for certain common cases. Second, the macros let you associate a comment string
with the string entry. Third, the macros are recognized by the genstrings tool but the
CFBundleCopyLocalizedString function is not.
For information about the syntax of the preceding macros, see CFBundle Reference .
Using the Foundation Framework
The Foundation framework defines a single method and several macros for loading string resources. The
localizedStringForKey:value:table: method of the NSBundle classloadsthe specified string resource
from a strings file residing in the current bundle. Cocoa also defines the following macros for getting localized
strings:
● NSLocalizedString(key, comment)
● NSLocalizedStringFromTable(key, tableName, comment)
● NSLocalizedStringFromTableInBundle(key, tableName, bundle, comment)
● NSLocalizedStringWithDefaultValue(key, tableName, bundle, value, comment)
As with Core Foundation, Apple recommends that you use the Cocoa convenience macros for loading strings.
The main advantage to these macros is that they can be parsed by the genstrings tool and used to create
your application’s strings files. They are also simpler to use and let you associate translation comments with
each entry.
For information about the syntax of the preceding macros, see Foundation Functions Reference . Additional
methods for loading strings are also defined in NSBundle Class Reference .
Examples of Getting Strings
The following examples demonstrate the basic techniques for using the Foundation and Core Foundation
macros to retrieve strings. Each example assumes that the current bundle contains a strings file with the name
Custom.strings that has been translated into French. This translated file includes the following strings:
/* A comment */
"Yes" = "Oui";
"The same text in English" = "Le même texte en anglais";
String Resources
Loading String Resources Into Your Code
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
39Using the Foundation framework, you can get the value of the “Yes” string using the
NSLocalizedStringFromTable macro, as shown in the following example:
NSString* theString;
theString = NSLocalizedStringFromTable (@"Yes", @"Custom", @"A comment");
Using the Core Foundation framework, you could get the same string using the
CFCopyLocalizedStringFromTable macro, as shown in this example:
CFStringRef theString;
theString = CFCopyLocalizedStringFromTable(CFSTR("Yes"), CFSTR("Custom"), "A
comment");
In both examples, the code specifies the key to retrieve, which is the string “Yes”. They also specify the strings
file (or table) in which to look for the key, which in this case isthe Custom.strings file. During string retrieval,
the comment string is ignored.
Advanced Strings File Tips
The following sections provide some additional tips for working with strings files and string resources.
Searching for Custom Functions With genstrings
The genstrings tool searches for the Core Foundation and Foundation string macros by default. It uses the
information in these macros to create the string entries in your project’s strings files. You can also direct
genstrings to look for custom string-loading functions in your code and use those functions in addition to
the standard macros. You might use custom functionsto wrap the built-in string-loading routines and perform
some extra processing or you might replace the defaultstring handling behavior with your own custom model.
If you want to use genstrings with your own custom functions, your functions must use the naming and
formatting conventions used by the Foundation macros. The parameters for your functions must match the
parameters for the corresponding macros exactly. When you invoke genstrings, you specify the -s option
followed by the name of the function that correspondsto the NSLocalizedString macro. Your other function
names should then build from this base name. For example, if you specified the function name
MyStringFunction, your other function names should be MyStringFunctionFromTable,
MyStringFunctionFromTableInBundle, and MyStringFunctionWithDefaultValue. The genstrings
tool looks for these functions and uses them to build the corresponding strings files.
String Resources
Advanced Strings File Tips
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
40Formatting String Resources
For some strings, you may not want to (or be able to) encode the entire string in a string resource because
portions of the string might change at runtime. For example, if a string contains the name of a user document,
you need to be able to insert that document name into the string dynamically. When creating your string
resources, you can use any of the formatting characters you would normally use for handling string replacement
in the Foundation and Core Foundation frameworks. Listing 2-4 shows several string resources that use basic
formatting characters:
Listing 2-4 Strings with formatting characters
"Windows must have at least %d columns and %d rows." =
"Les fenêtres doivent être composes au minimum de %d colonnes et %d lignes.";
"File %@ not found." = "Le fichier %@ n’existe pas.";
To replace formatting characters with actual values, you use the stringWithFormat: method of NSString
or the CFStringCreateWithFormat function, using the string resource as the format string. Foundation
and Core Foundation support most of the standard formatting characters used in printf statements. In
addition, you can use the %@ specifiershown in the preceding example to insert the descriptive text associated
with arbitrary Objective-C objects. See “Formatting String Objects” in String Programming Guide for the complete
list of specifiers.
One problem that often occurs during translation is that the translator may need to reorder parameters inside
translated strings to account for differences in the source and target languages. If a string contains multiple
arguments, the translator can insert special tags of the form n$ (where n specifies the position of the original
argument) in between the formatting characters. These tags let the translator reorder the arguments that
appear in the original string. The following example shows a string whose two arguments are reversed in the
translated string:
/* Message in alert dialog when something fails */
"%@ Error! %@ failed!" = "%2$@ blah blah, %1$@ blah!";
Using Special Characters in String Resources
Just as in C, some characters must be prefixed with a backslash before you can include them in the string.
These characters include double quotation marks, the backslash character itself, and special control characters
such as linefeed (\n) and carriage returns (\r).
"File \"%@\" cannot be opened" = " ... ";
"Type \"OK\" when done" = " ... ";
String Resources
Advanced Strings File Tips
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
41You can include arbitrary Unicode characters in a value string by specifying \U followed immediately by up to
four hexadecimal digits. The four digits denote the entry for the desired Unicode character; for example, the
space character is represented by hexadecimal 20 and thus would be \U0020 when specified as a Unicode
character. This option is useful if a string must include Unicode characters that for some reason cannot be
typed. If you use this option, you must also pass the -u option to genstrings in order for the hexadecimal
digits to be interpreted correctly in the resulting strings file. The genstrings tool assumes your strings are
low-ASCII by default and only interprets backslash sequences if the -u option is specified.
Note: The genstrings tool always generatesstringsfiles using the UTF-16 encoding. If you include
Unicode characters in your strings and do not use genstrings to create your strings files, be sure
to save your strings files in the UTF-16 encoding.
Debugging Strings Files
If you run into problems during testing and find that the functions and macros for retrieving strings are always
returning the same key (as opposed to the translated value), run the /usr/bin/plutil tool on your strings
file. A strings file is essentially a property-list file formatted in a special way. Running plutil with the -lint
option can uncover hidden characters or other errorsthat are preventing stringsfrom being retrieved correctly.
String Resources
Advanced Strings File Tips
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
42The OS X and iOS platforms were built to provide a rich multimedia experience. To support that experience,
both platforms provide plenty of support for loading and using image, sound, and video resources in your
application. Image resources are commonly used to draw portions of an application’s user interface. Sound
and video resources are used less frequently but can also enhance the basic appearance and appeal of an
application. The following sections describe the support available for working with image, sound, and video
resources in your applications.
Images and Sounds in Nib Files
Using Xcode, you can reference your application’s sound and image files from within nib files. You might do
so to associate those images or sounds with different properties of a view or control. For example, you might
set the default image to display in an image view or set the image to display for a button. Creating such a
connection in a nib file saves you the hassle of having to make that connection later when the nib file isloaded.
To make image and sound resources available in a nib file, all you have to do is add them to your Xcode project;
Xcode then lists them in the library pane. When you make a connection to a given resource file, Xcode makes
a note of that connection in the nib file. At load time, the nib-loading code looksfor that resource in the project
bundle, where it should have been placed by Xcode at build time.
When you load a nib file that contains references to image and sound resources, the nib-loading code caches
resources whenever possible for easy retrieval later. For example, after loading a nib file, you can retrieve an
image associated with that nib file using the imageNamed: method of either NSImage or UIImage (depending
on your platform). In OS X you can retrieve cached sound resources using the soundNamed: method of
NSSound.
Loading Image Resources
Image resources are commonly used in most applications. Even very simple applications use images to create
a custom look for controls and views. OS X and iOS provide extensive support for manipulating image data
using Objective-C objects. These objects make using image images extremely easy, often requiring only a few
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
43
Image, Sound, and Video Resourceslines of code to load and draw the image. If you prefer not to use the Objective-C objects, you can also use
Quartz to load images using a C-based interface. The following sections describe the processfor loading image
resource files using each of the available techniques.
Loading Images in Objective-C
To load images in Objective-C, you use either the NSImage or UIImage object, depending on the current
platform. Applications built for OS X using the AppKit framework use the NSImage object to load images and
draw them. Applications built for iOS use the UIImage object. Functionally, both of these objects provide
almost identical behavior when it comesto loading existing image resources. You initialize the object by passing
it a pointer to the image file in your application bundle and the image object takes care of the details of loading
the image data.
Listing 3-1 shows how to load an image resource using the NSImage class in OS X. After you locate the image
resource, which in this case is in the application bundle, you simply use that path to initialize the image object.
After initialization, you can draw the image using the methods of NSImage or passthat object to other methods
that can use it. To perform the exactsame task in iOS, all you would need to do is change references of NSImage
to UIImage.
Listing 3-1 Loading an image resource
NSString* imageName = [[NSBundle mainBundle] pathForResource:@"image1"
ofType:@"png"];
NSImage* imageObj = [[NSImage alloc] initWithContentsOfFile:imageName];
You can use image objectsto open any type of image supported on the target platform. Each object istypically
a lightweight wrapper for more advanced image handling code. To draw an image in the current graphics
context, you would simply use one of its drawing related methods. Both NSImage and UIImage have methods
for drawing the image in several different ways. The NSImage class also provides extra support for manipulating
the images you load.
For information about the methods of the NSImage and UIImage classes, see NSImage Class Reference and
UIImage Class Reference . For more detailed information about the additional features of the NSImage class,
see “Images” in Cocoa Drawing Guide .
Image, Sound, and Video Resources
Loading Image Resources
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
44Loading Images Using Quartz
If you are writing C-based code, you can use a combination of Core Foundation and Quartz calls to load image
resources into your applications. Core Foundation provides the initial support for locating image resources
and loading the corresponding image data into memory. Quartz takes the image data you load into memory
and turns it into a usable CGImageRef that your code can then use to draw the image.
There are two ways to load images using Quartz: data providers and image source objects. Data providers are
available in both iOS and OS X. Image source objects are available only in OS X v10.4 and later but take advantage
of the Image I/O framework to enhance the basic image handling capabilities of data providers. When it comes
to loading and displaying image resources, both technologies are well suited for the job. The only time you
might prefer image sources over data providers is when you want greater access to the image-related data.
Listing 3-2 shows how to use a data provider to load a JPEG image. This method uses the Core Foundation
bundle support to locate the image in the application’s main bundle and get a URL to it. It then uses that URL
to create the data provider object and then create a CGImageRef for the corresponding JPEG data. (For brevity
this example omits any error-handling code. Your own code should make sure that any referenced data
structures are valid.)
Listing 3-2 Using data providers to load image resources
CGImageRef MyCreateJPEGImageRef (const char *imageName);
{
CGImageRef image;
CGDataProviderRef provider;
CFStringRef name;
CFURLRef url;
CFBundleRef mainBundle = CFBundleGetMainBundle();
// Get the URL to the bundle resource.
name = CFStringCreateWithCString (NULL, imageName, kCFStringEncodingUTF8);
url = CFBundleCopyResourceURL(mainBundle, name, CFSTR("jpg"), NULL);
CFRelease(name);
// Create the data provider object
provider = CGDataProviderCreateWithURL (url);
CFRelease (url);
// Create the image object from that provider.
Image, Sound, and Video Resources
Loading Image Resources
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
45image = CGImageCreateWithJPEGDataProvider (provider, NULL, true,
kCGRenderingIntentDefault);
CGDataProviderRelease (provider);
return (image);
}
For detailed information about working with Quartz images, see Quartz 2D Programming Guide . For reference
information about data providers, see Quartz 2D Reference Collection (OS X) or Core Graphics Framework
Reference (iOS).
Specifying High-Resolution Images in iOS
An iOS app should include high-resolution versions of its image resources. When the app is run on a device
that has a high-resolution screen, high-resolution images provide extra detail and look better because they
do not need to be scaled to fit the space. You provide high-resolution images for each image resource in your
application bundle, including icons and launch images.
To specify a high-resolution version of an image, create a version whose width and height (measured in pixels)
are twice that of the original. You use the extra pixels in the image to provide additional detail. When saving
the image, use the same base name but include the string @2x between the base filename and the filename
extension. For example, if you have an image named MyImage.png, the name of the high-resolution version
would be MyImage@2x.png. Put the high-resolution and original versions of your image in the same location
in your application bundle.
The bundle- and image-loading routines automatically look for image files with the @2x string when the
underlying device has a high-resolution screen. If you combine the @2x string with other modifiers, the @2x
string should come before any device modifiers but after all other modifiers, such as launch orientation or URL
scheme modifiers. For example:
MyImage.png - Default version of an image resource.
MyImage@2x.png - High-resolution version of an image resource for devices with Retina displays.
MyImage~iphone.png - Version of an image for iPhone and iPod touch.
MyImage@2x~iphone.png - High-resolution version of an image for iPhone and iPod touch devices with
Retina displays.
Image, Sound, and Video Resources
Loading Image Resources
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
46When you want to load an image, do not include the @2x or any device modifiers when specifying the image
name in your code. For example, if your application bundle included the image files from the preceding list,
you would ask for an image named MyImage.png. The system automatically determines which version of the
image is most appropriate and loads it. Similarly, when using or drawing that image, you do not have to know
whether it is the original resolution or high-resolution version. The image-drawing routines automatically
adjust based on the image that wasloaded. However, if you still want to know whether an image isthe original
or high-resolution version, you can check its scale factor. If the image is the high-resolution version, its scale
factor is set to a value other than 1.0.
For more information about how to support high-resolution devices, see “Supporting High-Resolution Screens”.
Image, Sound, and Video Resources
Loading Image Resources
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
47Separating your application’s data from its code can make it easier to modify your application later. If you store
the configuration data for your application in resource files, you can change that configuration without having
to recompile your application. Data resource files can be used to store any type of information. The following
sections highlight some of the data resource types supported by iOS and OS X.
Property List Files
Property list files are a way to store custom configuration data outside of your application code. OS X and iOS
use property lists extensively to implement features such as user preferences and information property list
files for bundles. You can similarly use property lists to store private (or public) configuration data for your
applications.
A property-list file is essentially a set of structured data values. You can create and edit property lists either
programmatically or using the Property List Editor application (located in
/Developer/Applications/Utilities). The structure of custom property-list files is completely up to
you. You can use property liststo store string, number, Boolean, date, and raw data values. By default, a property
list stores data in a single dictionary structure, but you can assign additional dictionaries and arrays as values
to create a more hierarchical data set.
For information about using property lists,see Property List Programming Guide and Property List Programming
Topics for Core Foundation .
OS X Data Resource Files
Table 4-1 lists some additional resource file types that are supported in Mac apps.
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
48
Data Resource FilesTable 4-1 Other resource types
Resource Description
Type
In OS X, AppleScript terminology and suite files contain information about the
scriptability of an application. These files can use the file extensions .sdef,
.scriptSuite, or .scriptTerminology. Because the actual AppleScript commands
used to script an application are visible in userscripts and the Script Editor application,
these resources need to be localized. For information on supporting AppleScript, see
AppleScript Overview.
AppleScript
files
In OS X, help content typically consists of a set of HTML files created using a standard
text-editing program and registered with the Help Viewer application. (For information
on how to register with Help Viewer, see Apple Help Programming Guide .) It is also
possible to embed PDF files, RTF files, HTML files or other custom documents in your
bundle and open them using an external application, such as Preview or Safari. For
information on how to open files, see Launch Services Programming Guide .
Help files
Data Resource Files
OS X Data Resource Files
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
49This table describes the changes to Resource Programming Guide .
Date Notes
Modified discussion of high-resolution image resources to include all
Retina displays.
2012-06-11
2011-10-12 Updated for ARC and iOS 5.
Corrected information about how you specify high-resolution image
resource filenames.
2010-09-15
2010-05-25 Updated references to the Apple developer website.
2009-01-06 Added information about KVO notifications during nib loading.
2008-06-26 Updated for iOS.
Clarified the process of how objects are instantiated when a nib file is
loaded.
2007-09-04
Reorganized content and added new information. Changed title from
"Loading Resources".
2007-02-08
2005-11-09 Corrected the misidentification of a class method as an instance method.
Added “Instantiating Nibs From Memory” and the link to the NSNib class
reference.
2003-07-09
2003-05-28 Section on initializing nib file objects corrected and expanded.
Revision history was added to existing topic. It will be used to record
changes to the content of the topic.
2002-11-12
2012-06-11 | © 2012 Apple Inc. All Rights Reserved.
50
Document Revision HistoryApple Inc.
© 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, AppleScript, Cocoa, iPad,
iPhone, iPod, iPod touch, Mac, Objective-C, OS X,
Quartz, Safari, and Xcode are trademarks of Apple
Inc., registered in the U.S. and other countries.
Retina is a trademark of Apple Inc.
Java is a registered trademark of Oracle and/or
its affiliates.
iOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
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.
Safari CSS Visual Effects
GuideContents
Introduction 8
At a Glance 9
Use CSS Properties to Add Gradients, Masks, Reflections, and Filters 9
Animate Changes in CSS Properties 9
Apply 2D and 3D Transformations to Any HTML Element 10
How to Use This Document 10
Prerequisites 11
See Also 11
Using Gradients 12
Creating Linear Gradients 12
Setting the Direction of Change 13
Setting the Rate of Change 14
Creating Gradient Fades 16
Creating Radial Gradients 17
Moving the Center 18
Changing the Ending Color Location 19
Adding Color Stops 20
Creating a Radial Fade 22
Creating Repeating Gradients 23
Using a Gradient as a Border Image 24
Prior Syntax (-webkit-gradient) 26
Using Masks 28
Using an Image as a Mask 28
Using a Gradient as a Mask 32
Working with WebKit Mask Properties 35
Using Reflections 37
Adding a Reflection 37
Adjusting the Reflection’s Position 38
Masking a Reflection 39
Inner Reflections 41
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
2Using CSS Filters 43
Using CSS Filters 43
Animating CSS Transitions 45
Setting Transition Properties 46
Using Timing Functions 47
Delaying the Start 48
Setting Several Transition Properties At Once 48
Handling Intermediate States and Events 49
Animating With Keyframes 50
Creating a Keyframe Animation 51
Creating Keyframes 52
Setting Animation Properties 53
Animation Timing Functions 54
Starting Animations 55
Controlling Animation Using JavaScript 56
Handling Animation Events 58
Using 2D and 3D Transforms 61
2D Transform Functions 62
2D Translation 63
2D Rotation 63
2D Scaling 65
Setting Multiple Transforms 66
Changing the Origin 67
3D Transforms 69
Adding 3D Perspective 70
Creating a 3D Space 74
3D Transform Functions 76
Back Face Visibility 80
Using Transformation Matrices 81
2D Matrix Operations 82
3D Matrix Operations 84
Working with Transforms in JavaScript 84
Example: Animated Rotating Box Under JavaScript Control 86
Adding Interactive Control to Visual Effects 90
Using a Click or Tap to Trigger a Transition Effect 90
Controlling a 3D Transform with a Click, Touch, or Swipe 91
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
3
ContentsUsing Gestures to Scale and Rotate Elements 95
Document Revision History 99
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
4
ContentsFigures and Listings
Using Gradients 12
Figure 1-1 Simple linear gradient 13
Figure 1-2 Rainbow gradient 13
Figure 1-3 Diagonal gradients 14
Figure 1-4 Setting color stop percentages 15
Figure 1-5 Solid color band and abrupt color change 15
Figure 1-6 Linear gradient fade 16
Figure 1-7 Simple radial gradient 17
Figure 1-8 Circular gradient 18
Figure 1-9 3D lighting effect 19
Figure 1-10 Closest-corner gradient fills 20
Figure 1-11 Multicolor gradient 21
Figure 1-12 Red color stop at 20% 21
Figure 1-13 Color band and abrupt color change using color stops 22
Figure 1-14 Spotlight gradient 23
Figure 1-15 Repeating gradient patterns 24
Figure 1-16 Linear gradient border 25
Figure 1-17 Radial gradient border 26
Listing 1-1 Linear fade 16
Listing 1-2 Radial fade 22
Using Masks 28
Figure 2-1 Heart-shaped “cookie-cutter” 29
Figure 2-2 Masking a border 30
Figure 2-3 Stacking masks 31
Figure 2-4 Applying a mask with a fuzzy border 32
Figure 2-5 Result of applying a gradient mask 33
Figure 2-6 Horizontal gradient mask with color stops 34
Figure 2-7 Masking text with a radial gradient 35
Listing 2-1 Stacking masked elements 30
Using Reflections 37
Figure 3-1 Reflection below a heading 38
Figure 3-2 Reflection with negative offset 39
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
5Figure 3-3 Reflection with image as mask 40
Figure 3-4 Image with reflection and gradient mask 41
Figure 3-5 Inner reflection, reflected 42
Using CSS Filters 43
Figure 4-1 CSS filters on a video 43
Listing 4-1 Applying CSS filters to HTML elements 44
Animating CSS Transitions 45
Figure 5-1 Card Flip example 45
Figure 5-2 Cubic Bezier timing function 47
Figure 5-3 Transition of two properties 49
Listing 5-1 Setting transition properties 46
Listing 5-2 Creating multiple transitions at once 47
Listing 5-3 Defining a custom timing function 48
Listing 5-4 Detecting transition end events 49
Animating With Keyframes 50
Figure 6-1 Animated text elements 50
Figure 6-2 Animation timing function control points 54
Figure 6-3 JavaScript control of animation 58
Listing 6-1 Simple keyframe animation 51
Listing 6-2 Declaring keyframes 52
Listing 6-3 Starting an animation 56
Listing 6-4 Pausing and continuing an animation 57
Listing 6-5 Handling animation events 59
Using 2D and 3D Transforms 61
Figure 7-1 HTML page with rotation and perspective transforms 61
Figure 7-2 A translated element and its offspring 63
Figure 7-3 Rotating an element 64
Figure 7-4 Scaling an element up 66
Figure 7-5 Element rotated around the top-right corner 68
Figure 7-6 3D coordinate space 69
Figure 7-7 Setting the perspective 72
Figure 7-8 Perspective origin effects 74
Figure 7-9 Text rotated relative to 3D backdrop 76
Figure 7-10 Z-axis translation in perspective 78
Figure 7-11 X and y rotation 79
Figure 7-12 Cardflip example 81
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
6
Figures and ListingsFigure 7-13 2D transformation matrix parameter positions 82
Figure 7-14 Matrix mirroring transforms 83
Figure 7-15 3D matrix parameters 84
Figure 7-16 3D transforms under JavaScript control 89
Listing 7-1 Animating 2D rotation 64
Listing 7-2 Setting multiple transforms using a list 67
Listing 7-3 Nesting 2D transforms 67
Listing 7-4 Rotating an element around the top-right corner 68
Listing 7-5 Adding a perspective slider 70
Listing 7-6 Effects of perspective origin 73
Listing 7-7 Nested 3D rotations 75
Listing 7-8 Hiding the back side of a card 80
Listing 7-9 Matrix example 82
Adding Interactive Control to Visual Effects 90
Figure 8-1 Click and tap handler 91
Figure 8-2 Page flip in action 93
Figure 8-3 Element rotated by a gesture 96
Listing 8-1 Simple touch or tap handler 90
Listing 8-2 Page flip on click, tap, or swipe 93
Listing 8-3 Responding to gesture events 96
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
7
Figures and ListingsUse CSS to create stunning visual effects—masks, gradients, reflections, lighting effects, animations, transitions,
3D rotations, and more. Apply any or all of these effects interactively, triggered by mouse events or touch
events; make HTML elements visibly respond to the user—without requiring plug-ins, graphics libraries, or
elaborate JavaScript programs.
There are advantages to using CSS instead of graphic images to create visual effects:
● Because they are resolution-independent, CSS effects scale up smoothly when zoomed.
● Text formatted with CSS is searchable; images are not.
● CSS is compact and compresses well compared with graphic images.
● CSS is just text; it can be quickly modified using a text editor or the output of a script.
Safari supports CSS visual effects on Mac OS X and iOS.
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
8
IntroductionAt a Glance
Safari CSS visual effectsfall into three categories: new visual CSS properties, animation, and 2D and 3D transforms.
Use CSS Properties to Add Gradients, Masks, Reflections, and Filters
New visual CSS properties include gradients, masks, reflections, and filters. Gradients let you add beautiful,
resolution-independent color blends to backgrounds and borders, with a single line of CSS.
Use masks to render portions of HTML elements transparent for elegant compositing. Apply a mask as you
would a background or a border image. You can use an image as a mask. You can also use a gradient as a
mask, and you can mask any HTML element, not just images.
Add a reflection to any element; use a gradient as a mask for a reflection to make the reflection fade to
transparency.
Filters allow you to add hardware-accelerated visual effects to HTML elements, including images and videos.
Relevant chapters: “Using Gradients” (page 12), “Using a Gradient as a Mask” (page 32), “Using
Reflections” (page 37), “Using CSS Filters” (page 43).
Animate Changes in CSS Properties
CSS makes animation easy: specify the properties you want animated, and optionally supply a duration for the
animation, and any change to those CSS properties is automatically made into an animation of the HTML
element, without using graphic plug-ins or even JavaScript. Use CSS pseudoclasses such as :hover to make
the animations interactive—have elements fade in, grow, or enter from offscreen in response to touch or
mouse events.
CSS animations come in two flavors: implicit animations that render changes smoothly over a defined period,
and keyframe animations that allow for more complex behavior, such as moving from side to side or starting
and stopping en route.
Introduction
At a Glance
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
9Relevant chapters: “Animating CSS Transitions” (page 45), “Animating With Keyframes” (page 50).
Apply 2D and 3D Transformations to Any HTML Element
You can apply 2D or 3D transforms to any HTML element, turning a group of div elements into the faces of a
box or the pages of a book, for example. Apply perspective and animation, and you can open and close the
box, turn it to look inside, flip the pages of the book, and so on. 2D transforms include scaling, translation,
shearing, reflection, and rotation. 3D transforms add rotation about the x and y axis and displacement on the
z axis.
Add touch and mouse interaction to trigger transformations by implementing CSS pseudoclasses, such as
:hover, or by writing your own JavaScript functions.
Relevant chapters: “Using 2D and 3D Transforms” (page 61), “Adding Interactive Control to Visual
Effects” (page 90).
How to Use This Document
The visual effects described in this document are WebKit extensions of CSS. Most of the extensions are proposals
for W3C standards;some are in W3C draftsfor CSS3. Asthe standards evolve,syntax for these effectsis modified.
This change is done carefully to allow new syntax to coexist with existing syntax, however. This means you
can experiment with CSS extensions without having your website suddenly break when the standard is
modified—in most cases, the old syntax still works. This document describes the current syntax as of this
writing; many of the extensions have prior syntax that still works but is no longer recommended.
Introduction
How to Use This Document
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
10Note: Because these extensions are WebKit-specific, they are not supported in all browsers. Most
of the extensions have equivalentsin other WebKit-based browsers, however, and for mobile-specific
sites, WebKit-based browsers account for nearly all traffic. Many of the extensions are currently in
W3C working drafts and have equivalents in non-WebKit browsers as well, using the same syntax.
Nevertheless, unless you are writing an iOS web app, you should code your website to degrade
gracefully for browsersthat do notsupport these extensions. For the most part, thisis automatic—an
image may not have a reflection in some browsers, or a change in CSS properties may be immediate
instead of animated—but the site remains functional and the layout is not broken. As always, you
should test your website using all the browsers that you wish to support to ensure that all of your
users have an aesthetically pleasing experience.
Prerequisites
You need a solid understanding of HTML and some familiarity with JavaScript and CSS to make good use of
this document.
See Also
You may also find the following documents helpful:
● Safari DOM Additions Reference—describes the touch event classes that you use to handle multi-touch
gestures in JavaScript.
● Safari CSS Reference—describes the CSS properties supported by various Safari and WebKit applications.
● Safari Web Content Guide—describes how to create content that is compatible with, optimized for, and
customized for iOS.
●
iOS Human Interface Guidelines—provides user interface guidelines for designing webpages and web
applications for Safari on iOS.
● FingerTips—demonstrates how to build an interactive 3D carousel using CSS,JavaScript and touch events.
● http://dev.w3.org/csswg/css3-images/—W3C draft for gradients.
● http://www.w3.org/TR/css3-transitions/—W3C draft for animated transitions.
● http://www.w3.org/TR/css3-animations/—W3C draft for keyframe animations.
● http://www.w3.org/TR/css3-2d-transforms/—W3C draft for 2D transforms.
● http://www.w3.org/TR/css3-3d-transforms/—W3C draft for 3D transforms.
Introduction
Prerequisites
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
11Use gradients as color fills that blend smoothly from one color to another. Use a CSS gradient anywhere that
you can use an image, such as for the background of an element, an element border, or a mask. Because
gradients are resolution-independent and compact, a line or two of CSS can replace hundreds of kilobytes—or
even megabytes—of graphic imagery. Unlike graphic images, gradients have no inherentsize, and automatically
expand to fill a container.
To create a gradient, specify a starting color and an ending color, and optionally intermediate colors and a
direction. Safari supports two types of CSS gradients: linear and radial. This chapter describes both types of
gradients. Safari 5.1 on the desktop, and Safari on iOS 5.0, use the -webkit- prefix for specifying gradients,
but otherwise conform to the 17 February 2011 working draft for CSS3 gradients: http://dev.w3.org/csswg/css3-
images/.
Note: Recent drafts of the W3C proposal have simplified the syntax. This chapter describesthe most
recent implementation shipping in Safari. You should expect Safari’ssyntax for gradientsto continue
to change as the W3C standard evolves. While new syntax is expected, the existing syntax—and
prior syntax—should still work.
The -webkit-linear-gradient and webkit-radial-gradient properties require iOS 5.0 or
later, or Safari 5.1 or later on the desktop. If you need to support earlier releases of iOS or Safari, see
“Prior Syntax (-webkit-gradient)” (page 26).
Creating Linear Gradients
A linear gradient defines a color change along a specified line. Each point on the line has a particular color.
The width of the line, perpendicular to the direction of the line, extendsto the edges of the gradient’s container.
You can use a linear gradient to fill any two-dimensional shape. By default, a linear gradient changes colors
from top to bottom. For example:
background: -webkit-linear-gradient(aqua, white)
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
12
Using Gradientsdefines a linear gradient that starts as aqua at the top of the element and ends as white at the bottom of the
element. The gradient fills the element completely, as Figure 1-1 illustrates.
Figure 1-1 Simple linear gradient
If you specify intermediate colors between the starting and ending color, the gradient blends from color to
color. For example:
background: -webkit-linear-gradient(red, yellow, orange, green, blue, purple);
defines a rainbow gradient as a background. Apply this style to a div element, and the element is drawn with
a rainbow background, as Figure 1-2 illustrates.
Figure 1-2 Rainbow gradient
Setting the Direction of Change
You can define a linear gradient with the color change going in any direction: from any edge or corner to its
opposite edge or corner, or at any specified angle. To specify a direction from edge-to-edge or corner-to-corner,
just specify the beginning edge or corner. For example:
● background: -webkit-linear-gradient(left, black, white);
creates a horizontal gradient going from left to right.
● background: -webkit-linear-gradient(bottom right, black, white);
Using Gradients
Creating Linear Gradients
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
13creates a diagonal gradient from bottom right to top left.
You can also specify color change direction by supplying an angle. Angles are given in degrees, with 0deg
being straight up and proceeding counterclockwise-positive, so that 90deg is horizontal left and 180deg is
straight down. For example:
-webkit-linear-gradient(45deg, black, white)
creates a gradient at a 45 degree angle up and to the left.
Note: If you specify a gradient from corner to corner, the angle of the gradient changesif the parent
element is resized and the shape of the element changes. Specify the direction in degrees to create
a gradient with a fixed angle.
Figure 1-3 shows a diagonal gradient starting at the bottom left corner.
Figure 1-3 Diagonal gradients
Setting the Rate of Change
By default, the rate of color change for a gradient remains constant; if the gradient has three colors, the blend
starts with the first color at 0% of the gradient length, reaches the second color at 50% of the gradient length,
and reaches the third color at 100% of the gradient length. In other words, the first line of the gradient is the
starting color, the middle line is the second color, and the last line is the third color. To modify this behavior,
specify color stops. For example, the following snippet creates a gradient that changes gradually from white
to cornflower blue over 90% of the gradient length then blends quickly from to black over the remaining 10%:
-webkit-linear-gradient(left, white, cornflowerblue 90%, black)
Using Gradients
Creating Linear Gradients
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
14Figure 1-4 shows such a gradient.
Figure 1-4 Setting color stop percentages
Color stops can create some striking effects. For example, specify the same color at two consecutive stops to
create a band of solid color, or specify two different colors at the same percentage point to create an abrupt
change in color. Figure 1-5 shows the effect these kind of color stops create.
background: -webkit-linear-gradient(left,black,blue 10%,blue 90%,black);
background: -webkit-linear-gradient(left,white,blue 50%,purple 50%,white);
Figure 1-5 Solid color band and abrupt color change
Using Gradients
Creating Linear Gradients
2012-07-23 | © 2012 Apple Inc. All Rights Reserved.
15Creating Gradient Fades
Use RGBa colors in a gradient to soften or fade colors into the background by decreasing the alpha value of
the gradient. For example, Listing 1-1 creates a div element with a white background that fadesto transparent.
Two consecutive white color stops are used, so the div element’s background stays white for 50% of its width
and then fades into the background of the element’s parent. Figure 1-6 shows the result.
Listing 1-1 Linear fade
rgba gradient
RGBa Gradient Fades