You are previewing iOS 6 Programming Cookbook.

iOS 6 Programming Cookbook

Cover of iOS 6 Programming Cookbook by Vandad Nahavandipoor Published by O'Reilly Media, Inc.
  1. iOS 6 Programming Cookbook
  2. Preface
    1. Audience
    2. Organization of This Book
    3. Additional Resources
    4. Conventions Used in This Book
    5. Using Code Examples
    6. We’d Like to Hear from You
    7. Safari® Books Online
    8. Acknowledgments
  3. 1. The Basics
    1. 1.0. Introduction
    2. 1.1. Creating a Simple iOS App in Xcode
      1. Problem
      2. Solution
      3. Discussion
    3. 1.2. Understanding Interface Builder
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 1.3. Compiling iOS Apps
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 1.4. Running iOS Apps on the Simulator
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 1.5. Running iOS Apps on iOS Devices
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. 1.6. Packaging iOS Apps for Distribution
      1. Problem
      2. Solution
      3. Discussion
    8. 1.7. Declaring Variables in Objective-C
      1. Problem
      2. Solution
      3. Discussion
    9. 1.8. Allocating and Making Use of Strings
      1. Problem
      2. Solution
      3. Discussion
    10. 1.9. Comparing Values in Objective-C with an if Statement
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    11. 1.10. Implementing Loops with for Statements
      1. Problem
      2. Solution
      3. Discussion
    12. 1.11. Implementing while Loops
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    13. 1.12. Creating Custom Classes
      1. Problem
      2. Solution
      3. Discussion
    14. 1.13. Defining Functionality for Classes
      1. Problem
      2. Solution
      3. Discussion
    15. 1.14. Defining Two or More Methods with the Same Name
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    16. 1.15. Allocating and Initializing Objects
      1. Problem
      2. Solution
      3. Discussion
    17. 1.16. Adding Properties to Classes
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    18. 1.17. Moving from Manual Reference Counting to Automatic Reference Counting
      1. Problem
      2. Solution
      3. Discussion
    19. 1.18. Typecasting with Automatic Reference Counting
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    20. 1.19. Delegating Tasks with Protocols
      1. Problem
      2. Solution
      3. Discussion
    21. 1.20. Determining Whether Instance or Class Methods Are Available
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    22. 1.21. Determining Whether a Class Is Available at Runtime
      1. Problem
      2. Solution
      3. Discussion
    23. 1.22. Allocating and Making Use of Numbers
      1. Problem
      2. Solution
      3. Discussion
    24. 1.23. Allocating and Making Use of Arrays
      1. Problem
      2. Solution
      3. Discussion
    25. 1.24. Allocating and Making Use of Dictionaries
      1. Problem
      2. Solution
      3. Discussion
    26. 1.25. Allocating and Making Use of Sets
      1. Problem
      2. Solution
      3. Discussion
    27. 1.26. Creating Bundles
      1. Problem
      2. Solution
      3. Discussion
    28. 1.27. Loading Data from the Main Bundle
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    29. 1.28. Loading Data from Other Bundles
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    30. 1.29. Sending Notifications with NSNotificationCenter
      1. Problem
      2. Solution
      3. Discussion
    31. 1.30. Listening for Notifications Sent from NSNotificationCenter
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  4. 2. Implementing Controllers and Views
    1. 2.0. Introduction
    2. 2.1. Displaying Alerts with UIAlertView
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 2.2. Creating and Using Switches with UISwitch
      1. Problem
      2. Solution
      3. Discussion
    4. 2.3. Customizing the UISwitch
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 2.4. Picking Values with UIPickerView
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 2.5. Picking the Date and Time with UIDatePicker
      1. Problem
      2. Solution
      3. Discussion
    7. 2.6. Implementing Range Pickers with UISlider
      1. Problem
      2. Solution
      3. Discussion
    8. 2.7. Customizing the UISlider
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 2.8. Grouping Compact Options with UISegmentedControl
      1. Problem
      2. Solution
      3. Discussion
    10. 2.9. Customizing the UISegmentedControl
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    11. 2.10. Presenting and Managing Views with UIViewController
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    12. 2.11. Presenting Sharing Options with UIActivityViewController
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    13. 2.12. Implementing Navigation with UINavigationController
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    14. 2.13. Manipulating a Navigation Controller’s Array of View Controllers
      1. Problem
      2. Solution
      3. Discussion
    15. 2.14. Displaying an Image on a Navigation Bar
      1. Problem
      2. Solution
      3. Discussion
    16. 2.15. Adding Buttons to Navigation Bars Using UIBarButtonItem
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    17. 2.16. Presenting Multiple View Controllers with UITabBarController
      1. Problem
      2. Solution
      3. Discussion
    18. 2.17. Displaying Static Text with UILabel
      1. Problem
      2. Solution
      3. Discussion
    19. 2.18. Customizing the UILabel
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    20. 2.19. Accepting User Text Input with UITextField
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    21. 2.20. Displaying Long Lines of Text with UITextView
      1. Problem
      2. Solution
      3. Discussion
    22. 2.21. Adding Buttons to the User Interface with UIButton
      1. Problem
      2. Solution
      3. Discussion
    23. 2.22. Displaying Images with UIImageView
      1. Problem
      2. Solution
      3. Discussion
    24. 2.23. Creating Scrollable Content with UIScrollView
      1. Problem
      2. Solution
      3. Discussion
    25. 2.24. Loading Web Pages with UIWebView
      1. Problem
      2. Solution
      3. Discussion
    26. 2.25. Presenting Master-Detail Views with UISplitViewController
      1. Problem
      2. Solution
      3. Discussion
    27. 2.26. Enabling Paging with UIPageViewController
      1. Problem
      2. Solution
      3. Discussion
    28. 2.27. Displaying Popovers with UIPopoverController
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    29. 2.28. Displaying Progress with UIProgressView
      1. Problem
      2. Solution
      3. Discussion
    30. 2.29. Listening and Reacting to Keyboard Notifications
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    31. 2.30. Constructing and Displaying Styled Texts
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  5. 3. Auto Layout and the Visual Format Language
    1. 3.0. Introduction
    2. 3.1. Placing UI Components in the Center of the Screen
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 3.2. Defining Horizontal and Vertical Constraints with the Visual Format Language
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 3.3. Utilizing Cross View Constraints
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 3.4. Configuring Auto Layout Constraints in Interface Builder
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  6. 4. Constructing and Using Table Views
    1. 4.0. Introduction
    2. 4.1. Instantiating a Table View
      1. Problem
      2. Solution
      3. Discussion
    3. 4.2. Assigning a Delegate to a Table View
      1. Problem
      2. Solution
      3. Discussion
    4. 4.3. Populating a Table View with Data
      1. Problem
      2. Solution
      3. Discussion
    5. 4.4. Receiving and Handling Table View Events
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 4.5. Using Different Types of Accessories in a Table View Cell
      1. Problem
      2. Solution
      3. Discussion
    7. 4.6. Creating Custom Table View Cell Accessories
      1. Problem
      2. Solution
      3. Discussion
    8. 4.7. Displaying Hierarchical Data in Table Views
      1. Problem
      2. Solution
      3. Discussion
    9. 4.8. Enabling Swipe Deletion of Table View Cells
      1. Problem
      2. Solution
      3. Discussion
    10. 4.9. Constructing Headers and Footers in Table Views
      1. Problem
      2. Solution
      3. Discussion
    11. 4.10. Displaying Context Menus on Table View Cells
      1. Problem
      2. Solution
      3. Discussion
    12. 4.11. Moving Cells and Sections in Table Views
      1. Problem
      2. Solution
      3. Discussion
    13. 4.12. Deleting Cells and Sections from Table Views
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    14. 4.13. Utilizing the UITableViewController for Easy Creation of Table Views
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    15. 4.14. Displaying a Refresh Control for Table Views
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  7. 5. Storyboards
    1. 5.0. Introduction
    2. 5.1. Creating a Project with Storyboards
      1. Problem
      2. Solution
      3. Discussion
    3. 5.2. Adding a Navigation Controller to a Storyboard
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 5.3. Passing Data From One Screen to Another
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 5.4. Adding a Storyboard to an Existing Project
      1. Problem
      2. Solution
      3. Discussion
  8. 6. Concurrency
    1. 6.0. Introduction
    2. 6.1. Constructing Block Objects
      1. Problem
      2. Solution
      3. Discussion
    3. 6.2. Accessing Variables in Block Objects
      1. Problem
      2. Solution
      3. Discussion
    4. 6.3. Invoking Block Objects
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 6.4. Dispatching Tasks to Grand Central Dispatch
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 6.5. Performing UI-Related Tasks with GCD
      1. Problem
      2. Solution
      3. Discussion
    7. 6.6. Executing Non-UI Related Tasks Synchronously with GCD
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 6.7. Executing Non-UI Related Tasks Asynchronously with GCD
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 6.8. Performing Tasks After a Delay with GCD
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. 6.9. Performing a Task Only Once with GCD
      1. Problem
      2. Solution
      3. Discussion
    11. 6.10. Grouping Tasks Together with GCD
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    12. 6.11. Constructing Your Own Dispatch Queues with GCD
      1. Problem
      2. Solution
      3. Discussion
    13. 6.12. Running Tasks Synchronously with Operations
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    14. 6.13. Running Tasks Asynchronously with Operations
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    15. 6.14. Creating Dependency Between Operations
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    16. 6.15. Creating Timers
      1. Problem
      2. Solution
      3. Discussion
    17. 6.16. Creating Concurrency with Threads
      1. Problem
      2. Solution
      3. Discussion
    18. 6.17. Invoking Background Methods
      1. Problem
      2. Solution
      3. Discussion
    19. 6.18. Exiting Threads and Timers
      1. Problem
      2. Solution
      3. Discussion
  9. 7. Core Location and Maps
    1. 7.0. Introduction
    2. 7.1. Creating a Map View
      1. Problem
      2. Solution
      3. Discussion
    3. 7.2. Handling the Events of a Map View
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 7.3. Pinpointing the Location of a Device
      1. Problem
      2. Solution
      3. Discussion
    5. 7.4. Displaying Pins on a Map View
      1. Problem
      2. Solution
      3. Discussion
    6. 7.5. Displaying Pins with Different Colors on a Map View
      1. Problem
      2. Solution
      3. Discussion
    7. 7.6. Displaying Custom Pins on a Map View
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 7.7. Converting Meaningful Addresses to Longitude and Latitude
      1. Problem
      2. Solution
      3. Discussion
    9. 7.8. Converting Longitude and Latitude to a Meaningful Address
      1. Problem
      2. Solution
      3. Discussion
  10. 8. Implementing Gesture Recognizers
    1. 8.0. Introduction
    2. 8.1. Detecting Swipe Gestures
      1. Problem
      2. Solution
      3. Discussion
    3. 8.2. Detecting Rotation Gestures
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 8.3. Detecting Panning and Dragging Gestures
      1. Problem
      2. Solution
      3. Discussion
    5. 8.4. Detecting Long Press Gestures
      1. Problem
      2. Solution
      3. Discussion
    6. 8.5. Detecting Tap Gestures
      1. Problem
      2. Solution
      3. Discussion
    7. 8.6. Detecting Pinch Gestures
      1. Problem
      2. Solution
      3. Discussion
  11. 9. Networking, JSON, XML, and Twitter
    1. 9.0. Introduction
    2. 9.1. Downloading Asynchronously with NSURLConnection
      1. Problem
      2. Solution
      3. Discussion
    3. 9.2. Handling Timeouts in Asynchronous Connections
      1. Problem
      2. Solution
      3. Discussion
    4. 9.3. Downloading Synchronously with NSURLConnection
      1. Problem
      2. Solution
      3. Discussion
    5. 9.4. Modifying a URL Request with NSMutableURLRequest
      1. Problem
      2. Solution
      3. Discussion
    6. 9.5. Sending HTTP GET Requests with NSURLConnection
      1. Problem
      2. Solution
      3. Discussion
    7. 9.6. Sending HTTP POST Requests with NSURLConnection
      1. Problem
      2. Solution
      3. Discussion
    8. 9.7. Sending HTTP DELETE Requests with NSURLConnection
      1. Problem
      2. Solution
      3. Discussion
    9. 9.8. Sending HTTP PUT Requests with NSURLConnection
      1. Problem
      2. Solution
      3. Discussion
    10. 9.9. Serializing Arrays and Dictionaries into JSON
      1. Problem
      2. Solution
      3. Discussion
    11. 9.10. Deserializing JSON into Arrays and Dictionaries
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    12. 9.11. Integrating Twitter Functionality into Your Apps
      1. Problem
      2. Solution
      3. Discussion
    13. 9.12. Parsing XML with NSXMLParser
      1. Problem
      2. Solution
      3. Discussion
  12. 10. Audio and Video
    1. 10.0. Introduction
    2. 10.1. Playing Audio Files
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 10.2. Handling Interruptions while Playing Audio
      1. Problem
      2. Solution
      3. Discussion
    4. 10.3. Recording Audio
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 10.4. Handling Interruptions while Recording Audio
      1. Problem
      2. Solution
      3. Discussion
    6. 10.5. Playing Audio over Other Active Sounds
      1. Problem
      2. Solution
      3. Discussion
    7. 10.6. Playing Video Files
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 10.7. Capturing Thumbnails from a Video File
      1. Problem
      2. Solution
      3. Discussion
    9. 10.8. Accessing the Music Library
      1. Problem
      2. Solution
      3. Discussion
  13. 11. Address Book
    1. 11.0. Introduction
    2. 11.1. Requesting Access to the Address Book
      1. Problem
      2. Solution
      3. Discussion
    3. 11.2. Retrieving a Reference to an Address Book
      1. Problem
      2. Solution
      3. Discussion
    4. 11.3. Retrieving All the People in the Address Book
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 11.4. Retrieving Properties of Address Book Entries
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 11.5. Inserting a Person Entry into the Address Book
      1. Problem
      2. Solution
      3. Discussion
    7. 11.6. Inserting a Group Entry into the Address Book
      1. Problem
      2. Solution
      3. Discussion
    8. 11.7. Adding Persons to Groups
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 11.8. Searching the Address Book
      1. Problem
      2. Solution
      3. Discussion
    10. 11.9. Retrieving and Setting a Person’s Address Book Image
      1. Problem
      2. Solution
      3. Discussion
  14. 12. Files and Folder Management
    1. 12.0. Introduction
    2. 12.1. Finding the Paths of the Most Useful Folders on Disk
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 12.2. Writing to and Reading from Files
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 12.3. Creating Folders on Disk
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 12.4. Enumerating Files and Folders
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 12.5. Deleting Files and Folders
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. 12.6. Securing Files on Disk
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 12.7. Saving Objects to Files
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  15. 13. Camera and the Photo Library
    1. 13.0. Introduction
    2. 13.1. Detecting and Probing the Camera
      1. Problem
      2. Solution
      3. Discussion
    3. 13.2. Taking Photos with the Camera
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 13.3. Taking Videos with the Camera
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 13.4. Storing Photos in the Photo Library
      1. Problem
      2. Solution
      3. Discussion
    6. 13.5. Storing Videos in the Photo Library
      1. Problem
      2. Solution
      3. Discussion
    7. 13.6. Retrieving Photos and Videos from the Photo Library
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 13.7. Retrieving Assets from the Assets Library
      1. Problem
      2. Solution
      3. Discussion
    9. 13.8. Editing Videos on an iOS Device
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  16. 14. Multitasking
    1. 14.0. Introduction
    2. 14.1. Detecting the Availability of Multitasking
      1. Problem
      2. Solution
      3. Discussion
    3. 14.2. Completing a Long-Running Task in the Background
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 14.3. Receiving Local Notifications in the Background
      1. Problem
      2. Solution
      3. Discussion
    5. 14.4. Playing Audio in the Background
      1. Problem
      2. Solution
      3. Discussion
    6. 14.5. Handling Location Changes in the Background
      1. Problem
      2. Solution
      3. Discussion
    7. 14.6. Saving and Loading the State of Multitasking iOS Apps
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 14.7. Handling Network Connections in the Background
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 14.8. Handling Notifications Delivered to a Waking App
      1. Problem
      2. Solution
      3. Discussion
    10. 14.9. Responding to Changes in App Settings
      1. Problem
      2. Solution
      3. Discussion
    11. 14.10. Opting Out of Multitasking
      1. Problem
      2. Solution
      3. Discussion
  17. 15. Core Data
    1. 15.0. Introduction
    2. 15.1. Creating a Core Data Model with Xcode
      1. Problem
      2. Solution
      3. Discussion
    3. 15.2. Generating Class Files for Core Data Entities
      1. Problem
      2. Solution
      3. Discussion
    4. 15.3. Creating and Saving Data Using Core Data
      1. Problem
      2. Solution
      3. Discussion
    5. 15.4. Reading Data from Core Data
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 15.5. Deleting Data from Core Data
      1. Problem
      2. Solution
      3. Discussion
    7. 15.6. Sorting Data in Core Data
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 15.7. Boosting Data Access in Table Views
      1. Problem
      2. Solution
      3. Discussion
    9. 15.8. Implementing Relationships in Core Data
      1. Problem
      2. Solution
      3. Discussion
  18. 16. Dates, Calendars, and Events
    1. 16.0. Introduction
    2. 16.1. Retrieving the List of Calendars
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 16.2. Adding Events to Calendars
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 16.3. Accessing the Contents of Calendars
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 16.4. Removing Events from Calendars
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 16.5. Adding Recurring Events to Calendars
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. 16.6. Retrieving the Attendees of an Event
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 16.7. Adding Alarms to Calendars
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 16.8. Handling Event Changed Notifications
      1. Problem
      2. Solution
      3. Discussion
    10. 16.9. Presenting Event View Controllers
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    11. 16.10. Presenting Event Edit View Controllers
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  19. 17. Graphics and Animations
    1. 17.0. Introduction
    2. 17.1. Enumerating and Loading Fonts
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 17.2. Drawing Text
      1. Problem
      2. Solution
      3. Discussion
    4. 17.3. Constructing, Setting, and Using Colors
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 17.4. Drawing Images
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 17.5. Constructing Resizable Images
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. 17.6. Drawing Lines
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 17.7. Constructing Paths
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 17.8. Drawing Rectangles
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. 17.9. Adding Shadows to Shapes
      1. Problem
      2. Solution
      3. Discussion
    11. 17.10. Drawing Gradients
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    12. 17.11. Displacing Shapes Drawn on Graphic Contexts
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    13. 17.12. Scaling Shapes Drawn on Graphic Contexts
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    14. 17.13. Rotating Shapes Drawn on Graphic Contexts
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    15. 17.14. Animating and Moving Views
      1. Problem
      2. Solution
      3. Discussion
    16. 17.15. Animating and Scaling Views
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    17. 17.16. Animating and Rotating Views
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  20. 18. Core Motion
    1. 18.0. Introduction
    2. 18.1. Detecting the Availability of an Accelerometer
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 18.2. Detecting the Availability of a Gyroscope
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 18.3. Retrieving Accelerometer Data
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 18.4. Detecting Shakes on an iOS Device
      1. Problem
      2. Solution
      3. Discussion
    6. 18.5. Retrieving Gyroscope Data
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  21. 19. iCloud
    1. 19.0. Introduction
    2. 19.1. Setting Up Your App for iCloud
      1. Problem
      2. Solution
      3. Discussion
    3. 19.2. Storing and Synchronizing Dictionaries in iCloud
      1. Problem
      2. Solution
      3. Discussion
    4. 19.3. Creating and Managing Folders for Apps in iCloud
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 19.4. Searching for Files and Folders in iCloud
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 19.5. Storing User Documents in iCloud
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. 19.6. Managing the State of Documents in iCloud
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 19.7. Handling Conflicts in iCloud Documents
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  22. 20. Pass Kit
    1. 20.0. Introduction
    2. 20.1. Creating Pass Kit Certificates
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. 20.2. Creating Pass Files
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. 20.3. Providing Icons and Images for Passes
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. 20.4. Preparing Your Passes for Digital Signature
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. 20.5. Signing Passes Digitally
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. 20.6. Distributing Passes Using Email
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. 20.7. Distributing Passes Using Web Services
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. 20.8. Enabling Your iOS Apps to Access Passes on iOS Devices
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. 20.9. Interacting with Passbook Programmatically
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  23. Index
  24. About the Author
  25. Colophon
  26. Copyright
O'Reilly logo

4.12. Deleting Cells and Sections from Table Views

Problem

You want to delete sections and/or cells from table views using animations.

Solution

In order to delete sections from a table view, follow these steps:

  1. First delete the section(s) in your data source, whether you are using a data model like Core Data or a dictionary/array.

  2. Invoke the deleteSections:withRowAnimation: instance method of UITableView on your table view. The first parameter that you need to pass to this method is of type NSIndexSet and this object can be instantiated using the indexSetWithIndex: class method of NSIndexSet class, where the given index is an unsigned integer. Using this approach, you will be able to delete only one section at a time. If you intend to delete more than one section at a time, use the indexSetWithIndexesInRange: class method of NSIndexSet to create the index set using a range and pass that index set to the aforementioned instance method of UITableView.

If you want to delete cells from your table view, follow these steps:

  1. First, delete the cell(s) from your data source. Again, it doesn’t matter if you are using Core Data, a simple dictionary, array, or anything else. The important thing is to delete the objects that represent the table view cells from your data source.

  2. Now, in order to delete the cells that correspond to your data objects, invoke the deleteRowsAtIndexPaths:withRowAnimation: instance method of your table view. The first parameter that you have to pass to this method is an array of type NSArray that must contain objects of type NSIndexPath, with each index path representing one cell in the table view. Each index path has a section and a row, and can be constructed using the indexPathForRow:inSection: class method of NSIndexPath class.

Discussion

In your UI code, sometimes you might need to delete cells and/or sections. For instance, you might have a switch (of type UISwitch; see Recipe 2.2), and when the switch is turned on by the user, you might want to insert a few rows into your table view. After the switch is turned off by the user, you will then want to delete those rows. It’s not always table view cells (rows) that you have to delete. Sometimes you might need to delete a whole section or a few sections simultaneously from your table view. The key for deleting cells and sections from table views is to first delete the data corresponding to those cells/sections from your data source, and then call the appropriate deletion method on the table view. After the deletion method finishes, the table view will refer back to its data source object. If the number of cells/sections in the data source doesn’t match the number of cells/sections in the table view after the deletion is complete, your app will crash. But don’t worry—if you ever do make this mistake, the debug text that gets printed to the console is descriptive enough to point you in the right direction.

Let’s have a look at how we can delete sections from a table view. For this recipe, we will display a table view on a view controller that is displayed inside a navigation controller. Inside the table view, we will display two sections, one for odd numbers and another for even numbers. We will only display 1, 3, 5, and 7 for odd numbers and 0, 2, 4, and 6 for even numbers. For the first exercise, we are going to place a navigation bar button on our navigation bar and make that button responsible for deleting the section with odd numbers in it. Figure 4-16 shows what we want the results to look like.

The user interface to display two sections in a table view and a button that will delete the Odd Numbers section

Figure 4-16. The user interface to display two sections in a table view and a button that will delete the Odd Numbers section

First things first. Let’s define our view controller:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate,
                                              UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableViewNumbers;
@property (nonatomic, strong) NSMutableDictionary *dictionaryOfNumbers;
@property (nonatomic, strong) UIBarButtonItem *barButtonAction;

@end

The tableViewNumbers property is our table view. The barButtonAction property is the bar button that we’ll display on the navigation bar. Last but not least, the dictionaryOfNumbers property is our data source for the table view. In this dictionary, we will place two values of type NSMutableArray that contain our numbers of type NSNumber. They are mutable arrays, so that, later in this chapter, we will be able to delete them individually from the arrays in the dictionary. We will keep the keys for these arrays in our dictionary as static values in the implementation file of our view controller, so that we can later simply extract them from the dictionary using the static keys (if the keys were not static, finding our arrays in the dictionary would have to be done with string comparison, which is slightly more time-consuming than simply associating the object with a static key that doesn’t change during the lifetime of our view controller). Now let’s define the static string keys for our arrays inside the data source dictionary:

#import "ViewController.h"

@implementation ViewController

static NSString *SectionOddNumbers = @"Odd Numbers";
static NSString *SectionEvenNumbers = @"Even Numbers";
...

We now need to populate our data source dictionary with values before we create our table view. Here is the simple method that will take care of populating the dictionary for us:

#pragma mark - Populating the Data Source Dictionary
- (void) constructDictionaryOfNumbers{

  self.dictionaryOfNumbers = [[NSMutableDictionary alloc] init];

  NSMutableArray *arrayOfEvenNumbers = [[NSMutableArray alloc] initWithObjects:
                                        [NSNumber numberWithUnsignedInteger:0],
                                        [NSNumber numberWithUnsignedInteger:2],
                                        [NSNumber numberWithUnsignedInteger:4],
                                        [NSNumber numberWithUnsignedInteger:6],
                                        nil];

  NSMutableArray *arrayOfOddNumbers = [[NSMutableArray alloc] initWithObjects:
                                       [NSNumber numberWithUnsignedInteger:1],
                                       [NSNumber numberWithUnsignedInteger:3],
                                       [NSNumber numberWithUnsignedInteger:5],
                                       [NSNumber numberWithUnsignedInteger:7],
                                       nil];

  [self.dictionaryOfNumbers setObject:arrayOfEvenNumbers
                             forKey:SectionEvenNumbers];

  [self.dictionaryOfNumbers setObject:arrayOfOddNumbers
                             forKey:SectionOddNumbers];

}

So far so good? As you can see, we have two arrays, each of which contains some numbers (one odd and the other even numbers) and we associate them with the SectionEvenNumbers and SectionOddNumbers keys that we declared before in the implementation file of our view controller. Now let’s go ahead and instantiate our table view:

- (void)viewDidLoad
{
  [super viewDidLoad];

  [self constructDictionaryOfNumbers];

  self.barButtonAction =
  [[UIBarButtonItem alloc] initWithTitle:@"Delete Odd Numbers"
                                   style:UIBarButtonItemStylePlain
                                  target:self
                                  action:@selector(deleteOddNumbersSection:)];
  [self.navigationItem setRightBarButtonItem:self.barButtonAction animated:NO];

  self.tableViewNumbers = [[UITableView alloc]
                           initWithFrame:self.view.frame
                           style:UITableViewStyleGrouped];
  self.tableViewNumbers.autoresizingMask = UIViewAutoresizingFlexibleWidth |
                                           UIViewAutoresizingFlexibleHeight;
  self.tableViewNumbers.delegate = self;
  self.tableViewNumbers.dataSource = self;
  [self.view addSubview:self.tableViewNumbers];

}

The next thing we need to do is to populate our table view with data inside our data source dictionary:

#pragma mark - Table View Data Source
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{

  NSInteger result = 0;
  result = [[self.dictionaryOfNumbers allKeys] count];
  return result;

}

- (NSInteger) tableView:(UITableView *)tableView
  numberOfRowsInSection:(NSInteger)section{

  NSInteger result = 0;
  NSString *sectionNameInDictionary = [[self.dictionaryOfNumbers allKeys]
                                       objectAtIndex:section];
  NSArray *sectionArray = [self.dictionaryOfNumbers objectForKey:
                           sectionNameInDictionary];
  result = [sectionArray count];
  return result;

}

- (UITableViewCell *) tableView:(UITableView *)tableView
          cellForRowAtIndexPath:(NSIndexPath *)indexPath{

  UITableViewCell *result = nil;

  static NSString *CellIdentifier = @"NumbersCellIdentifier";

  result = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if (result == nil){
    result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:CellIdentifier];
  }

  NSString *sectionNameInDictionary = [[self.dictionaryOfNumbers allKeys]
                                       objectAtIndex:indexPath.section];
  NSArray *sectionArray = [self.dictionaryOfNumbers objectForKey:
                           sectionNameInDictionary];
  NSNumber *number = [sectionArray objectAtIndex:indexPath.row];

  result.textLabel.text = [NSString stringWithFormat:@"%lu",
                           (unsigned long)[number unsignedIntegerValue]];

  return result;

}

- (NSString *) tableView:(UITableView *)tableView
 titleForHeaderInSection:(NSInteger)section{

  NSString *result = nil;
  result = [[self.dictionaryOfNumbers allKeys] objectAtIndex:section];
  return result;

}

Our navigation button is linked to the deleteOddNumbersSection: selector. This is a method we are going to code now. The purpose of this method, as its name implies, is to find the section that corresponds to all odd numbers in our data source and the table view, and remove that section from both of these. Here is how we will do it:

- (void) deleteOddNumbersSection:(id)paramSender{

  /* First remove the section from our data source */
  NSString *key = SectionOddNumbers;
  NSInteger indexForKey = [[self.dictionaryOfNumbers allKeys]
                           indexOfObject:key];
  if (indexForKey == NSNotFound){
    NSLog(@"Could not find the section in the data source.");
    return;
  }
  [self.dictionaryOfNumbers removeObjectForKey:key];

  /* Then delete the section from the table view */
  NSIndexSet *sectionToDelete = [NSIndexSet indexSetWithIndex:indexForKey];
  [self.tableViewNumbers deleteSections:sectionToDelete
                     withRowAnimation:UITableViewRowAnimationAutomatic];

  /* Finally, remove the button from the navigation bar
   as it is not useful any longer */
  [self.navigationItem setRightBarButtonItem:nil animated:YES];

}

Simple enough. Now, when the user presses the navigation bar button, the Odd Numbers section will disappear from the table view. You can note that there is an animation that gets committed on the table view while the section is being deleted. This is because of the UITableViewRowAnimationAutomatic animation type that we are passing to the withRowAnimation: parameter of the deleteSections:withRowAnimation: method of our table view. Now run the app in iOS Simulator and select Debug Toggle Slow Animations. Then attempt to press the navigation bar button and see what happens. You can see the deletion animation in slow motion. It’s neat, isn’t it? After the deletion is completed, our app will look similar to Figure 4-17.

The section containing odd numbers is removed from the table view

Figure 4-17. The section containing odd numbers is removed from the table view

We now know how to delete sections from table views. Let’s move to deleting cells. We are going to change the functionality of our navigation bar button so that when it is pressed, it will delete all cells in all sections of our table view with a numerical value greater than 2. That includes all odd and even numbers greater than 2. So let’s change our navigation bar button item in the viewDidLoad method of our view controller:

- (void)viewDidLoad
{
  [super viewDidLoad];

  [self constructDictionaryOfNumbers];

  self.barButtonAction =
  [[UIBarButtonItem alloc] initWithTitle:@"Delete Numbers > 2"
                                   style:UIBarButtonItemStylePlain
                                  target:self
                                  action:@selector(deleteNumbersGreaterThan2:)];
  [self.navigationItem setRightBarButtonItem:self.barButtonAction animated:NO];

  self.tableViewNumbers = [[UITableView alloc]
                         initWithFrame:self.view.frame
                         style:UITableViewStyleGrouped];
  self.tableViewNumbers.autoresizingMask = UIViewAutoresizingFlexibleWidth |
  UIViewAutoresizingFlexibleHeight;
  self.tableViewNumbers.delegate = self;
  self.tableViewNumbers.dataSource = self;
  [self.view addSubview:self.tableViewNumbers];

}

Figure 4-18 shows the results of our app running in iPhone Simulator.

A button that will delete all cells containing a number greater than 2

Figure 4-18. A button that will delete all cells containing a number greater than 2

The navigation bar button is now connected to the deleteNumbersGreaterThan2: selector. This is a method that we have to implement in our view controller, but before jumping into coding it straightaway, let’s first define what this method should do:

  1. Find both arrays of odd and even numbers in our data source and grab the index paths (of type NSIndexPath) of those numbers that are greater than 2. We will use these index paths to later delete the corresponding cells from the table view.

  2. Delete all the numbers greater than 2 from our data source, in both the even and odd number dictionaries.

  3. Delete the relevant cells from the table view. We collected the index paths of these cells in the first step.

  4. Remove the navigation bar button, since it won’t be of any use after the relevant cells have been deleted from the data source and the table view. Alternatively, if you want, you could just disable this button—but I think removing that button provides a better user experience, since a disabled button is really of no use to the user.

- (void) deleteNumbersGreaterThan2:(id)paramSender{

  NSMutableArray *arrayOfIndexPathsToDelete = [[NSMutableArray alloc] init];
  NSMutableArray *arrayOfNumberObjectsToDelete = [[NSMutableArray alloc] init];

  /* Step 1: gather the objects we have to delete from our data source
   and their index paths */
  __block NSUInteger keyIndex = 0;
  [self.dictionaryOfNumbers enumerateKeysAndObjectsUsingBlock:
   ^(NSString *key, NSMutableArray *object, BOOL *stop) {

     [object enumerateObjectsUsingBlock:
      ^(NSNumber *number, NSUInteger numberIndex, BOOL *stop) {

        if ([number unsignedIntegerValue] > 2){
          NSIndexPath *indexPath = [NSIndexPath indexPathForRow:numberIndex
                                                      inSection:keyIndex];
          [arrayOfIndexPathsToDelete addObject:indexPath];
          [arrayOfNumberObjectsToDelete addObject:number];
        }

     }];

     keyIndex++;
  }];

  /* Step 2: delete the objects from the data source */
  if ([arrayOfNumberObjectsToDelete count] > 0){
    NSMutableArray *arrayOfOddNumbers = [self.dictionaryOfNumbers
                                         objectForKey:SectionOddNumbers];
    NSMutableArray *arrayOfEvenNumbers = [self.dictionaryOfNumbers
                                          objectForKey:SectionEvenNumbers];
    [arrayOfNumberObjectsToDelete enumerateObjectsUsingBlock:
     ^(NSNumber *numberToDelete, NSUInteger idx, BOOL *stop) {
       if ([arrayOfOddNumbers indexOfObject:numberToDelete] != NSNotFound){
         [arrayOfOddNumbers removeObject:numberToDelete];
       }
       if ([arrayOfEvenNumbers indexOfObject:numberToDelete] != NSNotFound){
         [arrayOfEvenNumbers removeObject:numberToDelete];
       }
       [arrayOfEvenNumbers removeObject:numberToDelete];
    }];
  }  /* Step 3: delete the cells that correspond to the objects */
  NSArray *arrayOfPaths = [[NSArray alloc]
                           initWithArray:arrayOfIndexPathsToDelete];
  [self.tableViewNumbers
   deleteRowsAtIndexPaths:arrayOfPaths
   withRowAnimation:UITableViewRowAnimationAutomatic];

  [self.navigationItem setRightBarButtonItem:nil animated:YES];

}

After the user presses the button on the navigation bar, all cells containing a number greater than 2 will be deleted from our data source, and the table view and our app will look like Figure 4-19.

We have deleted all cells with a value greater than 2

Figure 4-19. We have deleted all cells with a value greater than 2

See Also

Recipe 2.2

The best content for your career. Discover unlimited learning on demand for around $1/day.