SlideShare a Scribd company logo
Ios 7 Programming Cookbook 2nd Edition Vandad
Nahavandipoor download
https://ebookbell.com/product/ios-7-programming-cookbook-2nd-
edition-vandad-nahavandipoor-4427758
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Ios 7 Programming Fundamentals Matt Neuburg
https://ebookbell.com/product/ios-7-programming-fundamentals-matt-
neuburg-38546402
Ios 7 Programming Pushing The Limits Rob Napier Mugunth Kumar
https://ebookbell.com/product/ios-7-programming-pushing-the-limits-
rob-napier-mugunth-kumar-4653670
Programming Ios 7 4th Edition Neuburg Matt
https://ebookbell.com/product/programming-ios-7-4th-edition-neuburg-
matt-22034556
Windows Phone 7 Programming For Android And Ios Developers 1st Edition
Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-1st-edition-zhinan-zhou-2349820
Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-zhinan-zhou-5469884
Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou
Robert Zhu Pei Zheng Baijian Yang
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-zhinan-zhou-robert-zhu-pei-zheng-baijian-
yang-43144166
Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-zhinan-zhou-23142176
Windows Phone 7 Programming For Android And Ios Developers 1st Edition
Zhinan Zhou
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-1st-edition-zhinan-zhou-36137142
Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou
Robert Zhu Pei Zheng Baijian Yang
https://ebookbell.com/product/windows-phone-7-programming-for-android-
and-ios-developers-zhinan-zhou-robert-zhu-pei-zheng-baijian-
yang-43144164
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Vandad Nahavandipoor
iOS 7 Programming Cookbook
iOS 7 Programming Cookbook
by Vandad Nahavandipoor
Copyright © 2014 Vandad Nahavandipoor. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
alsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformation,contactourcorporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editors: Andy Oram and Rachel Roumeliotis
Production Editor: Christopher Hearse
Copyeditor: Zyg Group, LLC
Proofreader: Julie Van Keuren
Indexer: Angela Howard
Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrator: Rebecca Demarest
October 2013: First Edition
Revision History for the First Edition:
2013-10-09: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449372422 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc., iOS 7 Programming Cookbook, the image of a Cowan’s shrew tenrec, and related trade dress are
trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-37242-2
[QG]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Implementing Controllers and Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. Displaying Alerts with UIAlertView 23
1.2. Creating and Using Switches with UISwitch 32
1.3. Customizing the UISwitch 36
1.4. Picking Values with the UIPickerView 39
1.5. Picking the Date and Time with UIDatePicker 45
1.6. Implementing Range Pickers with UISlider 50
1.7. Customizing the UISlider 54
1.8. Grouping Compact Options with UISegmentedControl 59
1.9. Presenting and Managing Views with UIViewController 63
1.10. Presenting Sharing Options with UIActivityViewController 67
1.11. Presenting Custom Sharing Options with UIActivityViewController 73
1.12. Implementing Navigation with UINavigationController 79
1.13. Manipulating a Navigation Controller’s Array of View Controllers 85
1.14. Displaying an Image on a Navigation Bar 86
1.15. Adding Buttons to Navigation Bars Using UIBarButtonItem 88
1.16. Presenting Multiple View Controllers with UITabBarController 94
1.17. Displaying Static Text with UILabel 101
1.18. Customizing the UILabel 105
1.19. Accepting User Text Input with UITextField 108
1.20. Displaying Long Lines of Text with UITextView 118
1.21. Adding Buttons to the User Interface with UIButton 123
1.22. Displaying Images with UIImageView 127
1.23. Creating Scrollable Content with UIScrollView 132
1.24. Loading Web Pages with UIWebView 137
1.25. Displaying Progress with UIProgressView 141
1.26. Constructing and Displaying Styled Texts 143
iii
1.27. Presenting Master-Detail Views with UISplitViewController 148
1.28. Enabling Paging with UIPageViewController 153
1.29. Displaying Popovers with UIPopoverController 158
2. Creating Dynamic and Interactive User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
2.1. Adding Gravity to Your UI Components 171
2.2. Detecting and Reacting to Collisions Between UI Components 172
2.3. Animating Your UI Components with a Push 180
2.4. Attaching Multiple Dynamic Items to Each Other 184
2.5. Adding a Dynamic Snap Effect to Your UI Components 189
2.6. Assigning Characteristics to Your Dynamic Effects 192
3. Auto Layout and the Visual Format Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
3.1. Placing UI Components in the Center of the Screen 201
3.2. Defining Horizontal and Vertical Constraints with the Visual Format
Language 203
3.3. Utilizing Cross View Constraints 210
3.4. Configuring Auto Layout Constraints in Interface Builder 217
4. Constructing and Using Table Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
4.1. Populating a Table View with Data 225
4.2. Using Different Types of Accessories in a Table View Cell 229
4.3. Creating Custom Table View Cell Accessories 232
4.4. Enabling Swipe Deletion of Table View Cells 235
4.5. Constructing Headers and Footers in Table Views 237
4.6. Displaying Context Menus on Table View Cells 246
4.7. Moving Cells and Sections in Table Views 251
4.8. Deleting Cells and Sections from Table Views 257
4.9. Utilizing the UITableViewController for Easy Creation of Table Views 268
4.10. Displaying a Refresh Control for Table Views 274
5. Building Complex Layouts with Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
5.1. Constructing Collection Views 281
5.2. Assigning a Data Source to a Collection View 284
5.3. Providing a Flow Layout to a Collection View 285
5.4. Providing Basic Content to a Collection View 288
5.5. Feeding Custom Cells to Collection Views Using .xib Files 294
5.6. Handling Events in Collection Views 299
5.7. Providing a Header and a Footer in a Flow Layout 303
5.8. Adding Custom Interactions to Collection Views 308
iv | Table of Contents
5.9. Providing Contextual Menus on Collection View Cells 311
6. Storyboards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
6.1. Adding a Navigation Controller to a Storyboard 316
6.2. Passing Data from One Screen to Another 318
6.3. Adding a Tab Bar Controller to a Storyboard 325
6.4. Introducing Custom Segue Transitions to Your Storyboard 328
6.5. Placing Images and Other UI Components on Storyboards 332
7. Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
7.1. Constructing Block Objects 342
7.2. Accessing Variables in Block Objects 346
7.3. Invoking Block Objects 352
7.4. Performing UI-Related Tasks with GCD 354
7.5. Executing Non-UI Related Tasks Synchronously with GCD 358
7.6. Executing Non-UI Related Tasks Asynchronously with GCD 361
7.7. Performing Tasks after a Delay with GCD 368
7.8. Performing a Task Only Once with GCD 371
7.9. Grouping Tasks Together with GCD 373
7.10. Constructing Your Own Dispatch Queues with GCD 377
7.11. Running Tasks Synchronously with Operations 380
7.12. Running Tasks Asynchronously with Operations 387
7.13. Creating Dependency Between Operations 393
7.14. Creating Timers 395
7.15. Creating Concurrency with Threads 400
7.16. Invoking Background Methods 406
7.17. Exiting Threads and Timers 407
8. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
8.1. Enabling Security and Protection for Your Apps 418
8.2. Storing Values in the Keychain 422
8.3. Finding Values in the Keychain 424
8.4. Updating Existing Values in the Keychain 429
8.5. Deleting Exiting Values in the Keychain 432
8.6. Sharing Keychain Data Between Multiple Apps 434
8.7. Writing to and Reading Keychain Data from iCloud 440
8.8. Storing Files Securely in the App Sandbox 443
8.9. Securing Your User Interface 446
9. Core Location and Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
9.1. Creating a Map View 450
9.2. Handling the Events of a Map View 452
Table of Contents | v
9.3. Pinpointing the Location of a Device 453
9.4. Displaying Pins on a Map View 455
9.5. Displaying Pins with Different Colors on a Map View 459
9.6. Displaying Custom Pins on a Map View 465
9.7. Converting Meaningful Addresses to Longitude and Latitude 468
9.8. Converting Longitude and Latitude to a Meaningful Address 470
9.9. Searching on a Map View 472
9.10. Displaying Directions on the Map 475
10. Implementing Gesture Recognizers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
10.1. Detecting Swipe Gestures 483
10.2. Detecting Rotation Gestures 485
10.3. Detecting Panning and Dragging Gestures 489
10.4. Detecting Long-Press Gestures 491
10.5. Detecting Tap Gestures 495
10.6. Detecting Pinch Gestures 497
11. Networking, JSON, XML, and Sharing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
11.1. Downloading Asynchronously with NSURLConnection 501
11.2. Handling Timeouts in Asynchronous Connections 504
11.3. Downloading Synchronously with NSURLConnection 506
11.4. Modifying a URL Request with NSMutableURLRequest 508
11.5. Sending HTTP GET Requests with NSURLConnection 509
11.6. Sending HTTP POST Requests with NSURLConnection 511
11.7. Sending HTTP DELETE Requests with NSURLConnection 513
11.8. Sending HTTP PUT Requests with NSURLConnection 514
11.9. Serializing Arrays and Dictionaries into JSON 516
11.10. Deserializing JSON into Arrays and Dictionaries 518
11.11. Integrating Social Sharing into Your Apps 521
11.12. Parsing XML with NSXMLParser 525
12. Audio and Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
12.1. Playing Audio Files 531
12.2. Handling Interruptions While Playing Audio 534
12.3. Recording Audio 535
12.4. Handling Interruptions While Recording Audio 542
12.5. Playing Audio over Other Active Sounds 543
12.6. Playing Video Files 547
12.7. Capturing Thumbnails from Video Files 551
12.8. Accessing the Music Library 554
13. Address Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
vi | Table of Contents
13.1. Requesting Access to the Address Book 564
13.2. Retrieving a Reference to an Address Book 568
13.3. Retrieving All the People in the Address Book 571
13.4. Retrieving Properties of Address Book Entries 573
13.5. Inserting a Person Entry into the Address Book 577
13.6. Inserting a Group Entry into the Address Book 581
13.7. Adding Persons to Groups 584
13.8. Searching the Address Book 587
13.9. Retrieving and Setting a Person’s Address Book Image 592
14. Files and Folder Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
14.1. Finding the Paths of the Most Useful Folders on Disk 603
14.2. Writing to and Reading from Files 605
14.3. Creating Folders on Disk 610
14.4. Enumerating Files and Folders 612
14.5. Deleting Files and Folders 618
14.6. Saving Objects to Files 621
15. Camera and the Photo Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
15.1. Detecting and Probing the Camera 627
15.2. Taking Photos with the Camera 632
15.3. Taking Videos with the Camera 636
15.4. Storing Photos in the Photo Library 639
15.5. Storing Videos in the Photo Library 644
15.6. Retrieving Photos and Videos from the Photo Library 646
15.7. Retrieving Assets from the Assets Library 649
15.8. Editing Videos on an iOS Device 656
16. Multitasking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
16.1. Detecting the Availability of Multitasking 664
16.2. Completing a Long-Running Task in the Background 665
16.3. Adding Background Fetch Capabilities to Your Apps 669
16.4. Playing Audio in the Background 678
16.5. Handling Location Changes in the Background 682
16.6. Saving and Loading the State of Multitasking Apps 684
16.7. Handling Network Connections in the Background 688
16.8. Opting Out of Multitasking 691
17. Notifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
17.1. Sending Notifications 694
17.2. Listening for and Reacting to Notifications 696
17.3. Listening and Reacting to Keyboard Notifications 700
Table of Contents | vii
17.4. Scheduling Local Notifications 707
17.5. Listening for and Reacting to Local Notifications 711
17.6. Handling Local System Notifications 714
17.7. Setting Up Your App for Push Notifications 718
17.8. Delivering Push Notifications to Your App 724
17.9. Reacting to Push Notifications 732
18. Core Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
18.1. Creating a Core Data Model with Xcode 737
18.2. Generating Class Files for Core Data Entities 741
18.3. Creating and Saving Data Using Core Data 745
18.4. Reading Data from Core Data 747
18.5. Deleting Data from Core Data 750
18.6. Sorting Data in Core Data 752
18.7. Boosting Data Access in Table Views 754
18.8. Implementing Relationships in Core Data 761
18.9. Fetching Data in the Background 768
18.10. Using Custom Data Types in Your Core Data Model 772
19. Dates, Calendars, and Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
19.1. Requesting Permission to Access Calendars 784
19.2. Retrieving Calendar Groups on an iOS Device 790
19.3. Adding Events to Calendars 792
19.4. Accessing the Contents of Calendars 796
19.5. Removing Events from Calendars 799
19.6. Adding Recurring Events to Calendars 803
19.7. Retrieving the Attendees of an Event 808
19.8. Adding Alarms to Calendars 811
19.9. Handling Event Changed Notifications 814
19.10. Presenting Event View Controllers 816
19.11. Presenting Event Edit View Controllers 822
20. Graphics and Animations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
20.1. Enumerating and Loading Fonts 833
20.2. Drawing Text 835
20.3. Constructing, Setting, and Using Colors 836
20.4. Drawing Images 841
20.5. Constructing Resizable Images 845
20.6. Drawing Lines 850
20.7. Constructing Paths 858
20.8. Drawing Rectangles 862
20.9. Adding Shadows to Shapes 866
viii | Table of Contents
20.10. Drawing Gradients 873
20.11. Moving Shapes Drawn on Graphic Contexts 882
20.12. Scaling Shapes Drawn on Graphic Contexts 886
20.13. Rotating Shapes Drawn on Graphic Contexts 889
20.14. Animating and Moving Views 890
20.15. Animating and Scaling Views 900
20.16. Animating and Rotating Views 901
20.17. Capturing a Screenshot of Your View into an Image 903
21. Core Motion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907
21.1. Detecting the Availability of an Accelerometer 908
21.2. Detecting the Availability of a Gyroscope 910
21.3. Retrieving Accelerometer Data 911
21.4. Detecting Shakes on an iOS Device 915
21.5. Retrieving Gyroscope Data 916
22. iCloud. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
22.1. Setting Up Your App for iCloud 920
22.2. Storing and Synchronizing Dictionaries in iCloud 924
22.3. Creating and Managing Folders for Apps in iCloud 929
22.4. Searching for Files and Folders in iCloud 936
22.5. Storing User Documents in iCloud 946
22.6. Managing the State of Documents in iCloud 961
23. Pass Kit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 965
23.1. Creating Pass Kit Certificates 968
23.2. Creating Pass Files 975
23.3. Providing Icons and Images for Passes 984
23.4. Preparing Your Passes for Digital Signature 987
23.5. Signing Passes Digitally 989
23.6. Distributing Passes Using Email 993
23.7. Distributing Passes Using Web Services 995
23.8. Enabling Your iOS Apps to Access Passes on iOS Devices 997
23.9. Interacting with Passbook Programmatically 1003
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007
Table of Contents | ix
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Preface
This edition of the book is not just an update, but a total remake of the previous edition.
iOS 7 changed everything: the look and feel, the way we use our iOS devices, and most
importantly, the way we program for iOS devices. This called for a substantial rewrite
indeed. I have added roughly 50 new recipes to this book, talking about things such as
UIKit dynamics, collection views, the keychain, push notifications, and whatnot. I have
also gone through all the example codes and figures and updated them for iOS 7.
iOS 7 is a huge step forward for this amazing operating system that we all, as program‐
mers and users, have grown to love and enjoy programming for. You must have noticed
how the focus of iOS 7 is on being dynamic: how your UI should adapt to various
movements and motions that can be applied to the device. What I mean by that is Apple
wants developers to really look at the details of their apps and bring real-world physics
and dynamics into them. That’s why Apple introduced UIKit Dynamics to the SDK, and
that is why this book has a whole chapter dedicated to this concept. The more expensive
a high-end device such as the new iPhone becomes, the more demanding the users will
get as well. Nobody blames them, though! They have just bought a fantastic and top-
of-the-line new iPhone or iPad and they want to see amazing apps running on them,
leveraging all the capabilities that those devices have to offer.
That is why now more than ever developers have to get an in-depth knowledge of the
SDK and what the SDK has to offer to the developers so that we can create better and
faster apps for iOS users. Apple introduced a lot of cool new APIs to the iOS 7 SDK, and
we are going to explore them in this book.
The focus of iOS 7 is dynamics!
Before you read about this book, maybe you’d like to know about my background a bit
and how I can help you through this journey. I will just briefly let you know who I am
and how I got to love iOS. I started out writing Basic code for my Commodore 64 when
Iwasakid.IthenmovedontobuymyownPCandstartedexperimentingwithAssembly
code. At first, it was 8-bit Assembly for DOS. I then moved onto writing my own hobby
xi
operating system, which was never really released as a commercial product, for 32-bit
Intel x86 CPU architectures.
Among all the programming languages that I have programmed in, Assembly and
Objective-C are the two that have really been different from the others, and I’ve really
liked them. Assembly because of the purity of the language: a command does only one
thing and does that one thing well. I believe that I like Objective-C for the same reason,
and in fact iOS shares the same trait with Assembly and Objective-C. Even though iOS
is an operating system and not a programming language, whatever it does, it does it best
and better than its rivals. From its simplicity to the sheer power that you can harvest
from the software and the hardware combined, using technologies such as GCD, the
bar that iOS has set in terms of ease of use and beauty is unprecedented.
This edition of the book has seen all the recipes inside all chapters completely renewed
for iOS 7. All screenshots have been updated, and many more recipes—such as those
related to security and the keychain, UI dynamics, collection views, push and local
notifications, and many more—have exclusively been written for this edition of the
book. I really have had a fun time writing this edition of the book, and packed as it is
with new features, I hope you’ll enjoy reading it. May it be a valuable addition to your
tech-book library.
Audience
I assume you are comfortable with the iOS development environment and know how
to create an app for the iPhone or iPad. This book does not get novice programmers
started but presents useful ways to get things done for iOS programmers ranging from
novices to experts.
Organization of This Book
In this book, we will discuss frameworks and classes that are available in the iOS 7 SDK.
This book does its best to teach you the latest and the greatest APIs. As you know, some
users of your apps may still be on older versions of iOS, so please consider those users
and choose your APIs wisely, depending on the minimum iOS version that you want to
target with your apps.
Apple has recommended that you write your apps so that they support and run on iOS
6 and iOS 7. This means you need to use the latest SDK as your base SDK (the SDK that
youusetocompileyourapp)andchooseiOS6asyourtarget,ifthat’swhatyourbusiness
requirements dictate. If you are required to write your app to support only iOS 7, then
you are in for a lot of fun, as you can use all the cool APIs that have been introduced in
iOS 7 and discussed in this book.
xii | Preface
Here is a concise breakdown of the material each chapter covers:
Chapter 1, Implementing Controllers and Views
Explains how Objective-C classes are structured and how objects can be instanti‐
ated. The chapter talks about properties and delegates and subscripting by keys and
indexes. Even if you are competent in Objective-C, I strongly suggest that you read
this chapter, even if you only skim through it, to understand the basic material that
is used in the rest of the book. In this chapter, we will also explore the common
usage of various UI components, such as alert views, segmented controls, switches,
and labels. We will also talk about customizing these components with the latest
APIs provided in the SDK.
Chapter 2, Creating Dynamic and Interactive User Interfaces
Talks about UIKit Dynamics, the newest addition to the UIKit framework. These
dynamics allow you to add real-life physics and dynamics to your UI components.
This will allow you to create even livelier user interfaces with very small effort on
your side.
Chapter 3, Auto Layout and the Visual Format Language
Explains how you can take advantage of Auto Layout in the iOS SDK in order to
construct your UI in such a way that it can be resized and stretched to pretty much
any screen dimension.
Chapter 4, Constructing and Using Table Views
Shows how you can work with table views to create professional-looking iOS ap‐
plications. Table views are very dynamic in nature, and as a result, programmers
sometimes have difficulty understanding how they should work with them. By
reading this chapter and trying out the example code, you will gain the knowledge
that is required to comfortably work with table views.
Chapter 5, Building Complex Layouts with Collection Views
Collection views have been available to OS X programmers for quite some time
now, and Apple decided to provide the same APIs to iOS programmers in the iOS
SDK. Collection views are very much like table views, but they are much more
configurable and dynamic. Where in table views we have the concept of sections
and rows in each section, collection views bring columns to the equation as well,
so that you can display many items in one row if you want to. In this chapter we
will have a look at all the great user interfaces that you can create using collection
views.
Chapter 6, Storyboards
Demonstrates the process of storyboarding, the new way to define the connections
between different screens in your app. The great thing about storyboarding is that
you don’t have to know anything about iOS programming to get a simple app run‐
ning. This helps product analysts, product owners, or designers who work inde‐
pendently of developers to gain knowledge of the UI components iOS offers and to
Preface | xiii
buildmorerobustproducts.Programmerscanalsotakeadvantageofstoryboarding
to easily create prototypes. Storyboarding is just fun, whether you do it on paper
or using Xcode.
Chapter 7, Concurrency
As humans, we can do many things simultaneously without thinking much about
it. With advances in computer technology, mobile devices are also able to multitask,
and they provide programmers with tools and mechanisms that can accomplish
more than one task at the same time. This is called concurrency. In this chapter, you
will learn about Grand Central Dispatch, Apple’s preferred way of achieving con‐
currency in iOS. You will also learn about timers, threads, and operations.
Chapter 8, Security
iOS is a very secure operating system, and apps that we write for it also have to
adhere to certain security standards and practices. In this chapter, we will discuss
how you can take advantage of keychain APIs to make your apps more secure. We
will also talk about various steps that you can take to make your user interface more
secure.
Chapter 9, Core Location and Maps
DescribeshowyoushoulduseMapKitandCoreLocationAPIstodeveloplocation-
aware iOS applications. First you will learn about maps, and then you will learn
how to detect a device’s location and tailor your maps with custom annotations.
You will also learn about geocoding and reverse geocoding, as well as some of the
methods of the Core Location framework, which are available only in iOS 7.
Chapter 10, Implementing Gesture Recognizers
Demonstrates how to use gesture recognizers, which enable your users to easily and
intuitively manipulate the graphical interface of your iOS applications. In this
chapter, you will learn how to use all available gesture recognizers in the iOS SDK,
with working examples tested on iOS 7.
Chapter 11, Networking, JSON, XML, and Sharing
Demonstrates the built-in JSON and XML parsers. On top of that, this chapter talks
about various networking APIs and how programmers can build social networking
into our apps to allow our users to share their creations and data to social networks
such as Facebook.
Chapter 12, Audio and Video
Discusses the AV Foundation and Media Player frameworks that are available on
the iOS SDK. You will learn how to play audio and video files and how to handle
interruptions, such as a phone call, while the audio or video is being played. This
chapter also explains how to record audio using an iOS device’s built-in micro‐
phone(s). At the end of the chapter, you will learn how to access the Music Library
and play its media content, all from inside your application.
xiv | Preface
Chapter 13, Address Book
Explains the Address Book framework and how to retrieve contacts, groups, and
their information from the Address Book database on an iOS device. The Address
Book framework is composed entirely of C APIs. Because of this, many Objective-
C developers find it difficult to use this framework, as compared with frameworks
that provide an Objective-C interface. After reading this chapter and trying the
examples for yourself, you will feel much more confident using the Address Book
framework.
Chapter 14, Files and Folder Management
One of the most important tasks that, as developers, we want to perform in our iOS
apps is manipulating files and folders. Whether this means creating, reading from,
writing to, or deleting them, this chapter contains enough material to get you up
and running with file and folder management in the iOS SDK.
Chapter 15, Camera and the Photo Library
Demonstrates how you can determine the availability of front- and back-facing
cameras on an iOS device. You will also learn how to access the photo library using
the Assets Library framework. At the end of the chapter, you will learn about editing
videos right on an iOS device using a built-in view controller.
Chapter 16, Multitasking
Showsmultitasking-awareapplicationsthatrunbeautifullyoniOSdevices.Youwill
learn about background processing, including how to play audio and retrieve users’
locations in the background, as well as how to download content from a URL while
your application is running in the background. On top of that, we will explore some
of the new APIs that iOS 7 provides to us, in order to enable our apps to download
content periodically while in the background or even while our app is not even
running.
Chapter 17, Notifications
Notificationsareobjectsthatcanbecomposedbyasourceanddeliveredtomultiple
recipients.Inthischapter,wewilldiscussnotifications,includinglocalnotifications
and push notifications, along with how you can use the latest capabilities built into
Xcode to easily enable these features in your own apps.
Chapter 18, Core Data
Describes the details of Core Data stacks and what they are made out of. You will
thenbeabletodesignyourownobject-orienteddatamodelsrightintoXcode,using
the Core Data model editor, and also create and retrieve your objects in Core Data.
On top of that, you will learn how to add your own custom data to Core Data and
how to search for data in the background thread, leaving your UI thread ready to
process user events.
Preface | xv
Chapter 19, Dates, Calendars, and Events
Demonstrates the use of the Event Kit and Event Kit UI frameworks in order to
manage calendars and events on an iOS device. You will see how to create, modify,
save, and delete events. You will also learn, through examples, how to add alarms
to calendar events and how to set up CalDAV calendars so that you can share a
single calendar among multiple devices.
Chapter 20, Graphics and Animations
Introduces the Core Graphics framework. You will learn how to draw images and
text on a graphics context; draw lines, rectangles, and paths; and much more. You
will also learn to use the new iOS SDK APIs to capture your views’ contents as
screenshots.
Chapter 21, Core Motion
Explains the Core Motion framework. Using Core Motion, you will access the ac‐
celerometer and the gyroscope on an iOS device. You will also learn how to detect
shakes on a device. Of course, not all iOS devices are equipped with an accelerom‐
eter and a gyroscope, so you will also learn how to detect the availability of the
required hardware.
Chapter 22, iCloud
Shows how to use the iCloud service, which ties devices together and allows them
to share data to provide a seamless user experience as the user moves from one
device to another.
Chapter 23, Pass Kit
Describes Passbook: a virtual wallet, if you will, capable of managing your coupons,
boarding passes, rail and bus tickets, and much more. In this chapter, you will learn
all there is to know in order to be able to create your own digitally signed passes
and distribute them to your users easily.
Additional Resources
From time to time, I refer to official Apple documentation. Some of Apple’s descriptions
are right on the mark, and there is no point in trying to restate them. Throughout this
book, I have listed the most important documents and guides in the official Apple doc‐
umentation that every professional iOS developer should read.
For starters, I suggest that you have a look at the iOS Human Interface Guidelines for
all iOS devices. This document will tell you everything you need to know about devel‐
oping engaging and intuitive user interfaces for all iOS devices. Every iOS programmer
should read this document. In fact, I believe this should be required reading for the
product design and development teams of any company that develops iOS applications.
xvi | Preface
I also suggest that you skim through the “iOS App Programming Guide” in the iOS
Developer Library for some tips and advice on how to make great iOS applications.
iOS 7 brings with itself quite a lot of changes to how UI components appear on the
screen.Wewilltalkatgreatlengthaboutthesechangesandhowyou,astheprogrammer,
can use the latest APIs to create great-looking apps for iOS 7. However, I would like to
suggest that you have a look at the iOS 7 UI Transition Guide provided by Apple, which
outlines all the UI changes that have now been made to the latest version of the SDK.
One of the things you will notice when reading Chapter 16 is the use of block objects.
This book concisely explains block objects, but if you require further details on the
subject, I suggest you read “A Short Practical Guide to Blocks”.
Throughout this book, you will see references to “bundles” and loading images and data
from bundles. You will read a concise overview about bundles in this book, but if you
require further information, head over to the “Bundle Programming Guide”.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Preface | xvii
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available for download at
https://github.com/oreillymedia/iOS7_programming_cookbook.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not need
to contact us for permission unless you’re reproducing a significant portion of the code.
For example, writing a program that uses several chunks of code from this book does
not require permission. Selling or distributing a CD-ROM of examples from O’Reilly
books does require permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a significant amount of ex‐
ample code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “iOS 7 Programming Cookbook
by Vandad Nahavandipoor (O’Reilly). Copyright 2014 Vandad Nahavandipoor,
978-1-4493-7242-2.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online (www.safaribooksonline.com) is an on-
demand digital library that delivers expert content in both book and
video form from the world’s leading authors in technology and busi‐
ness.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.
xviii | Preface
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/iOS7-Programming-Cookbook.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
Andy Oram, my lovely editor, has again done an amazing job going through all the
changes that I made in this edition of the book. In fact, the whole book is updated in
this edition, and all example codes and screenshots have also been updated. I’d like to
alsothankKrzysztofGrobelnyandKrzysztofGutowski,mygreatfriendsandcolleagues,
for tech-reviewing this book. Without their help, this book wouldn’t be in your hands.
I’d like to say thank you to Rachel Roumeliotis, for supporting me and Andy, among all
the other admin work that she did for us behind the scenes. Rachel, you may be quiet,
but we’d have to be blind not to notice your hard work in the background. Also, Meghan
Connolly of O’Reilly has been a fantastic sport, listening to my nagging about paper‐
work, and she has been absolute bliss to work with. A thank-you goes to Jessica Hosman
for helping us a great deal with Git issues. Even though I didn’t believe the simple sol‐
utions that she suggested to me would work, they did, and I looked like a fool.
Last but not least, thank you to Alina Rizzoni, Bruno Packham, and Thomas Packham
for being real friends. I feel blessed to know them, and I appreciate their help and
support.
Preface | xix
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
CHAPTER 1
Implementing Controllers and Views
1.0. Introduction
iOS 7 has introduced a lot of new features to users, as well as tons of new APIs for us
programmers to use and play with. You probably already know that the user interface
has drastically changed in iOS 7. This user interface had stayed intact all the way from
the first version of iOS till now, and because of this, many apps were coded on the
assumption that this user interface would not ever change. Graphic designers are now
faced with the challenge of creating the user interface and thinking about the user ex‐
perience in a way that makes it great for both pre- and post-iOS 7 user interfaces (UIs).
In order to write apps for iOS 7, you need to know some of the basics of the Objective-
C programming language that we will use throughout this book. Objective-C, as its
name implies, is based on C with extensions that allow it to make use of objects. Objects
and classes are fundamental in object-oriented programming (OOP) languages such as
Objective-C, Java, C++, and many others. In Objective-C, like any other object-oriented
language(OOL),youhavenotonlyaccesstoobjects,butalsotoprimitives.Forinstance,
the number –20 (minus twenty) can be expressed simply as a primitive in this way:
NSInteger myNumber = -20;
This simple line of code will define a variable named myNumber with the data type of
NSInteger and sets its value to 20. This is how we define variables in Objective-C. A
variable is a simple assignment of a name to a location in memory. In this case, when
we set 20 as the value of the myNumber variable, we are telling the machine that will
eventually run this piece of code to put the aforementioned value in a memory location
that belongs to the variable myNumber.
All iOS applications essentially use the model-view-controller (MVC) architecture.
Model, view, and controller are the three main components of an iOS application from
an architectural perspective.
1
The model is the brain of the application. It does the calculations and creates a virtual
world for itself that can live without the views and controllers. In other words, think of
a model as a virtual copy of your application, without a face!
Aviewisthewindowthroughwhichyourusersinteractwithyourapplication.Itdisplays
what’s inside the model most of the time, but in addition to that, it accepts users’ inter‐
actions. Any interaction between the user and your application is sent to a view, which
then can be captured by a view controller and sent to the model.
The controller in iOS programming usually refers to the view controllers I just men‐
tioned. Think of a view controller as a bridge between the model and your views. This
controller interprets what is happening on one side and uses that information to alter
the other side as needed. For instance, if the user changes some field in a view, the
controller makes sure the model changes in response. And if the model gets new data,
the controller tells the view to reflect it.
In this chapter, you will learn how to create the structure of an iOS application and how
to use views and view controllers to create intuitive applications.
In this chapter, for most of the user interface (UI) components that we
create, we are using a Single View Application template in Xcode. To
reproduce the examples, follow the instructions in “Creating and Run‐
ning Our First iOS App” on page 2. Make sure that your app is uni‐
versal, as opposed to an iPhone or iPad app. A universal app can run
on both iPhone and iPad.
Creating and Running Our First iOS App
Before we dive any deeper into the features of Objective-C, we should have a brief look
at how to create a simple iOS app in Xcode. Xcode is Apple’s IDE (integrated develop‐
ment environment) that allows you to create, build, and run your apps on iOS Simulator
and even on real iOS devices. We will talk more about Xcode and its features as we go
along, but for now let’s focus on creating and running a simple iOS app. I assume that
you’ve already downloaded Xcode into your computer from the Mac App Store. Once
that step is taken care of, please follow these steps to create and run a simple iOS app:
1. Open Xcode if it’s not already open.
2. From the File menu, choose New Project...
3. In the New Project window that appears, on the lefthand side under the iOS cate‐
gory, choose Application and then on the righthand side choose Single View Ap‐
plication. Then press the Next button.
4. On the next screen, for the Product Name, enter a name that makes sense for you.
For instance, you can set the name of your product as My First iOS App. In the
2 | Chapter 1: Implementing Controllers and Views
Organization Name section, enter your company’s name, or if you don’t have a
company, enter anything else that makes sense to you. The organization name is
quite an important piece of information that you can enter here, but for now, you
don’t have to worry about it too much. For the Company Identifier field, enter
com.mycompany. If you really do own a company or you are creating this app for a
company that you work with, replace mycompany with the actual name of the com‐
pany in question. If you are just experimenting with development on your own,
invent a name. For the Devices section, choose Universal.
5. Onceyouaredonesettingtheaforementionedvalues,simplypresstheNextbutton.
6. You are now being asked by Xcode to save your project to a suitable place. Choose
a suitable folder for your project and press the Create button.
7. Assoonasyourprojectiscreated,youarereadytobuildandrunit.However,before
you begin, make sure that you’ve unplugged all your iOS devices from your com‐
puter. The reason behind this is that once an iOS device is plugged in, by default,
Xcode will attempt to build and run your project on the device, causing some issues
with provisioning profiles (which we haven’t talked about yet). So unplug your iOS
devices and then press the big Run button on the top-lefthand corner of Xcode. If
you cannot find the Run button, go to the Product menu and select the Run menu
item.
Voilà! Your first iOS app is running in iOS Simulator now. Even though the app is not
exactly impressive, simply displaying a white screen in the simulator, this is just the first
step toward our bigger goal of mastering the iOS SDK, so hold on tight as we embark
on this journey together.
Defining and Understanding Variables
All modern programming languages, including Objective-C, have the concept of vari‐
ables. Variables are simple aliases to locations in the memory. Every variable can have
the following properties:
1. A data type, which is either a primitive, such as an integer, or an object
2. A name
3. A value
You don’t always have to set a value for a variable, but you need to specify its type and
its name. Here are a few data types that you will need to know about when writing any
typical iOS app:
1.0. Introduction | 3
Mutable Versus Immutable
If a data type is mutable, you can change if after it is initialized. For
instance, you can change one of the values in a mutable array, or add
or remove values. In contrast, you must provide the values to an im‐
mutable data type when you initialize it, and cannot add to them,
remove them, or change them later. Immutable types are useful be‐
cause they are more efficient, and because they can prevent errors when
the values are meant to stay the same throughout the life of the data.
NSInteger and NSUInteger
Variables of this type can hold integral values such as 10, 20, etc. The NSInteger
type allows negative values as well as positive ones, but the NSUInteger data type
is the Unsigned type, hence the U in its name. Remember, the phrase unsigned in
programming languages in the context of numbers always means that the number
must not be negative. Only a signed data type can hold negative numbers.
CGFloat
Holds floating point variables with decimal points, such as 1.31 or 2.40.
NSString
Allows you to store strings of characters. We will see examples of this later.
NSNumber
Allows you to store numbers as objects.
id
Variables of type id can point to any object of any type. These are called untyped
objects. Whenever you want to pass an object from one place to another but do not
wish to specify its type for whatever reason, you can take advantage of this data
type.
NSDictionary and NSMutableDictionary
These are immutable and mutable variants of hash tables. A hash table allows you
to store a key and to associate a value to that key, such as a key named phone_num
that has the value 05552487700. Read the values by referring to the keys associated
with them.
NSArray and NSMutableArray
Immutableandmutablearraysofobjects.Anarrayisanorderedcollectionofitems.
For instance, you may have 10 string objects that you want to store in memory. An
array could be a good place for that.
NSSet, NSMutableSet, NSOrderedSet, NSMutableOrderedSet
Sets are like arrays in that they can hold series of objects, but they differ from arrays
in that they contain only unique objects. Arrays can hold the same object multiple
4 | Chapter 1: Implementing Controllers and Views
times, but a set can contain only one instance of an object. I encourage you to learn
the difference between arrays and sets and use them properly.
NSData and NSMutableData
Immutable and mutable containers for any data. These data types are perfect when
you want to read the contents of a file, for instance, into memory.
Some of the data types that we talked about are primitive, and some are classes. You’ll
just have to memorize which is which. For instance, NSInteger is a primitive data type,
but NSString is a class, so objects can be instantiated of it. Objective-C, like C and C++,
has the concept of pointers. A pointer is a data type that stores the memory address
where the real data is stored. You should know by now that pointers to classes are
denoted using an asterisk sign:
NSString *myString = @"Objective-C is great!";
Thus, when you want to assign a string to a variable of type NSString in Objective-C,
you simply have to store the data into a pointer of type NSString *. However, if you are
about to store a floating point value into a variable, you wouldn’t specify it as a pointer
since the data type for that variable is not a class:
/* Set the myFloat variable to PI */
CGFloat myFloat = M_PI;
If you wanted to have a pointer to that floating point variable, you could do so as follows:
/* Set the myFloat variable to PI */
CGFloat myFloat = M_PI;
/* Create a pointer variable that points to the myFloat variable */
CGFloat *pointerFloat = &myFloat;
Getting data from the original float is a simple dereference (myFloat), whereas getting
the value of through the pointer requires the use of the asterisk (*pointerFloat). The
pointer can be useful in some situations, such as when you call a function that sets the
value of a floating-point argument and you want to retrieve the new value after the
function returns.
Going back to classes, we probably have to talk a bit more about classes before things
get lost in translation, so let’s do that next.
Creating and Taking Advantage of Classes
A class is a data structure that can have methods, instance variables, and properties,
along with many other features, but for now we are just going to talk about the basics.
Every class has to follow these rules:
1.0. Introduction | 5
• The class has to be derived from a superclass, apart from a few exceptions such as
NSObject and NSProxy classes, which are root classes. Root classes do not have a
superclass.
• It has to have a name that conforms to Cocoa’s naming convention for methods.
• It has to have an interface file that defines the interface of the class.
• It has to have an implementation where you implement the features that you have
promised to deliver in the interface of the class.
NSObject is the root class from which almost every other class is inherited. For this
example, we are going to add a class, named Person, to the project we created in “Cre‐
ating and Running Our First iOS App” on page 2. We are going to then add two prop‐
erties to this class, named firstName and lastName, of type NSString. Follow these
steps to create and add the Person class to your project:
1. In Xcode, while your project is open and in front of you, from the File menu, choose
New → File...
2. On the lefthand side, ensure that under the iOS main section you have chosen the
Cocoa Touch category. Once done, select the Objective-C Class item and press the
Next button.
3. In the Class section, enter Person.
4. In the “Subclass of” section, enter NSObject.
5. Once done, press the Next button, at which point Xcode will ask where you would
like to save this file. Simply save the new class into the folder where you have placed
your project and its files. This is the default selection. Then press the Create button,
and you are done.
You now have two files added to your project: Person.h and Person.m. The former is the
interface and the latter is the implementation file for your Person class. In Objective-
C, .h files are headers, where you define the interface of each class, and .m files are
implementation files where you write the actual implementation of the class.
Now let’s go into the header file of our Person class and define two properties for the
class, of type NSString:
@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@end
Just like a variable, definition of properties has its own format, in this particular order:
6 | Chapter 1: Implementing Controllers and Views
1. The definition of the property has to start with the @property keyword.
2. You then need to specify the qualifiers of the property. nonatomic properties are
not thread-safe. We will talk about thread safety in Chapter 16. You can also specify
assign, copy, weak, strong, or unsafe_unretained as the property qualifiers. We
will read more about these soon too.
3. You then have to specify the data type of the property, such as NSInteger or
NSString.
4. Last but not least, you have to specify a name for the property. The name of the
property has to follow the Apple guidelines.
We said that properties can have various qualifiers. Here are the important qualifiers
that you need to know about:
strong
Properties of this type will be retained by the runtime. These can only be instances
of classes. In other words, you cannot retain a value into a property of type strong
if the value is a primitive. You can retain objects, but not primitives.
copy
The same as strong, but when you assign to properties of this type, the runtime
will make a copy of the object on the right side of the assignment. The object on
the righthand side of the assignment must conform to the NSCopying or NSMutable
Copying protocol.
assign
Objects or primitive values that are set as the value of a property of type assign will
not be copied or retained by that property. For primitive properties, this qualifier
will create a memory address where you can put the primitive data. For objects,
properties of this type will simply point to the object on the righthand side of the
equation.
unsafe_unretained
The same as the assign qualifier.
weak
The same as the assign qualifier with one big difference. In the case of objects,
when the object that is assigned to a property of this type is released from memory,
the runtime will automatically set the value of this property to nil.
We now have a Person class with two properties: firstName and lastName. Let’s go back
to our app delegate’s implementation (AppDelegate.m) file and instantiate an object of
type Person:
#import "AppDelegate.h"
#import "Person.h"
1.0. Introduction | 7
@implementation AppDelegate
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
Person *person = [[Person alloc] init];
person.firstName = @"Steve";
person.lastName = @"Jobs";
self.window = [[UIWindow alloc]
initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
We are allocating and initializing our instance of the Person class in this example. You
may not know what that means yet, but continue to the “Adding Functionality to Classes
with Methods” on page 8 section and you will find out.
Adding Functionality to Classes with Methods
Methods are building blocks of classes. For instance, a class named Person can have
logical functionalities such as walk, breathe, eat, and drink. These functionalities are
usually encapsulated in methods.
A method can take parameters, which are variables that the caller passes when calling
themethodandarevisibleonlytothemethod.Forinstance,inasimpleworld,wewould
have a walk method for our Person class. However, if you want, you can add a parameter
or argument to the method and name it walkingSpeed of type CGFloat, so that when
another programmer calls that method on your class, she can specify the speed at which
the person has to walk. You, as the programmer of that class, would then write the
appropriate code for your class to handle different speeds of walking. Don’t worry if this
all sounds like too much, but have a look at the following example, where I have added
a method to the implementation file we created in “Creating and Taking Advantage of
Classes” on page 5 for our Person class:
#import "Person.h"
@implementation Person
- (void) walkAtKilometersPerHour:(CGFloat)paramSpeedKilometersPerHour{
/* Write the code for this method here */
}
- (void) runAt10KilometersPerHour{
/* Call the walk method in our own class and pass the value of 10 */
8 | Chapter 1: Implementing Controllers and Views
[self walkAtKilometersPerHour:10.0f];
}
@end
A typical method has the following qualities in Objective-C:
1. A prefix to tell the compiler whether the method is an instance method (-) or a class
method (+). An instance method can be accessed only after the programmer allo‐
cates and initializes an instance of your class. A class method can be accessed by
calling it directly from the class itself. Don’t worry if this all sounds complicated.
We will see examples of these methods in this book, so don’t get hung up on this
for now.
2. A data type for the method, if the method returns any value. In our example, we
have specified void, telling the compiler that we are not returning anything.
3. The first part of the method name followed by the first parameter. You don’t nec‐
essarily have to have any parameters for a method. You can have methods that take
no parameters.
4. The list of subsequent parameters following the first parameter.
Let me show you an example of a method with two parameters:
- (void) singSong:(NSData *)paramSongData loudly:(BOOL)paramLoudly{
/* The parameters that we can access here in this method are:
paramSongData (to access the song's data)
paramLoudly will tell us if we have to sing the song loudly or not
*/
}
It’s important to bear in mind that every parameter in every method has an external and
an internal name. The external name is part of the method, whereas the internal part is
the actual name or alias of the parameter that can be used inside the method’s imple‐
mentation. In the previous example, the external name of the first parameter is sing‐
Song, whereas its internal name is paramSongData. The external name of the second
parameter is loudly, but its internal name is paramLoudly. The method’s name and the
external names of its parameters combine to form what is known as the selector for the
method. The selector for the aforementioned method in this case would be sing
Song:loudly:. A selector, as you will later see in this book, is the runtime identifier of
every method. No two methods inside a single class can have the same selector.
In our example, we have defined three methods for our Person class, inside its imple‐
mentation file (Person.m):
• walkAtKilometersPerHour:
• runAt10KilometersPerHour
1.0. Introduction | 9
• singSong:loudly:
If we want to be able to use any of these methods from the outside world—for instance,
from the app delegate—we should expose those methods in our interface file (Person.h):
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
- (void) walkAtKilometersPerHour:(CGFloat)paramSpeedKilometersPerHour;
- (void) runAt10KilometersPerHour;
/* Do not expose the singSong:loudly: method to the outside world.
That method is internal to our class. So why should we expose it? */
@end
Given this interface file, a programmer can call the walkAtKilometersPerHour: and
the runAt10KilometersPerHour methods from outside the Person class, but not the
singSong:loudly: method because it has not been exposed in the file. So let’s go ahead
and try to call all three of these methods from our app delegate to see what happens!
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
Person *person = [[Person alloc] init];
[person walkAtKilometersPerHour:3.0f];
[person runAt10KilometersPerHour];
/* If you uncomment this line of code, the compiler will give
you an error telling you this method doesn't exist on the Person class */
//[person singSong:nil loudly:YES];
self.window = [[UIWindow alloc]
initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Now we know how to define and call instance methods, but what about class methods?
Let’s first find out what class methods are and how they differ from instance methods.
An instance method is a method that relates to an instance of a class. For instance, in
our Person class, you can instantiate this class twice to create two distinct persons in a
hypothetical game that you are working on and have one of those persons walk at the
speed of 3 kilometers an hour while the other person walks at 2 kilometers an hour.
10 | Chapter 1: Implementing Controllers and Views
Even though you have written the code for the walking instance method only once,
when two separate instances of the Person class are created at runtime, the calls to the
instance methods will be routed to the appropriate instance of this class.
In contrast, class methods work on the class itself. For instance, in a game where you
have instances of a class named Light that light the scenery of your game, you may have
a dimAllLights class method on this class that a programmer can call to dim all lights
in the game, no matter where they are placed. Let’s have a look at an example of a class
method on our Person class:
#import "Person.h"
@implementation Person
+ (CGFloat) maximumHeightInCentimeters{
return 250.0f;
}
+ (CGFloat) minimumHeightInCentimeters{
return 40.0f;
}
@end
The maximumHeightInCentimeters method is a class method that returns the hypo‐
thetical maximum height of any person in centimeters. The minimumHeightInCentim
eters class method returns the minimum height of any person. Here is how we would
then expose these methods in the interface of our class:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, assign) CGFloat currentHeight;
+ (CGFloat) maximumHeightInCentimeters;
+ (CGFloat) minimumHeightInCentimeters;
@end
We have also added a new floating point property to our Person class
named currentHeight. This allows instances of this class to be able to
store their height in memory for later reference, just like their first or
last names.
And in our app delegate, we would proceed to use these new methods like so:
1.0. Introduction | 11
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
Person *steveJobs = [[Person alloc] init];
steveJobs.firstName = @"Steve";
steveJobs.lastName = @"Jobs";
steveJobs.currentHeight = 175.0f; /* Centimeters */
if (steveJobs.currentHeight >= [Person minimumHeightInCentimeters] &&
steveJobs.currentHeight <= [Person maximumHeightInCentimeters]){
/* The height of this particular person is in the acceptable range */
} else {
/* This person's height is not in the acceptable range */
}
self.window = [[UIWindow alloc]
initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Conforming to Requirements of Other Classes with Protocols
Objective-C has the concept of a protocol. This is a concept found in many other lan‐
guages (always under a different term, it seems); for instance, it is called an interface in
Java. A protocol, as its name implies, is a set of rules that classes can abide by in order
to be used in certain ways. A class that follows the rules is said to conform to the protocol.
Protocols are different from actual classes in that they do not have an implementation.
They are just rules. For instance, every car has wheels, doors, and a main body color,
among many other things. Let’s define these properties in a protocol named Car. Simply
follow these steps to create a header file that can contain our Car protocol:
1. In Xcode, while your project is open, from the File menu, select New → File...
2. In the new dialog, on the lefthand side, make sure that you’ve selected Cocoa Touch
undertheiOSmaincategory.Oncedone,ontherighthandsideofthedialog,choose
“Objective-C protocol” and then press the Next button.
3. On the next screen, under the Protocol section, enter Car as the protocol’s name
and then press the Next button.
4. You will now be asked to save your protocol on disk. Simply choose a location,
usually in your project’s folder, and press the Create button.
Xcode will now create a file for you named Car.h with content like this:
#import <Foundation/Foundation.h>
@protocol Car <NSObject>
12 | Chapter 1: Implementing Controllers and Views
@end
So let’s go ahead and define the properties for the Car protocol, as we discussed earlier
in this section:
#import <Foundation/Foundation.h>
@protocol Car <NSObject>
@property (nonatomic, copy) NSArray *wheels;
@property (nonatomic, strong) UIColor *bodyColor;
@property (nonatomic, copy) NSArray *doors;
@end
Now that our protocol has been defined, let’s create a class for a car, such as Jaguar, and
then make that class conform to our protocol. Simply follow the steps provided in
“Creating and Taking Advantage of Classes” on page 5 to create a class named Jaguar
and then make it conform to the Car protocol like so:
#import <Foundation/Foundation.h>
#import "Car.h"
@interface Jaguar : NSObject <Car>
@end
If you build your project now, you will notice that the compiler will give you a few
warnings such as this:
Auto property synthesis will not synthesize property declared in a protocol
This is simply telling you that your Jaguar class is attempting to conform to the Car
protocol but is not really implementing the required properties and/or methods in that
protocol. So you should now know that a protocol can have required or optional items,
and that you denote them by the @optional or the @required keywords. The default
qualifier is @required, and since in our Car protocol we didn’t specify the qualifier
explicitly, the compiler has chosen @required for us implicitly. Therefore, the Jaguar
class now has to implement everything that is required from it by the Car protocol, like
so:
#import <Foundation/Foundation.h>
#import "Car.h"
@interface Jaguar : NSObject <Car>
@property (nonatomic, copy) NSArray *wheels;
@property (nonatomic, strong) UIColor *bodyColor;
@property (nonatomic, copy) NSArray *doors;
@end
1.0. Introduction | 13
Perfect. Now you have an understanding of the basics of protocols and how they work
and how you can define them. We will read more about them later in this book, so what
you know right now about protocols is quite sufficient.
Storing Items in and Retrieving Them from Collections
Collections are instances of objects and can hold other objects. One of the primary
collections is an array, which instantiates either NSArray or NSMutableArray. You can
store any object in an array, and an array can contain more than one instance of the
same object. Here is an example where we create an array of three strings:
NSArray *stringsArray = @[
@"String 1",
@"String 2",
@"String 3"
];
__unused NSString *firstString = stringsArray[0];
__unused NSString *secondString = stringsArray[1];
__unused NSString *thirdString = stringsArray[2];
The __unused macro tells the compiler not to complain when a vari‐
able, such as the firstString variable in our example, is declared but
never used. The default behavior of the compiler is that it throws a
warning to the console saying a variable is not used. Our brief exam‐
ple has declared the variables but not used them, so adding the afore‐
mentioned macro to the beginning of the variable declaration keeps
the compiler and ourselves happy.
A mutable array is an array that can be mutated and changed after it has been created.
An immutable array, like we saw, cannot be tampered with after it is created. Here is an
example of an immutable array:
NSString *string1 = @"String 1";
NSString *string2 = @"String 2";
NSString *string3 = @"String 3";
NSArray *immutableArray = @[string1, string2, string3];
NSMutableArray *mutableArray = [[NSMutableArray alloc]
initWithArray:immutableArray];
[mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:1];
[mutableArray removeObjectAtIndex:1];
[mutableArray setObject:string1 atIndexedSubscript:0];
14 | Chapter 1: Implementing Controllers and Views
NSLog(@"Immutable array = %@", immutableArray);
NSLog(@"Mutable Array = %@", mutableArray);
The output of this program is as follows:
Immutable array = (
"String 1",
"String 2",
"String 3"
)
Mutable Array = (
"String 1",
"String 3"
)
Another very common collection found throughout iOS programs is a dictionary. Dic‐
tionaries are like arrays, but every object in a dictionary is assigned to a key so that later
you can retrieve the same object using the key. Here is an example:
NSDictionary *personInformation =
@{
@"firstName" : @"Mark",
@"lastName" : @"Tremonti",
@"age" : @30,
@"sex" : @"Male"
};
NSString *firstName = personInformation[@"firstName"];
NSString *lastName = personInformation[@"lastName"];
NSNumber *age = personInformation[@"age"];
NSString *sex = personInformation[@"sex"];
NSLog(@"Full name = %@ %@", firstName, lastName);
NSLog(@"Age = %@, Sex = %@", age, sex);
The output of this program is:
Full name = Mark Tremonti
Age = 30, Sex = Male
You can also have mutable dictionaries, just as you can have mutable arrays. Mutable
dictionaries’ contents can be changed after they are instantiated. Here is an example:
NSDictionary *personInformation =
@{
@"firstName" : @"Mark",
@"lastName" : @"Tremonti",
@"age" : @30,
@"sex" : @"Male"
};
NSMutableDictionary *mutablePersonInformation =
[[NSMutableDictionary alloc] initWithDictionary:personInformation];
1.0. Introduction | 15
mutablePersonInformation[@"age"] = @32;
NSLog(@"Information = %@", mutablePersonInformation);
The output of this program is:
Information = {
age = 32;
firstName = Mark;
lastName = Tremonti;
sex = Male;
}
You can also take advantage of sets. Sets are like arrays but must contain a unique set of
objects. You cannot add the same instance of an object twice to the same set. Here is an
example:
NSSet *shoppingList = [[NSSet alloc] initWithObjects:
@"Milk",
@"Bananas",
@"Bread",
@"Milk", nil];
NSLog(@"Shopping list = %@", shoppingList);
If you run this program, the output will be:
Shopping list = {(
Milk,
Bananas,
Bread
)}
Note how Milk was mentioned twice in our program but added to the set only once.
That’s the magic behind sets. You can also use mutable sets like so:
NSSet *shoppingList = [[NSSet alloc] initWithObjects:
@"Milk",
@"Bananas",
@"Bread",
@"Milk", nil];
NSMutableSet *mutableList = [NSMutableSet setWithSet:shoppingList];
[mutableList addObject:@"Yogurt"];
[mutableList removeObject:@"Bread"];
NSLog(@"Original list = %@", shoppingList);
NSLog(@"Mutable list = %@", mutableList);
And the output is:
Original list = {(
Milk,
Bananas,
16 | Chapter 1: Implementing Controllers and Views
Bread
)}
Mutable list = {(
Milk,
Bananas,
Yogurt
)}
There are two other important classes that you need to know about, now that we are
talking about sets and collections:
NSOrderedSet
An immutable set that keeps the order in which objects were added to it
NSMutableOrderedSet
The mutable version of the ordered set
By default, sets do not keep the order in which objects were added to them. Take the
following as an example:
NSSet *setOfNumbers = [NSSet setWithArray:@[@3, @4, @1, @5, @10]];
NSLog(@"Set of numbers = %@", setOfNumbers);
What gets printed to the screen after you run this program is:
Set of numbers = {(
5,
10,
3,
4,
1
)}
But that is not the order in which we created the set. If you want to keep the order intact,
simply use the NSOrderedSet class instead:
NSOrderedSet *setOfNumbers = [NSOrderedSet orderedSetWithArray
:@[@3, @4, @1, @5, @10]];
NSLog(@"Ordered set of numbers = %@", setOfNumbers);
And, of course, you can use the mutable version of an ordered set:
NSMutableOrderedSet *setOfNumbers =
[NSMutableOrderedSet orderedSetWithArray:@[@3, @4, @1, @5, @10]];
[setOfNumbers removeObject:@5];
[setOfNumbers addObject:@0];
[setOfNumbers exchangeObjectAtIndex:1 withObjectAtIndex:2];
NSLog(@"Set of numbers = %@", setOfNumbers);
The results are shown here:
1.0. Introduction | 17
Set of numbers = {(
3,
1,
4,
10,
0
)}
Before we move off the topic of sets, there is one other handy class that you may need
to know about. The NSCountedSet class can hold a unique instance of an object multiple
times. However, the way this is done is different from the way arrays perform the same
task. In an array, the same object can appear multiple times. But in a counted set, the
object will appear only once, but the set keeps a count of how many times the object
was added to the set and will decrement that counter each time you remove an instance
of the object. Here is an example:
NSCountedSet *setOfNumbers = [NSCountedSet setWithObjects:
@10, @20, @10, @10, @30, nil];
[setOfNumbers addObject:@20];
[setOfNumbers removeObject:@10];
NSLog(@"Count for object @10 = %lu",
(unsigned long)[setOfNumbers countForObject:@10]);
NSLog(@"Count for object @20 = %lu",
(unsigned long)[setOfNumbers countForObject:@20]);
The output is:
Count for object @10 = 2
Count for object @20 = 2
The NSCountedSet class is mutable, despite what its name may lead
you to think.
Adding Object Subscripting Support to Your Classes
Traditionally, when accessing objects in collections such as arrays and dictionaries,
programmers had to access a method on the array or the dictionary to get or set that
object. For instance, this is the traditional way of creating a mutable dictionary, adding
two keys and values to it, and retrieving those values back:
NSString *const kFirstNameKey = @"firstName";
NSString *const kLastNameKey = @"lastName";
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
18 | Chapter 1: Implementing Controllers and Views
[dictionary setValue:@"Tim" forKey:kFirstNameKey];
[dictionary setValue:@"Cook" forKey:kLastNameKey];
__unused NSString *firstName = [dictionary valueForKey:kFirstNameKey];
__unused NSString *lastName = [dictionary valueForKey:kLastNameKey];
But with all the advances in the LLVM compiler, this code can now be shortened to this:
NSString *const kFirstNameKey = @"firstName";
NSString *const kLastNameKey = @"lastName";
NSDictionary *dictionary = @{
kFirstNameKey : @"Tim",
kLastNameKey : @"Cook",
};
__unused NSString *firstName = dictionary[kFirstNameKey];
__unused NSString *lastName = dictionary[kLastNameKey];
Youcanseethatweareinitializingthedictionarybyprovidingthekeysincurlybrackets.
The same thing for arrays. Here is how we used to create and use arrays traditionally:
NSArray *array = [[NSArray alloc] initWithObjects:@"Tim", @"Cook", nil];
__unused NSString *firstItem = [array objectAtIndex:0];
__unused NSString *secondObject = [array objectAtIndex:1];
And now with object subscripting, we can shorten this code, as follows:
NSArray *array = @[@"Tim", @"Cook"];
__unused NSString *firstItem = array[0];
__unused NSString *secondObject = array[0];
LLVM didn’t even stop there. You can add subscripting to your own classes as well.
There are two types of subscripting:
Subscripting by key
Withthis,youcansetthevalueforaspecifickeyinsideanobject,justlikeyouwould
in a dictionary. You can also access/read-from values inside the object by providing
the key.
Subscripting by index
As with arrays, you can set/get values inside the object by providing an index to
thatobject.Thismakessenseforarray-likeclasseswheretheelementslieinanatural
order that can be represented by an index.
For the first example, we are going to look at subscripting by key. To do this, we are
going to create a class named Person with a firstName and a lastName. Then we are
going to allow the programmer to change the first and last names by simply providing
the keys to those properties.
The reason you may want to add subscripting by key to a class like this is if your property
names are volatile and you want to allow the programmer to set the value of those
1.0. Introduction | 19
properties without having to worry about whether the names of those properties will
change later; otherwise, the programmer is better off using the properties directly. The
other reason for implementing subscripting by key is if you want to hide the exact
implementation/declaration of your properties from the programmer and not let her
access them directly.
In order to support subscripting by key on your own classes, you must implement the
following two methods on your class and put the method signatures in your class’s
header file; otherwise, the compiler won’t know that your class supports subscripting
by key.
#import <Foundation/Foundation.h>
/* We will use these as the keys to our firstName and lastName
properties so that if our firstName and lastName properties' names
change in the future in the implementation, we won't break anything
and our class will still work, as we can simply change the value of
these constants inside our implementation file */
extern NSString *const kFirstNameKey;
extern NSString *const kLastNameKey;
@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
- (id) objectForKeyedSubscript:(id<NSCopying>)paramKey;
- (void) setObject:(id)paramObject forKeyedSubscript:(id<NSCopying>)paramKey;
@end
The objectForKeyedSubscript: method will be called on your class whenever the
programmer provides a key and wants to read the value of that key in your class. The
parameterthatwillbegiventoyouwillobviouslybethekeyfromwhichtheprogrammer
wants to read the value. To complement this method, the setObject:forKeyedSub
script: method will be called on your class whenever the programmer wants to set the
value for a specified key. So in our implementation, we want to check whether the given
keys are the first name and the last name keys, and if yes, we will set/get the values of
the first name and last name in our class:
#import "Person.h"
NSString *const kFirstNameKey = @"firstName";
NSString *const kLastNameKey = @"lastName";
@implementation Person
- (id) objectForKeyedSubscript:(id<NSCopying>)paramKey{
NSObject<NSCopying> *keyAsObject = (NSObject<NSCopying> *)paramKey;
20 | Chapter 1: Implementing Controllers and Views
if ([keyAsObject isKindOfClass:[NSString class]]){
NSString *keyAsString = (NSString *)keyAsObject;
if ([keyAsString isEqualToString:kFirstNameKey] ||
[keyAsString isEqualToString:kLastNameKey]){
return [self valueForKey:keyAsString];
}
}
return nil;
}
- (void) setObject:(id)paramObject forKeyedSubscript:(id<NSCopying>)paramKey{
NSObject<NSCopying> *keyAsObject = (NSObject<NSCopying> *)paramKey;
if ([keyAsObject isKindOfClass:[NSString class]]){
NSString *keyAsString = (NSString *)keyAsObject;
if ([keyAsString isEqualToString:kFirstNameKey] ||
[keyAsString isEqualToString:kLastNameKey]){
[self setValue:paramObject forKey:keyAsString];
}
}
}
@end
So in this code, in the objectForKeyedSubscript: method, we are given a key, and we
are expected to return the object that is associated in our instance with that key. The
key that is given to us is an object that conforms to the NSCopying protocol. In other
words, it’s an object that we can make a copy of, if we want to. We expect the key to be
a string so that we can compare it with the predefined keys that we have declared on
top of our class, and if it matches, we will set the value of that property in our class. We
will then use the NSObject method named valueForKey: to return the value associated
with the given key. But obviously, before we do so, we ensure that the given key is one
of the keys that we expect. In the setObject:forKeyedSubscript: method we do the
exact opposite. We set the values for a given key instead of returning them.
Now, elsewhere in your app, you can instantiate an object of type Person and use the
predefined keys of kFirstNameKey and kLastNameKey to change the value of the first
Name and lastName properties like so:
Person *person = [Person new];
person[kFirstNameKey] = @"Tim";
person[kLastNameKey] = @"Cook";
__unused NSString *firstName = person[kFirstNameKey];
__unused NSString *lastName = person[kLastNameKey];
This code will achieve exactly the same effect as the more direct approach of setting the
properties of a class:
Person *person = [Person new];
person.firstName = @"Tim";
person.lastName = @"Cook";
1.0. Introduction | 21
__unused NSString *firstName = person.firstName;
__unused NSString *lastName = person.lastName;
You can also support subscripting by index, the same way arrays do. This is useful, as
mentioned before, to allow programmers to access objects that have a natural order
inside a class. But there are not many data structures besides arrays where it makes sense
to order and number elements, unlike subscripting by key, which applies to a wide range
of data structures. So the example I’ll use to illustrate subscripting by index is a bit
contrived. In our previous example, we had the Person class with a first and last name.
Now if you want to allow programmers to be able to read the first name by providing
the index of 0 and the last name by providing the index of 1, all you have to do is declare
the objectAtIndexedSubscript: and the setObject:atIndexedSubscript: methods
in the header file of your class, and then write the implementation. Here is how we
declare these methods in our Person class’s header file:
- (id) objectAtIndexedSubscript:(NSUInteger)paramIndex;
- (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex;
The implementation is also quite simple. We take the index and act upon it in a way that
makes sense to our class. We decided that the first name has to have the index of 0 and
the last name the index of 1. So if we get the index of 0 for setting a value, we set the
value of the first name to the incoming object, and so on:
- (id) objectAtIndexedSubscript:(NSUInteger)paramIndex{
switch (paramIndex){
case 0:{
return self.firstName;
break;
}
case 1:{
return self.lastName;
break;
}
default:{
[NSException raise:@"Invalid index" format:nil];
}
}
return nil;
}
- (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex{
switch (paramIndex){
case 0:{
self.firstName = paramObject;
break;
}
case 1:{
self.lastName = paramObject;
22 | Chapter 1: Implementing Controllers and Views
break;
}
default:{
[NSException raise:@"Invalid index" format:nil];
}
}
}
Now we can test out what we’ve written so far, like so:
Person *person = [Person new];
person[kFirstNameKey] = @"Tim";
person[kLastNameKey] = @"Cook";
NSString *firstNameByKey = person[kFirstNameKey];
NSString *lastNameByKey = person[kLastNameKey];
NSString *firstNameByIndex = person[0];
NSString *lastNameByIndex = person[1];
if ([firstNameByKey isEqualToString:firstNameByIndex] &&
[lastNameByKey isEqualToString:lastNameByIndex]){
NSLog(@"Success");
} else {
NSLog(@"Something is not right");
}
If you’ve followed all the steps in this recipe, you should see the value Success printed
to the console now.
1.1. Displaying Alerts with UIAlertView
Problem
You want to display a message to your users in the form of an alert. This could be used
to ask them to confirm an action, to ask for their username and password, or simply to
let them enter some simple text that you can use in your app.
Solution
Utilize the UIAlertView class.
Discussion
If you are an iOS user, you have most certainly already seen an alert view. Figure 1-1
depicts an example.
1.1. Displaying Alerts with UIAlertView | 23
Figure 1-1. Example of an alert view in iOS
The best way to initialize an alert view is to use its designated initializer:
- (void) viewDidAppear:(BOOL)paramAnimated{
[super viewDidAppear:paramAnimated];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Alert"
message:@"You've been delivered an alert"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
[alertView show];
}
24 | Chapter 1: Implementing Controllers and Views
Whenthisalertviewisdisplayedtotheuser,shewillseesomethingsimilartothatshown
in Figure 1-2.
Figure 1-2. A simple alert view displayed to the user
In order to display an alert view to the user, we use the alert view’s show method. Let’s
have a look at the description for each of the parameters that we passed to the initializer
of the alert view:
title
The string that the alert view will display on the top when it is shown to the user.
This string is Title in Figure 1-2.
message
The actual message that gets displayed to the user. In Figure 1-2, this message is set
to Message.
1.1. Displaying Alerts with UIAlertView | 25
delegate
The optional delegate object that we pass to the alert view. This object will get
notified whenever the alert’s state changes; for instance, when the user taps on a
button on the alert view. The object passed to this parameter must conform to the
UIAlertViewDelegate protocol.
cancelButtonTitle
A string that will get assigned to the cancel button on an alert view. An alert view
that has a cancel button usually asks the user for an action. If the user isn’t com‐
fortable with performing that action, he will press the cancel button. This button’s
title does not necessarily have to say Cancel. It is up to you to specify a title for this
button. This parameter is optional; you could put up a dialog box with no cancel
button.
otherButtonTitles
Titles of any other buttons that you want to have appear on the alert view. Separate
the titles with commas and make sure you terminate the list of titles with a nil,
which is called a sentinel. This parameter is optional.
It is possible to create an alert view without any buttons. But the view
cannot be dismissed by the user. If you create such a view, you, as the
programmer, need to make sure this alert view will get dismissed au‐
tomatically; for instance, three seconds after it is displayed. An alert
view without any buttons that does not dismiss itself automatically
gives a really poor user experience. Not only will your app get low
ratings on the App Store for blocking the UI from user access, but
chances are that your app will get rejected by Apple.
Alert views can take various styles. The UIAlertView class has a property called alert
ViewStyle of type UIAlertViewStyle:
typedef NS_ENUM(NSInteger, UIAlertViewStyle) {
UIAlertViewStyleDefault = 0,
UIAlertViewStyleSecureTextInput,
UIAlertViewStylePlainTextInput,
UIAlertViewStyleLoginAndPasswordInput
};
Here is what each of these styles will do:
UIAlertViewStyleDefault
This is the default style of an alert view, as we saw in Figure 1-2.
UIAlertViewStyleSecureTextInput
With this style, the alert view will contain a secure text field, which hides the actual
characters typed by the user. For instance, if you are asking the user for her online
banking credentials, you might choose this style of alert view.
26 | Chapter 1: Implementing Controllers and Views
UIAlertViewStylePlainTextInput
Under this style, the alert view will display a nonsecure text field to the user. This
style is great if you simply want to ask the user for a plain-text entry, such as her
phone number.
UIAlertViewStyleLoginAndPasswordInput
With this style, the alert view will display two text fields: a nonsecure one for a
username and a secure one for a password.
If you need to get notified when the user interacts with the alert view, specify a delegate
object to your alert view. This delegate must conform to the UIAlertViewDelegate
protocol. The most important method defined in this protocol is the alertView:click
edButtonAtIndex:method,whichiscalledassoonastheusertapsononeofthebuttons
in the alert view. The button index is passed to you through the clickedButtonAtIn
dex parameter.
As an example, let’s display an alert view to the user and ask whether she would like to
visit a website in Safari after having pressed a link to that website available in our UI.
We will display two buttons on our alert view: Yes and No. In our alert view delegate,
we will detect which button she tapped on and will take action accordingly.
Let’s first implement two very simple methods that return the title of our two buttons:
- (NSString *) yesButtonTitle{
return @"Yes";
}
- (NSString *) noButtonTitle{
return @"No";
}
Now we need to make sure that we are conforming to the UIAlertViewDelegate pro‐
tocol in our view controller:
#import "ViewController.h"
@interface ViewController () <UIAlertViewDelegate>
@end
@implementation ViewController
...
The next step is to create and display our alert view to the user:
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
self.view.backgroundColor = [UIColor whiteColor];
1.1. Displaying Alerts with UIAlertView | 27
NSString *message = @"Are you sure you want to open this link in Safari?";
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Open Link"
message:message
delegate:self
cancelButtonTitle:[self noButtonTitle]
otherButtonTitles:[self yesButtonTitle], nil];
[alertView show];
}
So now, our alert view will look similar to that shown in Figure 1-3.
Figure 1-3. An alert view with Yes and No buttons
Now we need a way to know whether the user selected the Yes or the No option in our
alert view. For this, we will need to implement the alertView:clickedButtonAtIn
dex: method of our alert view delegate:
- (void) alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex{
28 | Chapter 1: Implementing Controllers and Views
Another Random Document on
Scribd Without Any Related Topics
struggle for existence, the blind controller, instead of the provident
God, that effects the changes of organic forms by a mutual action of
the laws of heredity and adaptation. And there is no more trace of
“design” in the embryology of the individual plant, animal, or man.
This ontogeny is but a brief epitome of phylogeny, an abbreviated
and condensed recapitulation of it, determined by the physiological
laws of heredity.
Baer ended the preface to his classical Evolution of Animals (1828)
with these words: “The palm will be awarded to the fortunate
scientist who succeeds in reducing the constructive forces of the
animal body to the general forces or life-processes of the entire
world. The tree has not yet been planted which is to make his
cradle.” The great embryologist erred once more. That very year,
1828, witnessed the arrival of Charles Darwin at Cambridge
University (for the purpose of studying theology!)—the “fortunate
scientist” who richly earned the palm thirty years afterwards by his
theory of selection.
In the philosophy of history—that is, in the general reflections which
historians make on the destinies of nations and the complicated
course of political evolution—there still prevails the notion of a
“moral order of the universe.” Historians seek in the vivid drama of
history a leading design, an ideal purpose, which has ordained one
or other race or state to a special triumph, and to dominion over the
others. This teleological view of history has recently become more
strongly contrasted with our monistic view in proportion as monism
has proved to be the only possible interpretation of inorganic nature.
Throughout the whole of astronomy, geology, physics, and chemistry
there is no question to-day of a “moral order,” or a personal God,
whose “hand hath disposed all things in wisdom and understanding.”
And the same must be said of the entire field of biology, the whole
constitution and history of organic nature, if we set aside the
question of man for the moment. Darwin has not only proved by his
theory of selection that the orderly processes in the life and
structure of animals and plants have arisen by mechanical laws
without any preconceived design, but he has shown us in the
“struggle for life” the powerful natural force which has exerted
supreme control over the entire course of organic evolution for
millions of years. It may be said that the struggle for life is the
“survival of the fittest” or the “victory of the best”; that is only
correct when we regard the strongest as the best (in a moral sense).
Moreover, the whole history of the organic world goes to prove that,
besides the predominant advance towards perfection, there are at all
times cases of retrogression to lower stages. Even Baer’s notion of
“design” has no moral feature whatever.
Do we find a different state of things in the history of peoples, which
man, in his anthropocentric presumption, loves to call “the history of
the world”? Do we find in every phase of it a lofty moral principle or
a wise ruler, guiding the destinies of nations? There can be but one
answer in the present advanced stage of natural and human history:
No. The fate of those branches of the human family, those nations
and races which have struggled for existence and progress for
thousands of years, is determined by the same “eternal laws of iron”
as the history of the whole organic world which has peopled the
earth for millions of years.
Geologists distinguish three great epochs in the organic history of
the earth, as far as we can read it in the monuments of the science
of fossils—the primary, secondary, and tertiary epochs. According to
a recent calculation, the first occupied at least thirty-four million, the
second eleven million, and the third three million years. The history
of the family of vertebrates, from which our own race has sprung,
unfolds clearly before our eyes during this long period. Three
different stages in the evolution of the vertebrate correspond to the
three epochs; the fishes characterized the primary (palæozoic) age,
the reptiles the secondary (mesozoic), and the mammals the tertiary
(cænozoic). Of the three groups the fishes rank lowest in
organization, the reptiles come next, and the mammals take the
highest place. We find, on nearer examination of the history of the
three classes, that their various orders and families also advanced
progressively during the three epochs towards a higher stage of
perfection. May we consider this progressive development as the
outcome of a conscious design or a moral order of the universe?
Certainly not. The theory of selection teaches us that this organic
progress, like the earlier organic differentiation, is an inevitable
consequence of the struggle for existence. Thousands of beautiful
and remarkable species of animals and plants have perished during
those forty-eight million years, to give place to stronger competitors,
and the victors in this struggle for life were not always the noblest or
most perfect forms in a moral sense.
It has been just the same with the history of humanity. The splendid
civilization of classical antiquity perished because Christianity, with
its faith in a loving God and its hope of a better life beyond the
grave, gave a fresh, strong impetus to the soaring human mind. The
Papal Church quickly degenerated into a pitiful caricature of real
Christianity, and ruthlessly scattered the treasures of knowledge
which the Hellenic philosophy had gathered; it gained the dominion
of the world through the ignorance of the credulous masses. In time
the Reformation broke the chains of this mental slavery, and assisted
reason to secure its right once more. But in the new, as in the older,
period the great struggle for existence went on in its eternal
fluctuation, with no trace of a moral order.
And it is just as impossible for the impartial and critical observer to
detect a “wise providence” in the fate of individual human beings as
a moral order in the history of peoples. Both are determined with
iron necessity by a mechanical causality which connects every single
phenomenon with one or more antecedent causes. Even the ancient
Greeks recognized ananke, the blind heimarmene, the fate “that
rules gods and men,” as the supreme principle of the universe.
Christianity replaced it by a conscious Providence, which is not blind,
but sees, and which governs the world in patriarchal fashion. The
anthropomorphic character of this notion, generally closely
connected with belief in a personal God, is quite obvious. Belief in a
“loving Father,” who unceasingly guides the destinies of one billion
five hundred million men on our planet, and is attentive at all times
to their millions of contradictory prayers and pious wishes, is
absolutely impossible; that is at once perceived on laying aside the
colored spectacles of “faith” and reflecting rationally on the subject.
As a rule, this belief in Providence and the tutelage of a “loving
Father” is more intense in the modern civilized man—just as in the
uncultured savage—when some good fortune has fallen him: an
escape from peril of life, recovery from a severe illness, the winning
of the first prize in a lottery, the birth of a long-delayed child, and so
forth. When, on the other hand, a misfortune is met with, or an
ardent wish is not fulfilled, “Providence” is forgotten. The wise ruler
of the world slumbered—or refused his blessing.
In the extraordinary development of commerce of the nineteenth
century the number of catastrophes and accidents has necessarily
increased beyond all imagination; of that the journal is a daily
witness. Thousands are killed every year by shipwreck, railway
accidents, mine accidents, etc. Thousands slay each other every year
in war, and the preparation for this wholesale massacre absorbs
much the greater part of the revenue in the highest civilized nations,
the chief professors of “Christian charity.” And among these
hundreds of thousands of annual victims of modern civilization
strong, industrious, courageous workers predominate. Yet the talk of
a “moral order” goes on.
Since impartial study of the evolution of the world teaches us that
there is no definite aim and no special purpose to be traced in it,
there seems to be no alternative but to leave everything to “blind
chance.” This reproach has been made to the transformism of
Lamarck and Darwin, as it had been to the previous systems of Kant
and Laplace; there are a number of dualist philosophers who lay
great stress on it. It is, therefore, worth while to make a brief
remark upon it.
One group of philosophers affirms, in accordance with its teleological
conception, that the whole cosmos is an orderly system, in which
every phenomenon has its aim and purpose; there is no such thing
as chance. The other group, holding a mechanical theory, expresses
itself thus: The development of the universe is a monistic mechanical
process, in which we discover no aim or purpose whatever; what we
call design in the organic world is a special result of biological
agencies; neither in the evolution of the heavenly bodies nor in that
of the crust of our earth do we find any trace of a controlling
purpose—all is the result of chance. Each party is right—according to
its definition of chance. The general law of causality, taken in
conjunction with the law of substance, teaches us that every
phenomenon has a mechanical cause; in this sense there is no such
thing as chance. Yet it is not only lawful, but necessary, to retain the
term for the purpose of expressing the simultaneous occurrence of
two phenomena, which are not causally related to each other, but of
which each has its own mechanical cause, independent of that of the
other. Everybody knows that chance, in its monistic sense, plays an
important part in the life of man and in the universe at large. That,
however, does not prevent us from recognizing in each “chance”
event, as we do in the evolution of the entire cosmos, the universal
sovereignty of nature’s supreme law, the law of substance.
CHAPTER XV
GOD AND THE WORLD
The Idea of God in General—Antithesis of God and the World; the
Supernatural and Nature—Theism and Pantheism—Chief Forms
of Theism—Polytheism—Triplotheism—Amphitheism—
Monotheism—Religious Statistics—Naturalistic Monotheism—
Solarism—Anthropistic Monotheism—The Three Great
Mediterranean Religions—Mosaism—Christianity—The Cult of the
Madonna and the Saints—Papal Polytheism—Islam—Mixotheism
—Nature of Theism—An Extra-mundane and Anthropomorphic
God; a Gaseous Vertebrate—Pantheism—Intramundane God
(Nature)—The Hylozoism of the Ionic Monists (Anaximander)—
Conflict of Pantheism and Christianity—Spinoza—Modern
Monism—Atheism
For thousands of years humanity has placed the last and supreme
basis of all phenomena in an efficient cause, to which it gives the
title of God (deus, theos). Like all general ideas, this notion of God
has undergone a series of remarkable modifications and
transformations in the course of the evolution of reason. Indeed, it
may be said that no other idea has had so many metamorphoses;
for no other belief affects in so high a degree the chief objects of the
mind and of rational science, as well as the deepest interests of the
emotion and poetic fancy of the believer.
A comparative criticism of the many different forms of the idea of
God would be extremely interesting and instructive; but we have not
space for it in the present work. We must be content with a passing
glance at the most important forms of the belief and their relation to
the modern thought that has been evoked by a sound study of
nature. For further information on this interesting question the
reader would do well to consult the distinguished work of Adalbert
Svoboda, Forms of Faith (1897).
When we pass over the finer shades and the variegated clothing of
the God-idea and confine our attention to its chief element, we can
distribute all the different presentations of it in two groups—the
theistic and pantheistic group. The latter is closely connected with
the monistic, or rational, view of things, and the former is associated
with dualism and mysticism.
I.—THEISM
In this view God is distinct from, and opposed to, the world as its
creator, sustainer, and ruler. He is always conceived in a more or less
human form, as an organism which thinks and acts like a man—only
on a much higher scale. This anthropomorphic God, polyphyletically
evolved by the different races, assumes an infinity of shapes in their
imagination, from fetichism to the refined monotheistic religions of
the present day. The chief forms of theism are polytheism,
triplotheism, amphitheism, and monotheism.
The polytheist peoples the world with a variety of gods and
goddesses, which enter into its machinery more or less
independently. Fetichism sees such subordinate deities in the lifeless
body of nature, in rocks, in water, in the air, in human productions of
every kind (pictures, statues, etc.). Demonism sees gods in living
organisms of every species—trees, animals, and men. This kind of
polytheism is found in innumerable forms even in the lowest tribes.
It reaches the highest stage in Hellenic polytheism, in the myths of
ancient Greece, which still furnish the finest images to the modern
poet and artist. At a much lower stage we have Catholic polytheism,
in which innumerable “saints” (many of them of very equivocal
repute) are venerated as subordinate divinities, and prayed to to
exert their mediation with the supreme divinity.
The dogma of the “Trinity,” which still comprises three of the chief
articles of faith in the creed of Christian peoples, culminates in the
notion that the one God of Christianity is really made up of three
different persons: (1) God the Father, the omnipotent creator of
heaven and earth (this untenable myth was refuted long ago by
scientific cosmogony, astronomy, and geology); (2) Jesus Christ; and
(3) the Holy Ghost, a mystical being, over whose incomprehensible
relation to the Father and the Son millions of Christian theologians
have racked their brains in vain for the last nineteen hundred years.
The Gospels, which are the only clear sources of this triplotheism,
are very obscure as to the relation of these three persons to each
other, and do not give a satisfactory answer to the question of their
unity. On the other hand, it must be carefully noted what confusion
this obscure and mystic dogma of the Trinity must necessarily cause
in the minds of our children even in the earlier years of instruction.
One morning they learn (in their religious instruction) that three
times one are one, and the very next hour they are told in their
arithmetic class that three times one are three. I remember well the
reflection that this confusion led me to in my early school-days.
For the rest, the “Trinity” is not an original element in Christianity;
like most of the other Christian dogmas, it has been borrowed from
earlier religions. Out of the sun-worship of the Chaldean magi was
evolved the Trinity of Ilu, the mysterious source of the world; its
three manifestations were Anu, primeval chaos; Bel, the architect of
the world; and Aa, the heavenly light, the all-enlightening wisdom.
In the Brahmanic religion the Trimurti is also conceived as a “divine
unity” made up of three persons—Brahma (the creator), Vishnu (the
sustainer), and Shiva (the destroyer). It would seem that in this and
other ideas of a Trinity the “sacred number, three,” as such—as a
“symbolical number”—has counted for something. The three first
Christian virtues—Faith, Hope, and Charity—form a similar triad.
According to the amphitheists, the world is ruled by two different
gods, a good and an evil principle, God and the Devil. They are
engaged in a perpetual struggle, like rival emperors, or pope and
anti-pope. The condition of the world is the result of this conflict.
The loving God, or good principle, is the source of all that is good
and beautiful, of joy and of peace. The world would be perfect if His
work were not continually thwarted by the evil principle, the Devil;
this being is the cause of all that is bad and hateful, of contradiction
and of pain.
Amphitheism is undoubtedly the most rational of all forms of belief in
God, and the one which is least incompatible with a scientific view of
the world. Hence we find it elaborated in many ancient peoples
thousands of years before Christ. In ancient India Vishnu, the
preserver, struggles with Shiva, the destroyer. In ancient Egypt the
good Osiris is opposed by the wicked Typhon. The early Hebrews
had a similar dualism of Aschera (or Keturah), the fertile mother-
earth, and Elion (Moloch or Sethos), the stern heavenly father. In the
Zend religion of the ancient Persians, founded by Zoroaster two
thousand years before Christ, there is a perpetual struggle between
Ormuzd, the good god of light, and Ahriman, the wicked god of
darkness.
In Christian mythology the Devil is scarcely less conspicuous as the
adversary of the good deity, the tempter and seducer, the prince of
hell, and lord of darkness. A personal devil was still an important
element in the belief of most Christians at the beginning of the
nineteenth century. Towards the middle of the century he was
gradually eliminated by being progressively explained away, or he
was restricted to the subordinate rôle he plays as Mephistopheles in
Goethe’s great drama. To-day the majority of educated people look
upon “belief in a personal devil” as a mediæval superstition, while
“belief in God” (that is, the personal, good, and loving God) is
retained as an indispensable element of religion. Yet the one belief is
just as much (or as little) justified as the other. In any case, the
much-lamented “imperfection of our earthly life,” the “struggle for
existence,” and all that pertains to it, are explained much more
simply and naturally by this struggle of a good and an evil god than
by any other form of theism.
The dogma of the unity of God may in some respects be regarded as
the simplest and most natural type of theism; it is popularly
supposed to be the most widely accepted element of religion, and to
predominate in the ecclesiastical systems of civilized countries. In
reality, that is not the case, because this alleged “monotheism”
usually turns out on closer inquiry to be one of the other forms of
theism we have examined, a number of subordinate deities being
generally introduced besides the supreme one. Most of the religions
which took a purely monotheistic stand-point have become more or
less polytheistic in the course of time. Modern statistics assure us
that of the one billion five hundred million men who people the earth
the great majority are monotheists; of these, nominally, about six
hundred millions are Brahma-Buddhists, five hundred millions are
called Christians, two hundred millions are heathens (of various
types), one hundred and eighty millions are Mohammedans, ten
millions are Jews, and ten millions have no religion at all. However,
the vast majority of these nominal monotheists have very confused
ideas about the deity, or believe in a number of gods and goddesses
besides the chief god—angels, devils, etc.
The different forms which monotheism has assumed in the course of
its polyphyletic development may be distributed in two groups—
those of naturalistic and anthropistic monotheism. Naturalistic
monotheism finds the embodiment of the deity in some lofty and
dominating natural phenomenon. The sun, the deity of light and
warmth, on whose influence all organic life insensibly and directly
depends, was taken to be such a phenomenon many thousand years
ago. Sun-worship (solarism, or heliotheism) seems to the modern
scientist to be the best of all forms of theism, and the one which
may be most easily reconciled with modern monism. For modern
astrophysics and geogeny have taught us that the earth is a
fragment detached from the sun, and that it will eventually return to
the bosom of its parent. Modern physiology teaches us that the first
source of organic life on the earth is the formation of protoplasm,
and that this synthesis of simple inorganic substances, water,
carbonic acid, and ammonia, only takes place under the influence of
sunlight. On the primary evolution of the plasmodomous plants
followed, secondarily, that of the plasmophagous animals, which
directly or indirectly depend on them for nourishment; and the origin
of the human race itself is only a later stage in the development of
the animal kingdom. Indeed, the whole of our bodily and mental life
depends, in the last resort, like all other organic life, on the light and
heat rays of the sun. Hence in the light of pure reason, sun-worship,
as a form of naturalistic monotheism, seems to have a much better
foundation than the anthropistic worship of Christians and of other
monotheists who conceive their god in human form. As a matter of
fact, the sun-worshippers attained, thousands of years ago, a higher
intellectual and moral standard than most of the other theists. When
I was in Bombay, in 1881, I watched with the greatest sympathy the
elevating rites of the pious Parsees, who, standing on the sea-shore,
or kneeling on their prayer-rugs, offered their devotion to the sun at
its rise and setting.[31]
Moon-worship (lunarism and selenotheism) is of much less
importance than sun-worship. There are a few uncivilized races that
have adored the moon as their only deity, but it has generally been
associated with a worship of the stars and the sun.
The humanization of God, or the idea that the “Supreme Being”
feels, thinks, and acts like man (though in a higher degree), has
played a most important part, as anthropomorphic monotheism, in
the history of civilization. The most prominent in this respect are the
three great religions of the Mediterranean peoples—the old Mosaic
religion, the intermediate Christian religion, and the younger
Mohammedanism. These three great Mediterranean religions, all
three arising on the east coast of the most interesting of all seas,
and originating in an imaginative enthusiast of the Semitic race, are
intimately connected, not only by this external circumstance of an
analogous origin, but by many common features of their internal
contents. Just as Christianity borrowed a good deal of its mythology
directly from ancient Judaism, so Islam has inherited much from
both its predecessors. All the three were originally monotheistic; all
three were subsequently overlaid with a great variety of polytheistic
features, in proportion as they extended, first along the coast of the
Mediterranean with its heterogeneous population, and eventually
into every part of the world.
The Hebrew monotheism, as it was founded by Moses (about 1600
B.C.), is usually regarded as the ancient faith which has been of the
greatest importance in the ethical and religious development of
humanity. This high historical appreciation is certainly valid in the
sense that the two other world-conquering Mediterranean religions
issued from it; Christ was just as truly a pupil of Moses as
Mohammed was afterwards of Christ. So also the New Testament,
which has become the foundation of the belief of the highest
civilized nations in the short space of nineteen hundred years, rests
on the venerable basis of the Old Testament. The Bible, which the
two compose, has had a greater influence and a wider circulation
than any other book in the world. Even to-day the Bible—in spite of
its curious mingling of the best and the worst elements—is in a
certain sense the “book of books.” Yet when we make an impartial
and unprejudiced study of this notable historical source, we find it
very different in several important respects from the popular
impression. Here again modern criticism and history have come to
certain conclusions which destroy the prevalent tradition in its very
foundations.
The monotheism which Moses endeavored to establish in the
worship of Jehovah, and which the prophets—the philosophers of
the Hebrew race—afterwards developed with great success, had at
first to sustain a long and severe struggle with the dominant
polytheism which was in possession. Jehovah, or Yahveh, was
originally derived from the heaven-god, which, under the title of
Moloch or Baal, was one of the most popular of the Oriental deities
(the Sethos or Typhon of the Egyptians, and the Saturn or Cronos of
the Greeks). There were, however, other gods in great favor with the
Jewish people, and so the struggle with “idolatry” continued. Still,
Jehovah was, in principle, the only God, explicitly claiming, in the
first precept of the decalogue: “I am the Lord thy God; thou shalt
have no other gods beside me.”
Christian monotheism shared the fate of its mother, Mosaism; it was
generally only monotheistic in theory, while it degenerated practically
into every kind of polytheism. In point of fact, monotheism was
logically abandoned in the very dogma of the Trinity, which was
adopted as an indispensable foundation of the Christian religion. The
three persons, which are distinguished as Father, Son, and Holy
Ghost, are three distinct individuals (and, indeed, anthropomorphic
persons), just as truly as the three Indian deities of the Trimurti
(Brahma, Vishnu, and Shiva) or the Trinity of the ancient Hebrews
(Anu, Bel, and Aa). Moreover, in the most widely distributed form of
Christianity the “virgin” mother of Christ plays an important part as a
fourth deity; in many Catholic countries she is practically taken to be
much more powerful and influential than the three male persons of
the celestial administration. The cult of the madonna has been
developed to such an extent in these countries that we may oppose
it to the usual masculine form of monotheism as one of a feminine
type. The “Queen of Heaven” becomes so prominent, as is seen in
so many pictures and legends of the madonna, that the three male
persons practically disappear.
In addition, the imagination of the pious Christian soon came to
increase this celestial administration by a numerous company of
“saints” of all kinds, and bands of musical angels, who should see
that “eternal life” should not prove too dull. The popes—the greatest
charlatans that any religion ever produced—have constantly studied
to increase this band of celestial satellites by repeated canonizations.
This curious company received its most interesting acquisition in
1870, when the Vatican Council pronounced the popes, as the vicars
of Christ, to be infallible, and thus raised them to a divine dignity.
When we add the “personal Devil” that they acknowledge, and the
“bad angels” who form his court, we have in modern Catholicism,
still the most extensive branch of Christianity, a rich and variegated
polytheism that dwarfs the Olympic family of the Greeks.
Islam, or the Mohammedan monotheism, is the youngest and purest
form of monotheism. When the young Mohammed (born 570)
learned to despise the polytheistic idolatry of his Arabian
compatriots, and became acquainted with Nestorian Christianity, he
adopted its chief doctrines in a general way; but he could not bring
himself to see anything more than a prophet in Christ, like Moses.
He found in the dogma of the Trinity what every emancipated
thinker finds on impartial reflection—an absurd legend which is
neither reconcilable with the first principles of reason nor of any
value whatever for our religious advancement. He justly regarded
the worship of the immaculate mother of God as a piece of pure
idolatry, like the veneration of pictures and images. The longer he
reflected on it, and the more he strove after a purified idea of deity,
the clearer did the certitude of his great maxim appear: “God is the
only God”—there are no other gods beside him.
Yet Mohammed could not free himself from the anthropomorphism
of the God-idea. His one only God was an idealized, almighty man,
like the stern, vindictive God of Moses, and the gentle, loving God of
Christ. Still, we must admit that the Mohammedan religion has
preserved the character of pure monotheism throughout the course
of its historical development and its inevitable division much more
faithfully than the Mosaic and Christian religions. We see that to-day,
even externally, in its forms of prayer and preaching, and in the
architecture and adornment of its mosques. When I visited the East
for the first time, in 1873, and admired the noble mosques of Cairo,
Smyrna, Brussa, and Constantinople, I was inspired with a feeling of
real devotion by the simple and tasteful decoration of the interior,
and the lofty and beautiful architectural work of the exterior. How
noble and inspiring do these mosques appear in comparison with the
majority of Catholic churches, which are covered internally with
gaudy pictures and gilt, and are outwardly disfigured by an
immoderate crowd of human and animal figures! Not less elevated
are the silent prayers and the simple devotional acts of the Koran
when compared with the loud, unintelligible verbosity of the Catholic
Mass and the blatant music of their theatrical processions.
Under the title of mixotheism we may embrace all the forms of
theistic belief which contain mixtures of religious notions of different,
sometimes contradictory, kinds. In theory this most widely diffused
type of religion is not recognized at all; in the concrete it is the most
important and most notable of all. The vast majority of men who
have religious opinions have always been, and still are, mixotheists;
their idea of God is picturesquely compounded from the impressions
received in childhood from their own sect, and a number of other
impressions which are received later on, from contact with members
of other religions, and which modify the earlier notions. In educated
people there is also sometimes the modifying influence of
philosophic studies in maturer years, and especially the unprejudiced
study of natural phenomena, which reveals the futility of the theistic
idea. The conflict of these contradictory impressions, which is very
painful to a sensitive soul, and which often remains undecided
throughout life, clearly shows the immense power of the heredity of
ancient myths on the one hand and the early adaptation to
erroneous dogmas on the other. The particular faith in which the
child has been brought up generally remains in power, unless a
“conversion” takes place subsequently, owing to the stronger
influence of some other religion. But even in this supersession of one
faith by another the new name, like the old one, proves to be merely
an outward label covering a mixture of the most diverse opinions
and errors. The greater part of those who call themselves Christians
are not monotheists (as they think), but amphitheists, triplotheists,
or polytheists. And the same must be said of Islam and Mosaism,
and other monotheistic religions. Everywhere we find associated
with the original idea of a “sole and triune God” later beliefs in a
number of subordinate deities—angels, devils, saints, etc.—a
picturesque assortment of the most diverse theistic forms.
All the above forms of theism, in the proper sense of the word—
whether the belief assumes a naturalistic or an anthropistic form—
represent God to be an extramundane or a supernatural being. He is
always opposed to the world, or nature, as an independent being;
generally as its creator, sustainer, and ruler. In most religions he has
the additional character of personality, or, to put it more definitely
still, God as a person is likened to man. “In his gods man paints
himself.” This anthropomorphic conception of God as one who
thinks, feels, and acts like man prevails with the great majority of
theists, sometimes in a cruder and more naïve form, sometimes in a
more refined and abstract degree. In any case the form of
theosophy we have described is sure to affirm that God, the
supreme being, is infinite in perfection, and therefore far removed
from the imperfection of humanity. Yet, when we examine closely,
we always find the same psychic or mental activity in the two. God
feels, thinks, and acts as man does, although it be in an infinitely
more perfect form.
The personal anthropism of God has become so natural to the
majority of believers that they experience no shock when they find
God personified in human form in pictures and statues, and in the
varied images of the poet, in which God takes human form—that is,
is changed into a vertebrate. In some myths, even, God takes the
form of other mammals (an ape, lion, bull, etc.), and more rarely of
a bird (eagle, dove, or stork), or of some lower vertebrate (serpent,
crocodile, dragon, etc.).
In the higher and more abstract forms of religion this idea of bodily
appearance is entirely abandoned, and God is adored as a “pure
spirit” without a body. “God is a spirit, and they who worship him
must worship him in spirit and in truth.” Nevertheless, the psychic
activity of this “pure spirit” remains just the same as that of the
anthropomorphic God. In reality, even this immaterial spirit is not
conceived to be incorporeal, but merely invisible, gaseous. We thus
arrive at the paradoxical conception of God as a gaseous vertebrate.
II.—PANTHEISM
Pantheism teaches that God and the world are one. The idea of God
is identical with that of nature or substance. This pantheistic view is
sharply opposed in principle to all the systems we have described,
and to all possible forms of theism although there have been many
attempts made from both sides to bridge over the deep chasm that
separates the two. There is always this fundamental contradiction
between them, that in theism God is opposed to nature as an
extramundane being, as creating and sustaining the world, and
acting upon it from without, while in pantheism God, as an
intramundane being, is everywhere identical with nature itself, and is
operative within the world as “force” or “energy.” The latter view
alone is compatible with our supreme law—the law of substance. It
follows necessarily that pantheism is the world-system of the
modern scientist. There are, it is true, still a few men of science who
contest this, and think it possible to reconcile the old theistic theory
of human nature with the pantheistic truth of the law of substance.
All these efforts rest on confusion or sophistry—when they are
honest.
As pantheism is a result of an advanced conception of nature in the
civilized mind, it is naturally much younger than theism, the crudest
forms of which are found in great variety in the uncivilized races of
ten thousand years ago. We do, indeed, find the germs of pantheism
in different religions at the very dawn of philosophy in the earliest
civilized peoples (in India, Egypt, China, and Japan), several
thousand years before the time of Christ; still, we do not meet a
definite philosophical expression of it until the hylozoism of the Ionic
philosophers, in the first half of the sixth century before Christ. All
the great thinkers of this flourishing period of Hellenic thought are
surpassed by the famous Anaximander, of Miletus, who conceived
the essential unity of the infinite universe (apeiron) more profoundly
and more clearly than his master, Thales, or his pupil, Anaximenes.
Not only the great thought of the original unity of the cosmos and
the development of all phenomena out of the all-pervading primitive
matter found expression in Anaximander, but he even enunciated the
bold idea of countless worlds in a periodic alternation of birth and
death.
Many other great philosophers of classical antiquity, especially
Democritus, Heraclitus, and Empedocles, had, in the same or an
analogous sense, a profound conception of this unity of nature and
God, of body and spirit, which has obtained its highest expression in
the law of substance of our modern monism. The famous Roman
poet and philosopher, Lucretius Carus, has presented it in a highly
poetic form in his poem “De Rerum Natura.” However, this true
pantheistic monism was soon entirely displaced by the mystic
dualism of Plato, and especially by the powerful influence which the
idealistic philosophy obtained by its blending with Christian dogmas.
When the papacy attained to its spiritual despotism over the world,
pantheism was hopelessly crushed; Giordano Bruno, its most gifted
defender, was burned alive by the “Vicar of Christ” in the Campo dei
Fiori at Rome on February 17, 1600.
It was not until the middle of the seventeenth century that
pantheism was exhibited in its purest form by the great Baruch
Spinoza; he gave for the totality of things a definition of substance in
which God and the world are inseparably united. The clearness,
confidence, and consistency of Spinoza’s monistic system are the
more remarkable when we remember that this gifted thinker of two
hundred and fifty years ago was without the support of all those
sound empirical bases which have been obtained in the second half
of the nineteenth century. We have already spoken, in the first
chapter, of Spinoza’s relation to the materialism of the eighteenth
and the monism of the nineteenth century. The propagation of his
views, especially in Germany, is due, above all, to the immortal
works of our greatest poet and thinker, Wolfgang Goethe. His
splendid God and the World, Prometheus, Faust, etc., embody the
great thoughts of pantheism in the most perfect poetic creations.
Atheism affirms that there are no gods or goddesses, assuming that
god means a personal, extramundane entity. This “godless world-
system” substantially agrees with the monism or pantheism of the
modern scientist; it is only another expression for it, emphasizing its
negative aspect, the non-existence of any supernatural deity. In this
sense Schopenhauer justly remarks: “Pantheism is only a polite form
of atheism. The truth of pantheism lies in its destruction of the
dualist antithesis of God and the world, in its recognition that the
world exists in virtue of its own inherent forces. The maxim of the
pantheist, ‘God and the world are one,’ is merely a polite way of
giving the Lord God his congé.”
During the whole of the Middle Ages, under the bloody despotism of
the popes, atheism was persecuted with fire and sword as a most
pernicious system. As the “godless” man is plainly identified with the
“wicked” in the Gospel, and is threatened—simply on account of his
“want of faith”—with the eternal fires of hell, it was very natural that
every good Christian should be anxious to avoid the suspicion of
atheism. Unfortunately, the idea still prevails very widely. The
atheistic scientist who devotes his strength and his life to the search
for the truth, is freely credited with all that is evil; the theistic
church-goer, who thoughtlessly follows the empty ceremonies of
Catholic worship, is at once assumed to be a good citizen, even if
there be no meaning whatever in his faith and his morality be
deplorable. This error will only be destroyed when, in the twentieth
century, the prevalent superstition gives place to rational knowledge
and to a monistic conception of the unity of God and the world.
CHAPTER XVI
KNOWLEDGE AND BELIEF
The Knowledge of the Truth and Its Sources: the Activity of the
Senses and the Association of Presentations—Organs of Sense
and Organs of Thought—Sense-Organs and their Specific
Energy—Their Evolution—The Philosophy of Sensibility—
Inestimable Value of the Senses—Limits of Sensitive Knowledge
—Hypothesis and Faith—Theory and Faith—Essential Difference
of Scientific (Natural) and Religious (Supernatural) Faith—
Superstition of Savage and of Civilized Races—Confessions of
Faith—Unsectarian Schools—The Faith of Our Fathers—Spiritism
—Revelation
Every effort of genuine science makes for a knowledge of the truth.
Our only real and valuable knowledge is a knowledge of nature itself,
and consists of presentations which correspond to external things.
We are incompetent, it is true, to penetrate into the innermost
nature of this real world—the “thing in itself”—but impartial critical
observation and comparison inform us that, in the normal action of
the brain and the organs of sense, the impressions received by them
from the outer world are the same in all rational men, and that in
the normal function of the organs of thought certain presentations
are formed which are everywhere the same. These presentations we
call true, and we are convinced that their content corresponds to the
knowable aspect of things. We know that these facts are not
imaginary, but real.
All knowledge of the truth depends on two different, but intimately
connected, groups of human physiological functions: firstly, on the
sense-impressions of the object by means of sense-action, and,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
PDF
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
PDF
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
PDF
Ios 5 Programming Cookbook Solutions Examples For Iphone Ipad And Ipod Touch ...
PDF
Ios 4 Programming Cookbook Solutions Examples For Iphone Ipad And Ipod Touch ...
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
iOS 5 Programming Cookbook Solutions Examples for iPhone iPad and iPod touch ...
Ios 5 Programming Cookbook Solutions Examples For Iphone Ipad And Ipod Touch ...
Ios 4 Programming Cookbook Solutions Examples For Iphone Ipad And Ipod Touch ...

Similar to Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor (20)

PDF
iOS 7 in Action 1st Edition Brendan G. Lim
PDF
iOS 7 in Action 1st Edition Brendan G. Lim
PDF
Programming iOS 14 11th Edition Matt Neuburg
PDF
Programming iOS 5 2nd Edition Matt Neuburg
PDF
Programming iOS 5 2nd Edition Matt Neuburg
PDF
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
PDF
Learning Swift 3 Early release 3rd Edition Jonathan Manning
PDF
Programming iOS 14 11th Edition Matt Neuburg
PDF
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
PDF
Programming Ios 5 2nd Edition 2nd Early Release Draft Matt Neuburg
PDF
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
PDF
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
PDF
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
PDF
Dev101
PDF
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
PDF
Learning Swift 3 Early release 3rd Edition Jonathan Manning
PDF
Apple iPhone App Programming Guide
PDF
Xcode4 userguide Apple
PDF
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
PPTX
Building your first iOS app using Xamarin
iOS 7 in Action 1st Edition Brendan G. Lim
iOS 7 in Action 1st Edition Brendan G. Lim
Programming iOS 14 11th Edition Matt Neuburg
Programming iOS 5 2nd Edition Matt Neuburg
Programming iOS 5 2nd Edition Matt Neuburg
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Programming iOS 14 11th Edition Matt Neuburg
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Programming Ios 5 2nd Edition 2nd Early Release Draft Matt Neuburg
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
Dev101
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Apple iPhone App Programming Guide
Xcode4 userguide Apple
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Building your first iOS app using Xamarin
Ad

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Classroom Observation Tools for Teachers
PDF
Computing-Curriculum for Schools in Ghana
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Institutional Correction lecture only . . .
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Sports Quiz easy sports quiz sports quiz
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Final Presentation General Medicine 03-08-2024.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Supply Chain Operations Speaking Notes -ICLT Program
Classroom Observation Tools for Teachers
Computing-Curriculum for Schools in Ghana
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Institutional Correction lecture only . . .
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Abdominal Access Techniques with Prof. Dr. R K Mishra
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O7-L3 Supply Chain Operations - ICLT Program
VCE English Exam - Section C Student Revision Booklet
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
Ad

Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor

  • 1. Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor download https://ebookbell.com/product/ios-7-programming-cookbook-2nd- edition-vandad-nahavandipoor-4427758 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Ios 7 Programming Fundamentals Matt Neuburg https://ebookbell.com/product/ios-7-programming-fundamentals-matt- neuburg-38546402 Ios 7 Programming Pushing The Limits Rob Napier Mugunth Kumar https://ebookbell.com/product/ios-7-programming-pushing-the-limits- rob-napier-mugunth-kumar-4653670 Programming Ios 7 4th Edition Neuburg Matt https://ebookbell.com/product/programming-ios-7-4th-edition-neuburg- matt-22034556 Windows Phone 7 Programming For Android And Ios Developers 1st Edition Zhinan Zhou https://ebookbell.com/product/windows-phone-7-programming-for-android- and-ios-developers-1st-edition-zhinan-zhou-2349820
  • 3. Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou https://ebookbell.com/product/windows-phone-7-programming-for-android- and-ios-developers-zhinan-zhou-5469884 Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou Robert Zhu Pei Zheng Baijian Yang https://ebookbell.com/product/windows-phone-7-programming-for-android- and-ios-developers-zhinan-zhou-robert-zhu-pei-zheng-baijian- yang-43144166 Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou https://ebookbell.com/product/windows-phone-7-programming-for-android- and-ios-developers-zhinan-zhou-23142176 Windows Phone 7 Programming For Android And Ios Developers 1st Edition Zhinan Zhou https://ebookbell.com/product/windows-phone-7-programming-for-android- and-ios-developers-1st-edition-zhinan-zhou-36137142 Windows Phone 7 Programming For Android And Ios Developers Zhinan Zhou Robert Zhu Pei Zheng Baijian Yang https://ebookbell.com/product/windows-phone-7-programming-for-android- and-ios-developers-zhinan-zhou-robert-zhu-pei-zheng-baijian- yang-43144164
  • 7. Vandad Nahavandipoor iOS 7 Programming Cookbook
  • 8. iOS 7 Programming Cookbook by Vandad Nahavandipoor Copyright © 2014 Vandad Nahavandipoor. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are alsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformation,contactourcorporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Andy Oram and Rachel Roumeliotis Production Editor: Christopher Hearse Copyeditor: Zyg Group, LLC Proofreader: Julie Van Keuren Indexer: Angela Howard Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest October 2013: First Edition Revision History for the First Edition: 2013-10-09: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449372422 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc., iOS 7 Programming Cookbook, the image of a Cowan’s shrew tenrec, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-37242-2 [QG]
  • 9. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Implementing Controllers and Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1. Displaying Alerts with UIAlertView 23 1.2. Creating and Using Switches with UISwitch 32 1.3. Customizing the UISwitch 36 1.4. Picking Values with the UIPickerView 39 1.5. Picking the Date and Time with UIDatePicker 45 1.6. Implementing Range Pickers with UISlider 50 1.7. Customizing the UISlider 54 1.8. Grouping Compact Options with UISegmentedControl 59 1.9. Presenting and Managing Views with UIViewController 63 1.10. Presenting Sharing Options with UIActivityViewController 67 1.11. Presenting Custom Sharing Options with UIActivityViewController 73 1.12. Implementing Navigation with UINavigationController 79 1.13. Manipulating a Navigation Controller’s Array of View Controllers 85 1.14. Displaying an Image on a Navigation Bar 86 1.15. Adding Buttons to Navigation Bars Using UIBarButtonItem 88 1.16. Presenting Multiple View Controllers with UITabBarController 94 1.17. Displaying Static Text with UILabel 101 1.18. Customizing the UILabel 105 1.19. Accepting User Text Input with UITextField 108 1.20. Displaying Long Lines of Text with UITextView 118 1.21. Adding Buttons to the User Interface with UIButton 123 1.22. Displaying Images with UIImageView 127 1.23. Creating Scrollable Content with UIScrollView 132 1.24. Loading Web Pages with UIWebView 137 1.25. Displaying Progress with UIProgressView 141 1.26. Constructing and Displaying Styled Texts 143 iii
  • 10. 1.27. Presenting Master-Detail Views with UISplitViewController 148 1.28. Enabling Paging with UIPageViewController 153 1.29. Displaying Popovers with UIPopoverController 158 2. Creating Dynamic and Interactive User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 2.1. Adding Gravity to Your UI Components 171 2.2. Detecting and Reacting to Collisions Between UI Components 172 2.3. Animating Your UI Components with a Push 180 2.4. Attaching Multiple Dynamic Items to Each Other 184 2.5. Adding a Dynamic Snap Effect to Your UI Components 189 2.6. Assigning Characteristics to Your Dynamic Effects 192 3. Auto Layout and the Visual Format Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 3.1. Placing UI Components in the Center of the Screen 201 3.2. Defining Horizontal and Vertical Constraints with the Visual Format Language 203 3.3. Utilizing Cross View Constraints 210 3.4. Configuring Auto Layout Constraints in Interface Builder 217 4. Constructing and Using Table Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 4.1. Populating a Table View with Data 225 4.2. Using Different Types of Accessories in a Table View Cell 229 4.3. Creating Custom Table View Cell Accessories 232 4.4. Enabling Swipe Deletion of Table View Cells 235 4.5. Constructing Headers and Footers in Table Views 237 4.6. Displaying Context Menus on Table View Cells 246 4.7. Moving Cells and Sections in Table Views 251 4.8. Deleting Cells and Sections from Table Views 257 4.9. Utilizing the UITableViewController for Easy Creation of Table Views 268 4.10. Displaying a Refresh Control for Table Views 274 5. Building Complex Layouts with Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 5.1. Constructing Collection Views 281 5.2. Assigning a Data Source to a Collection View 284 5.3. Providing a Flow Layout to a Collection View 285 5.4. Providing Basic Content to a Collection View 288 5.5. Feeding Custom Cells to Collection Views Using .xib Files 294 5.6. Handling Events in Collection Views 299 5.7. Providing a Header and a Footer in a Flow Layout 303 5.8. Adding Custom Interactions to Collection Views 308 iv | Table of Contents
  • 11. 5.9. Providing Contextual Menus on Collection View Cells 311 6. Storyboards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 6.1. Adding a Navigation Controller to a Storyboard 316 6.2. Passing Data from One Screen to Another 318 6.3. Adding a Tab Bar Controller to a Storyboard 325 6.4. Introducing Custom Segue Transitions to Your Storyboard 328 6.5. Placing Images and Other UI Components on Storyboards 332 7. Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 7.1. Constructing Block Objects 342 7.2. Accessing Variables in Block Objects 346 7.3. Invoking Block Objects 352 7.4. Performing UI-Related Tasks with GCD 354 7.5. Executing Non-UI Related Tasks Synchronously with GCD 358 7.6. Executing Non-UI Related Tasks Asynchronously with GCD 361 7.7. Performing Tasks after a Delay with GCD 368 7.8. Performing a Task Only Once with GCD 371 7.9. Grouping Tasks Together with GCD 373 7.10. Constructing Your Own Dispatch Queues with GCD 377 7.11. Running Tasks Synchronously with Operations 380 7.12. Running Tasks Asynchronously with Operations 387 7.13. Creating Dependency Between Operations 393 7.14. Creating Timers 395 7.15. Creating Concurrency with Threads 400 7.16. Invoking Background Methods 406 7.17. Exiting Threads and Timers 407 8. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 8.1. Enabling Security and Protection for Your Apps 418 8.2. Storing Values in the Keychain 422 8.3. Finding Values in the Keychain 424 8.4. Updating Existing Values in the Keychain 429 8.5. Deleting Exiting Values in the Keychain 432 8.6. Sharing Keychain Data Between Multiple Apps 434 8.7. Writing to and Reading Keychain Data from iCloud 440 8.8. Storing Files Securely in the App Sandbox 443 8.9. Securing Your User Interface 446 9. Core Location and Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 9.1. Creating a Map View 450 9.2. Handling the Events of a Map View 452 Table of Contents | v
  • 12. 9.3. Pinpointing the Location of a Device 453 9.4. Displaying Pins on a Map View 455 9.5. Displaying Pins with Different Colors on a Map View 459 9.6. Displaying Custom Pins on a Map View 465 9.7. Converting Meaningful Addresses to Longitude and Latitude 468 9.8. Converting Longitude and Latitude to a Meaningful Address 470 9.9. Searching on a Map View 472 9.10. Displaying Directions on the Map 475 10. Implementing Gesture Recognizers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 10.1. Detecting Swipe Gestures 483 10.2. Detecting Rotation Gestures 485 10.3. Detecting Panning and Dragging Gestures 489 10.4. Detecting Long-Press Gestures 491 10.5. Detecting Tap Gestures 495 10.6. Detecting Pinch Gestures 497 11. Networking, JSON, XML, and Sharing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 11.1. Downloading Asynchronously with NSURLConnection 501 11.2. Handling Timeouts in Asynchronous Connections 504 11.3. Downloading Synchronously with NSURLConnection 506 11.4. Modifying a URL Request with NSMutableURLRequest 508 11.5. Sending HTTP GET Requests with NSURLConnection 509 11.6. Sending HTTP POST Requests with NSURLConnection 511 11.7. Sending HTTP DELETE Requests with NSURLConnection 513 11.8. Sending HTTP PUT Requests with NSURLConnection 514 11.9. Serializing Arrays and Dictionaries into JSON 516 11.10. Deserializing JSON into Arrays and Dictionaries 518 11.11. Integrating Social Sharing into Your Apps 521 11.12. Parsing XML with NSXMLParser 525 12. Audio and Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 12.1. Playing Audio Files 531 12.2. Handling Interruptions While Playing Audio 534 12.3. Recording Audio 535 12.4. Handling Interruptions While Recording Audio 542 12.5. Playing Audio over Other Active Sounds 543 12.6. Playing Video Files 547 12.7. Capturing Thumbnails from Video Files 551 12.8. Accessing the Music Library 554 13. Address Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 vi | Table of Contents
  • 13. 13.1. Requesting Access to the Address Book 564 13.2. Retrieving a Reference to an Address Book 568 13.3. Retrieving All the People in the Address Book 571 13.4. Retrieving Properties of Address Book Entries 573 13.5. Inserting a Person Entry into the Address Book 577 13.6. Inserting a Group Entry into the Address Book 581 13.7. Adding Persons to Groups 584 13.8. Searching the Address Book 587 13.9. Retrieving and Setting a Person’s Address Book Image 592 14. Files and Folder Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601 14.1. Finding the Paths of the Most Useful Folders on Disk 603 14.2. Writing to and Reading from Files 605 14.3. Creating Folders on Disk 610 14.4. Enumerating Files and Folders 612 14.5. Deleting Files and Folders 618 14.6. Saving Objects to Files 621 15. Camera and the Photo Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625 15.1. Detecting and Probing the Camera 627 15.2. Taking Photos with the Camera 632 15.3. Taking Videos with the Camera 636 15.4. Storing Photos in the Photo Library 639 15.5. Storing Videos in the Photo Library 644 15.6. Retrieving Photos and Videos from the Photo Library 646 15.7. Retrieving Assets from the Assets Library 649 15.8. Editing Videos on an iOS Device 656 16. Multitasking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663 16.1. Detecting the Availability of Multitasking 664 16.2. Completing a Long-Running Task in the Background 665 16.3. Adding Background Fetch Capabilities to Your Apps 669 16.4. Playing Audio in the Background 678 16.5. Handling Location Changes in the Background 682 16.6. Saving and Loading the State of Multitasking Apps 684 16.7. Handling Network Connections in the Background 688 16.8. Opting Out of Multitasking 691 17. Notifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 17.1. Sending Notifications 694 17.2. Listening for and Reacting to Notifications 696 17.3. Listening and Reacting to Keyboard Notifications 700 Table of Contents | vii
  • 14. 17.4. Scheduling Local Notifications 707 17.5. Listening for and Reacting to Local Notifications 711 17.6. Handling Local System Notifications 714 17.7. Setting Up Your App for Push Notifications 718 17.8. Delivering Push Notifications to Your App 724 17.9. Reacting to Push Notifications 732 18. Core Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 18.1. Creating a Core Data Model with Xcode 737 18.2. Generating Class Files for Core Data Entities 741 18.3. Creating and Saving Data Using Core Data 745 18.4. Reading Data from Core Data 747 18.5. Deleting Data from Core Data 750 18.6. Sorting Data in Core Data 752 18.7. Boosting Data Access in Table Views 754 18.8. Implementing Relationships in Core Data 761 18.9. Fetching Data in the Background 768 18.10. Using Custom Data Types in Your Core Data Model 772 19. Dates, Calendars, and Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779 19.1. Requesting Permission to Access Calendars 784 19.2. Retrieving Calendar Groups on an iOS Device 790 19.3. Adding Events to Calendars 792 19.4. Accessing the Contents of Calendars 796 19.5. Removing Events from Calendars 799 19.6. Adding Recurring Events to Calendars 803 19.7. Retrieving the Attendees of an Event 808 19.8. Adding Alarms to Calendars 811 19.9. Handling Event Changed Notifications 814 19.10. Presenting Event View Controllers 816 19.11. Presenting Event Edit View Controllers 822 20. Graphics and Animations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827 20.1. Enumerating and Loading Fonts 833 20.2. Drawing Text 835 20.3. Constructing, Setting, and Using Colors 836 20.4. Drawing Images 841 20.5. Constructing Resizable Images 845 20.6. Drawing Lines 850 20.7. Constructing Paths 858 20.8. Drawing Rectangles 862 20.9. Adding Shadows to Shapes 866 viii | Table of Contents
  • 15. 20.10. Drawing Gradients 873 20.11. Moving Shapes Drawn on Graphic Contexts 882 20.12. Scaling Shapes Drawn on Graphic Contexts 886 20.13. Rotating Shapes Drawn on Graphic Contexts 889 20.14. Animating and Moving Views 890 20.15. Animating and Scaling Views 900 20.16. Animating and Rotating Views 901 20.17. Capturing a Screenshot of Your View into an Image 903 21. Core Motion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907 21.1. Detecting the Availability of an Accelerometer 908 21.2. Detecting the Availability of a Gyroscope 910 21.3. Retrieving Accelerometer Data 911 21.4. Detecting Shakes on an iOS Device 915 21.5. Retrieving Gyroscope Data 916 22. iCloud. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919 22.1. Setting Up Your App for iCloud 920 22.2. Storing and Synchronizing Dictionaries in iCloud 924 22.3. Creating and Managing Folders for Apps in iCloud 929 22.4. Searching for Files and Folders in iCloud 936 22.5. Storing User Documents in iCloud 946 22.6. Managing the State of Documents in iCloud 961 23. Pass Kit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 965 23.1. Creating Pass Kit Certificates 968 23.2. Creating Pass Files 975 23.3. Providing Icons and Images for Passes 984 23.4. Preparing Your Passes for Digital Signature 987 23.5. Signing Passes Digitally 989 23.6. Distributing Passes Using Email 993 23.7. Distributing Passes Using Web Services 995 23.8. Enabling Your iOS Apps to Access Passes on iOS Devices 997 23.9. Interacting with Passbook Programmatically 1003 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007 Table of Contents | ix
  • 17. Preface This edition of the book is not just an update, but a total remake of the previous edition. iOS 7 changed everything: the look and feel, the way we use our iOS devices, and most importantly, the way we program for iOS devices. This called for a substantial rewrite indeed. I have added roughly 50 new recipes to this book, talking about things such as UIKit dynamics, collection views, the keychain, push notifications, and whatnot. I have also gone through all the example codes and figures and updated them for iOS 7. iOS 7 is a huge step forward for this amazing operating system that we all, as program‐ mers and users, have grown to love and enjoy programming for. You must have noticed how the focus of iOS 7 is on being dynamic: how your UI should adapt to various movements and motions that can be applied to the device. What I mean by that is Apple wants developers to really look at the details of their apps and bring real-world physics and dynamics into them. That’s why Apple introduced UIKit Dynamics to the SDK, and that is why this book has a whole chapter dedicated to this concept. The more expensive a high-end device such as the new iPhone becomes, the more demanding the users will get as well. Nobody blames them, though! They have just bought a fantastic and top- of-the-line new iPhone or iPad and they want to see amazing apps running on them, leveraging all the capabilities that those devices have to offer. That is why now more than ever developers have to get an in-depth knowledge of the SDK and what the SDK has to offer to the developers so that we can create better and faster apps for iOS users. Apple introduced a lot of cool new APIs to the iOS 7 SDK, and we are going to explore them in this book. The focus of iOS 7 is dynamics! Before you read about this book, maybe you’d like to know about my background a bit and how I can help you through this journey. I will just briefly let you know who I am and how I got to love iOS. I started out writing Basic code for my Commodore 64 when Iwasakid.IthenmovedontobuymyownPCandstartedexperimentingwithAssembly code. At first, it was 8-bit Assembly for DOS. I then moved onto writing my own hobby xi
  • 18. operating system, which was never really released as a commercial product, for 32-bit Intel x86 CPU architectures. Among all the programming languages that I have programmed in, Assembly and Objective-C are the two that have really been different from the others, and I’ve really liked them. Assembly because of the purity of the language: a command does only one thing and does that one thing well. I believe that I like Objective-C for the same reason, and in fact iOS shares the same trait with Assembly and Objective-C. Even though iOS is an operating system and not a programming language, whatever it does, it does it best and better than its rivals. From its simplicity to the sheer power that you can harvest from the software and the hardware combined, using technologies such as GCD, the bar that iOS has set in terms of ease of use and beauty is unprecedented. This edition of the book has seen all the recipes inside all chapters completely renewed for iOS 7. All screenshots have been updated, and many more recipes—such as those related to security and the keychain, UI dynamics, collection views, push and local notifications, and many more—have exclusively been written for this edition of the book. I really have had a fun time writing this edition of the book, and packed as it is with new features, I hope you’ll enjoy reading it. May it be a valuable addition to your tech-book library. Audience I assume you are comfortable with the iOS development environment and know how to create an app for the iPhone or iPad. This book does not get novice programmers started but presents useful ways to get things done for iOS programmers ranging from novices to experts. Organization of This Book In this book, we will discuss frameworks and classes that are available in the iOS 7 SDK. This book does its best to teach you the latest and the greatest APIs. As you know, some users of your apps may still be on older versions of iOS, so please consider those users and choose your APIs wisely, depending on the minimum iOS version that you want to target with your apps. Apple has recommended that you write your apps so that they support and run on iOS 6 and iOS 7. This means you need to use the latest SDK as your base SDK (the SDK that youusetocompileyourapp)andchooseiOS6asyourtarget,ifthat’swhatyourbusiness requirements dictate. If you are required to write your app to support only iOS 7, then you are in for a lot of fun, as you can use all the cool APIs that have been introduced in iOS 7 and discussed in this book. xii | Preface
  • 19. Here is a concise breakdown of the material each chapter covers: Chapter 1, Implementing Controllers and Views Explains how Objective-C classes are structured and how objects can be instanti‐ ated. The chapter talks about properties and delegates and subscripting by keys and indexes. Even if you are competent in Objective-C, I strongly suggest that you read this chapter, even if you only skim through it, to understand the basic material that is used in the rest of the book. In this chapter, we will also explore the common usage of various UI components, such as alert views, segmented controls, switches, and labels. We will also talk about customizing these components with the latest APIs provided in the SDK. Chapter 2, Creating Dynamic and Interactive User Interfaces Talks about UIKit Dynamics, the newest addition to the UIKit framework. These dynamics allow you to add real-life physics and dynamics to your UI components. This will allow you to create even livelier user interfaces with very small effort on your side. Chapter 3, Auto Layout and the Visual Format Language Explains how you can take advantage of Auto Layout in the iOS SDK in order to construct your UI in such a way that it can be resized and stretched to pretty much any screen dimension. Chapter 4, Constructing and Using Table Views Shows how you can work with table views to create professional-looking iOS ap‐ plications. Table views are very dynamic in nature, and as a result, programmers sometimes have difficulty understanding how they should work with them. By reading this chapter and trying out the example code, you will gain the knowledge that is required to comfortably work with table views. Chapter 5, Building Complex Layouts with Collection Views Collection views have been available to OS X programmers for quite some time now, and Apple decided to provide the same APIs to iOS programmers in the iOS SDK. Collection views are very much like table views, but they are much more configurable and dynamic. Where in table views we have the concept of sections and rows in each section, collection views bring columns to the equation as well, so that you can display many items in one row if you want to. In this chapter we will have a look at all the great user interfaces that you can create using collection views. Chapter 6, Storyboards Demonstrates the process of storyboarding, the new way to define the connections between different screens in your app. The great thing about storyboarding is that you don’t have to know anything about iOS programming to get a simple app run‐ ning. This helps product analysts, product owners, or designers who work inde‐ pendently of developers to gain knowledge of the UI components iOS offers and to Preface | xiii
  • 20. buildmorerobustproducts.Programmerscanalsotakeadvantageofstoryboarding to easily create prototypes. Storyboarding is just fun, whether you do it on paper or using Xcode. Chapter 7, Concurrency As humans, we can do many things simultaneously without thinking much about it. With advances in computer technology, mobile devices are also able to multitask, and they provide programmers with tools and mechanisms that can accomplish more than one task at the same time. This is called concurrency. In this chapter, you will learn about Grand Central Dispatch, Apple’s preferred way of achieving con‐ currency in iOS. You will also learn about timers, threads, and operations. Chapter 8, Security iOS is a very secure operating system, and apps that we write for it also have to adhere to certain security standards and practices. In this chapter, we will discuss how you can take advantage of keychain APIs to make your apps more secure. We will also talk about various steps that you can take to make your user interface more secure. Chapter 9, Core Location and Maps DescribeshowyoushoulduseMapKitandCoreLocationAPIstodeveloplocation- aware iOS applications. First you will learn about maps, and then you will learn how to detect a device’s location and tailor your maps with custom annotations. You will also learn about geocoding and reverse geocoding, as well as some of the methods of the Core Location framework, which are available only in iOS 7. Chapter 10, Implementing Gesture Recognizers Demonstrates how to use gesture recognizers, which enable your users to easily and intuitively manipulate the graphical interface of your iOS applications. In this chapter, you will learn how to use all available gesture recognizers in the iOS SDK, with working examples tested on iOS 7. Chapter 11, Networking, JSON, XML, and Sharing Demonstrates the built-in JSON and XML parsers. On top of that, this chapter talks about various networking APIs and how programmers can build social networking into our apps to allow our users to share their creations and data to social networks such as Facebook. Chapter 12, Audio and Video Discusses the AV Foundation and Media Player frameworks that are available on the iOS SDK. You will learn how to play audio and video files and how to handle interruptions, such as a phone call, while the audio or video is being played. This chapter also explains how to record audio using an iOS device’s built-in micro‐ phone(s). At the end of the chapter, you will learn how to access the Music Library and play its media content, all from inside your application. xiv | Preface
  • 21. Chapter 13, Address Book Explains the Address Book framework and how to retrieve contacts, groups, and their information from the Address Book database on an iOS device. The Address Book framework is composed entirely of C APIs. Because of this, many Objective- C developers find it difficult to use this framework, as compared with frameworks that provide an Objective-C interface. After reading this chapter and trying the examples for yourself, you will feel much more confident using the Address Book framework. Chapter 14, Files and Folder Management One of the most important tasks that, as developers, we want to perform in our iOS apps is manipulating files and folders. Whether this means creating, reading from, writing to, or deleting them, this chapter contains enough material to get you up and running with file and folder management in the iOS SDK. Chapter 15, Camera and the Photo Library Demonstrates how you can determine the availability of front- and back-facing cameras on an iOS device. You will also learn how to access the photo library using the Assets Library framework. At the end of the chapter, you will learn about editing videos right on an iOS device using a built-in view controller. Chapter 16, Multitasking Showsmultitasking-awareapplicationsthatrunbeautifullyoniOSdevices.Youwill learn about background processing, including how to play audio and retrieve users’ locations in the background, as well as how to download content from a URL while your application is running in the background. On top of that, we will explore some of the new APIs that iOS 7 provides to us, in order to enable our apps to download content periodically while in the background or even while our app is not even running. Chapter 17, Notifications Notificationsareobjectsthatcanbecomposedbyasourceanddeliveredtomultiple recipients.Inthischapter,wewilldiscussnotifications,includinglocalnotifications and push notifications, along with how you can use the latest capabilities built into Xcode to easily enable these features in your own apps. Chapter 18, Core Data Describes the details of Core Data stacks and what they are made out of. You will thenbeabletodesignyourownobject-orienteddatamodelsrightintoXcode,using the Core Data model editor, and also create and retrieve your objects in Core Data. On top of that, you will learn how to add your own custom data to Core Data and how to search for data in the background thread, leaving your UI thread ready to process user events. Preface | xv
  • 22. Chapter 19, Dates, Calendars, and Events Demonstrates the use of the Event Kit and Event Kit UI frameworks in order to manage calendars and events on an iOS device. You will see how to create, modify, save, and delete events. You will also learn, through examples, how to add alarms to calendar events and how to set up CalDAV calendars so that you can share a single calendar among multiple devices. Chapter 20, Graphics and Animations Introduces the Core Graphics framework. You will learn how to draw images and text on a graphics context; draw lines, rectangles, and paths; and much more. You will also learn to use the new iOS SDK APIs to capture your views’ contents as screenshots. Chapter 21, Core Motion Explains the Core Motion framework. Using Core Motion, you will access the ac‐ celerometer and the gyroscope on an iOS device. You will also learn how to detect shakes on a device. Of course, not all iOS devices are equipped with an accelerom‐ eter and a gyroscope, so you will also learn how to detect the availability of the required hardware. Chapter 22, iCloud Shows how to use the iCloud service, which ties devices together and allows them to share data to provide a seamless user experience as the user moves from one device to another. Chapter 23, Pass Kit Describes Passbook: a virtual wallet, if you will, capable of managing your coupons, boarding passes, rail and bus tickets, and much more. In this chapter, you will learn all there is to know in order to be able to create your own digitally signed passes and distribute them to your users easily. Additional Resources From time to time, I refer to official Apple documentation. Some of Apple’s descriptions are right on the mark, and there is no point in trying to restate them. Throughout this book, I have listed the most important documents and guides in the official Apple doc‐ umentation that every professional iOS developer should read. For starters, I suggest that you have a look at the iOS Human Interface Guidelines for all iOS devices. This document will tell you everything you need to know about devel‐ oping engaging and intuitive user interfaces for all iOS devices. Every iOS programmer should read this document. In fact, I believe this should be required reading for the product design and development teams of any company that develops iOS applications. xvi | Preface
  • 23. I also suggest that you skim through the “iOS App Programming Guide” in the iOS Developer Library for some tips and advice on how to make great iOS applications. iOS 7 brings with itself quite a lot of changes to how UI components appear on the screen.Wewilltalkatgreatlengthaboutthesechangesandhowyou,astheprogrammer, can use the latest APIs to create great-looking apps for iOS 7. However, I would like to suggest that you have a look at the iOS 7 UI Transition Guide provided by Apple, which outlines all the UI changes that have now been made to the latest version of the SDK. One of the things you will notice when reading Chapter 16 is the use of block objects. This book concisely explains block objects, but if you require further details on the subject, I suggest you read “A Short Practical Guide to Blocks”. Throughout this book, you will see references to “bundles” and loading images and data from bundles. You will read a concise overview about bundles in this book, but if you require further information, head over to the “Bundle Programming Guide”. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Preface | xvii
  • 24. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/oreillymedia/iOS7_programming_cookbook. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of ex‐ ample code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “iOS 7 Programming Cookbook by Vandad Nahavandipoor (O’Reilly). Copyright 2014 Vandad Nahavandipoor, 978-1-4493-7242-2.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at permissions@oreilly.com. Safari® Books Online Safari Books Online (www.safaribooksonline.com) is an on- demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and busi‐ ness. Technology professionals, software developers, web designers, and business and crea‐ tive professionals use Safari Books Online as their primary resource for research, prob‐ lem solving, learning, and certification training. Safari Books Online offers a range of product mixes and pricing programs for organi‐ zations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐ fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐ ogy, and dozens more. For more information about Safari Books Online, please visit us online. xviii | Preface
  • 25. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/iOS7-Programming-Cookbook. To comment or ask technical questions about this book, send email to bookques tions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments Andy Oram, my lovely editor, has again done an amazing job going through all the changes that I made in this edition of the book. In fact, the whole book is updated in this edition, and all example codes and screenshots have also been updated. I’d like to alsothankKrzysztofGrobelnyandKrzysztofGutowski,mygreatfriendsandcolleagues, for tech-reviewing this book. Without their help, this book wouldn’t be in your hands. I’d like to say thank you to Rachel Roumeliotis, for supporting me and Andy, among all the other admin work that she did for us behind the scenes. Rachel, you may be quiet, but we’d have to be blind not to notice your hard work in the background. Also, Meghan Connolly of O’Reilly has been a fantastic sport, listening to my nagging about paper‐ work, and she has been absolute bliss to work with. A thank-you goes to Jessica Hosman for helping us a great deal with Git issues. Even though I didn’t believe the simple sol‐ utions that she suggested to me would work, they did, and I looked like a fool. Last but not least, thank you to Alina Rizzoni, Bruno Packham, and Thomas Packham for being real friends. I feel blessed to know them, and I appreciate their help and support. Preface | xix
  • 27. CHAPTER 1 Implementing Controllers and Views 1.0. Introduction iOS 7 has introduced a lot of new features to users, as well as tons of new APIs for us programmers to use and play with. You probably already know that the user interface has drastically changed in iOS 7. This user interface had stayed intact all the way from the first version of iOS till now, and because of this, many apps were coded on the assumption that this user interface would not ever change. Graphic designers are now faced with the challenge of creating the user interface and thinking about the user ex‐ perience in a way that makes it great for both pre- and post-iOS 7 user interfaces (UIs). In order to write apps for iOS 7, you need to know some of the basics of the Objective- C programming language that we will use throughout this book. Objective-C, as its name implies, is based on C with extensions that allow it to make use of objects. Objects and classes are fundamental in object-oriented programming (OOP) languages such as Objective-C, Java, C++, and many others. In Objective-C, like any other object-oriented language(OOL),youhavenotonlyaccesstoobjects,butalsotoprimitives.Forinstance, the number –20 (minus twenty) can be expressed simply as a primitive in this way: NSInteger myNumber = -20; This simple line of code will define a variable named myNumber with the data type of NSInteger and sets its value to 20. This is how we define variables in Objective-C. A variable is a simple assignment of a name to a location in memory. In this case, when we set 20 as the value of the myNumber variable, we are telling the machine that will eventually run this piece of code to put the aforementioned value in a memory location that belongs to the variable myNumber. All iOS applications essentially use the model-view-controller (MVC) architecture. Model, view, and controller are the three main components of an iOS application from an architectural perspective. 1
  • 28. The model is the brain of the application. It does the calculations and creates a virtual world for itself that can live without the views and controllers. In other words, think of a model as a virtual copy of your application, without a face! Aviewisthewindowthroughwhichyourusersinteractwithyourapplication.Itdisplays what’s inside the model most of the time, but in addition to that, it accepts users’ inter‐ actions. Any interaction between the user and your application is sent to a view, which then can be captured by a view controller and sent to the model. The controller in iOS programming usually refers to the view controllers I just men‐ tioned. Think of a view controller as a bridge between the model and your views. This controller interprets what is happening on one side and uses that information to alter the other side as needed. For instance, if the user changes some field in a view, the controller makes sure the model changes in response. And if the model gets new data, the controller tells the view to reflect it. In this chapter, you will learn how to create the structure of an iOS application and how to use views and view controllers to create intuitive applications. In this chapter, for most of the user interface (UI) components that we create, we are using a Single View Application template in Xcode. To reproduce the examples, follow the instructions in “Creating and Run‐ ning Our First iOS App” on page 2. Make sure that your app is uni‐ versal, as opposed to an iPhone or iPad app. A universal app can run on both iPhone and iPad. Creating and Running Our First iOS App Before we dive any deeper into the features of Objective-C, we should have a brief look at how to create a simple iOS app in Xcode. Xcode is Apple’s IDE (integrated develop‐ ment environment) that allows you to create, build, and run your apps on iOS Simulator and even on real iOS devices. We will talk more about Xcode and its features as we go along, but for now let’s focus on creating and running a simple iOS app. I assume that you’ve already downloaded Xcode into your computer from the Mac App Store. Once that step is taken care of, please follow these steps to create and run a simple iOS app: 1. Open Xcode if it’s not already open. 2. From the File menu, choose New Project... 3. In the New Project window that appears, on the lefthand side under the iOS cate‐ gory, choose Application and then on the righthand side choose Single View Ap‐ plication. Then press the Next button. 4. On the next screen, for the Product Name, enter a name that makes sense for you. For instance, you can set the name of your product as My First iOS App. In the 2 | Chapter 1: Implementing Controllers and Views
  • 29. Organization Name section, enter your company’s name, or if you don’t have a company, enter anything else that makes sense to you. The organization name is quite an important piece of information that you can enter here, but for now, you don’t have to worry about it too much. For the Company Identifier field, enter com.mycompany. If you really do own a company or you are creating this app for a company that you work with, replace mycompany with the actual name of the com‐ pany in question. If you are just experimenting with development on your own, invent a name. For the Devices section, choose Universal. 5. Onceyouaredonesettingtheaforementionedvalues,simplypresstheNextbutton. 6. You are now being asked by Xcode to save your project to a suitable place. Choose a suitable folder for your project and press the Create button. 7. Assoonasyourprojectiscreated,youarereadytobuildandrunit.However,before you begin, make sure that you’ve unplugged all your iOS devices from your com‐ puter. The reason behind this is that once an iOS device is plugged in, by default, Xcode will attempt to build and run your project on the device, causing some issues with provisioning profiles (which we haven’t talked about yet). So unplug your iOS devices and then press the big Run button on the top-lefthand corner of Xcode. If you cannot find the Run button, go to the Product menu and select the Run menu item. Voilà! Your first iOS app is running in iOS Simulator now. Even though the app is not exactly impressive, simply displaying a white screen in the simulator, this is just the first step toward our bigger goal of mastering the iOS SDK, so hold on tight as we embark on this journey together. Defining and Understanding Variables All modern programming languages, including Objective-C, have the concept of vari‐ ables. Variables are simple aliases to locations in the memory. Every variable can have the following properties: 1. A data type, which is either a primitive, such as an integer, or an object 2. A name 3. A value You don’t always have to set a value for a variable, but you need to specify its type and its name. Here are a few data types that you will need to know about when writing any typical iOS app: 1.0. Introduction | 3
  • 30. Mutable Versus Immutable If a data type is mutable, you can change if after it is initialized. For instance, you can change one of the values in a mutable array, or add or remove values. In contrast, you must provide the values to an im‐ mutable data type when you initialize it, and cannot add to them, remove them, or change them later. Immutable types are useful be‐ cause they are more efficient, and because they can prevent errors when the values are meant to stay the same throughout the life of the data. NSInteger and NSUInteger Variables of this type can hold integral values such as 10, 20, etc. The NSInteger type allows negative values as well as positive ones, but the NSUInteger data type is the Unsigned type, hence the U in its name. Remember, the phrase unsigned in programming languages in the context of numbers always means that the number must not be negative. Only a signed data type can hold negative numbers. CGFloat Holds floating point variables with decimal points, such as 1.31 or 2.40. NSString Allows you to store strings of characters. We will see examples of this later. NSNumber Allows you to store numbers as objects. id Variables of type id can point to any object of any type. These are called untyped objects. Whenever you want to pass an object from one place to another but do not wish to specify its type for whatever reason, you can take advantage of this data type. NSDictionary and NSMutableDictionary These are immutable and mutable variants of hash tables. A hash table allows you to store a key and to associate a value to that key, such as a key named phone_num that has the value 05552487700. Read the values by referring to the keys associated with them. NSArray and NSMutableArray Immutableandmutablearraysofobjects.Anarrayisanorderedcollectionofitems. For instance, you may have 10 string objects that you want to store in memory. An array could be a good place for that. NSSet, NSMutableSet, NSOrderedSet, NSMutableOrderedSet Sets are like arrays in that they can hold series of objects, but they differ from arrays in that they contain only unique objects. Arrays can hold the same object multiple 4 | Chapter 1: Implementing Controllers and Views
  • 31. times, but a set can contain only one instance of an object. I encourage you to learn the difference between arrays and sets and use them properly. NSData and NSMutableData Immutable and mutable containers for any data. These data types are perfect when you want to read the contents of a file, for instance, into memory. Some of the data types that we talked about are primitive, and some are classes. You’ll just have to memorize which is which. For instance, NSInteger is a primitive data type, but NSString is a class, so objects can be instantiated of it. Objective-C, like C and C++, has the concept of pointers. A pointer is a data type that stores the memory address where the real data is stored. You should know by now that pointers to classes are denoted using an asterisk sign: NSString *myString = @"Objective-C is great!"; Thus, when you want to assign a string to a variable of type NSString in Objective-C, you simply have to store the data into a pointer of type NSString *. However, if you are about to store a floating point value into a variable, you wouldn’t specify it as a pointer since the data type for that variable is not a class: /* Set the myFloat variable to PI */ CGFloat myFloat = M_PI; If you wanted to have a pointer to that floating point variable, you could do so as follows: /* Set the myFloat variable to PI */ CGFloat myFloat = M_PI; /* Create a pointer variable that points to the myFloat variable */ CGFloat *pointerFloat = &myFloat; Getting data from the original float is a simple dereference (myFloat), whereas getting the value of through the pointer requires the use of the asterisk (*pointerFloat). The pointer can be useful in some situations, such as when you call a function that sets the value of a floating-point argument and you want to retrieve the new value after the function returns. Going back to classes, we probably have to talk a bit more about classes before things get lost in translation, so let’s do that next. Creating and Taking Advantage of Classes A class is a data structure that can have methods, instance variables, and properties, along with many other features, but for now we are just going to talk about the basics. Every class has to follow these rules: 1.0. Introduction | 5
  • 32. • The class has to be derived from a superclass, apart from a few exceptions such as NSObject and NSProxy classes, which are root classes. Root classes do not have a superclass. • It has to have a name that conforms to Cocoa’s naming convention for methods. • It has to have an interface file that defines the interface of the class. • It has to have an implementation where you implement the features that you have promised to deliver in the interface of the class. NSObject is the root class from which almost every other class is inherited. For this example, we are going to add a class, named Person, to the project we created in “Cre‐ ating and Running Our First iOS App” on page 2. We are going to then add two prop‐ erties to this class, named firstName and lastName, of type NSString. Follow these steps to create and add the Person class to your project: 1. In Xcode, while your project is open and in front of you, from the File menu, choose New → File... 2. On the lefthand side, ensure that under the iOS main section you have chosen the Cocoa Touch category. Once done, select the Objective-C Class item and press the Next button. 3. In the Class section, enter Person. 4. In the “Subclass of” section, enter NSObject. 5. Once done, press the Next button, at which point Xcode will ask where you would like to save this file. Simply save the new class into the folder where you have placed your project and its files. This is the default selection. Then press the Create button, and you are done. You now have two files added to your project: Person.h and Person.m. The former is the interface and the latter is the implementation file for your Person class. In Objective- C, .h files are headers, where you define the interface of each class, and .m files are implementation files where you write the actual implementation of the class. Now let’s go into the header file of our Person class and define two properties for the class, of type NSString: @interface Person : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; @end Just like a variable, definition of properties has its own format, in this particular order: 6 | Chapter 1: Implementing Controllers and Views
  • 33. 1. The definition of the property has to start with the @property keyword. 2. You then need to specify the qualifiers of the property. nonatomic properties are not thread-safe. We will talk about thread safety in Chapter 16. You can also specify assign, copy, weak, strong, or unsafe_unretained as the property qualifiers. We will read more about these soon too. 3. You then have to specify the data type of the property, such as NSInteger or NSString. 4. Last but not least, you have to specify a name for the property. The name of the property has to follow the Apple guidelines. We said that properties can have various qualifiers. Here are the important qualifiers that you need to know about: strong Properties of this type will be retained by the runtime. These can only be instances of classes. In other words, you cannot retain a value into a property of type strong if the value is a primitive. You can retain objects, but not primitives. copy The same as strong, but when you assign to properties of this type, the runtime will make a copy of the object on the right side of the assignment. The object on the righthand side of the assignment must conform to the NSCopying or NSMutable Copying protocol. assign Objects or primitive values that are set as the value of a property of type assign will not be copied or retained by that property. For primitive properties, this qualifier will create a memory address where you can put the primitive data. For objects, properties of this type will simply point to the object on the righthand side of the equation. unsafe_unretained The same as the assign qualifier. weak The same as the assign qualifier with one big difference. In the case of objects, when the object that is assigned to a property of this type is released from memory, the runtime will automatically set the value of this property to nil. We now have a Person class with two properties: firstName and lastName. Let’s go back to our app delegate’s implementation (AppDelegate.m) file and instantiate an object of type Person: #import "AppDelegate.h" #import "Person.h" 1.0. Introduction | 7
  • 34. @implementation AppDelegate - (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ Person *person = [[Person alloc] init]; person.firstName = @"Steve"; person.lastName = @"Jobs"; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } We are allocating and initializing our instance of the Person class in this example. You may not know what that means yet, but continue to the “Adding Functionality to Classes with Methods” on page 8 section and you will find out. Adding Functionality to Classes with Methods Methods are building blocks of classes. For instance, a class named Person can have logical functionalities such as walk, breathe, eat, and drink. These functionalities are usually encapsulated in methods. A method can take parameters, which are variables that the caller passes when calling themethodandarevisibleonlytothemethod.Forinstance,inasimpleworld,wewould have a walk method for our Person class. However, if you want, you can add a parameter or argument to the method and name it walkingSpeed of type CGFloat, so that when another programmer calls that method on your class, she can specify the speed at which the person has to walk. You, as the programmer of that class, would then write the appropriate code for your class to handle different speeds of walking. Don’t worry if this all sounds like too much, but have a look at the following example, where I have added a method to the implementation file we created in “Creating and Taking Advantage of Classes” on page 5 for our Person class: #import "Person.h" @implementation Person - (void) walkAtKilometersPerHour:(CGFloat)paramSpeedKilometersPerHour{ /* Write the code for this method here */ } - (void) runAt10KilometersPerHour{ /* Call the walk method in our own class and pass the value of 10 */ 8 | Chapter 1: Implementing Controllers and Views
  • 35. [self walkAtKilometersPerHour:10.0f]; } @end A typical method has the following qualities in Objective-C: 1. A prefix to tell the compiler whether the method is an instance method (-) or a class method (+). An instance method can be accessed only after the programmer allo‐ cates and initializes an instance of your class. A class method can be accessed by calling it directly from the class itself. Don’t worry if this all sounds complicated. We will see examples of these methods in this book, so don’t get hung up on this for now. 2. A data type for the method, if the method returns any value. In our example, we have specified void, telling the compiler that we are not returning anything. 3. The first part of the method name followed by the first parameter. You don’t nec‐ essarily have to have any parameters for a method. You can have methods that take no parameters. 4. The list of subsequent parameters following the first parameter. Let me show you an example of a method with two parameters: - (void) singSong:(NSData *)paramSongData loudly:(BOOL)paramLoudly{ /* The parameters that we can access here in this method are: paramSongData (to access the song's data) paramLoudly will tell us if we have to sing the song loudly or not */ } It’s important to bear in mind that every parameter in every method has an external and an internal name. The external name is part of the method, whereas the internal part is the actual name or alias of the parameter that can be used inside the method’s imple‐ mentation. In the previous example, the external name of the first parameter is sing‐ Song, whereas its internal name is paramSongData. The external name of the second parameter is loudly, but its internal name is paramLoudly. The method’s name and the external names of its parameters combine to form what is known as the selector for the method. The selector for the aforementioned method in this case would be sing Song:loudly:. A selector, as you will later see in this book, is the runtime identifier of every method. No two methods inside a single class can have the same selector. In our example, we have defined three methods for our Person class, inside its imple‐ mentation file (Person.m): • walkAtKilometersPerHour: • runAt10KilometersPerHour 1.0. Introduction | 9
  • 36. • singSong:loudly: If we want to be able to use any of these methods from the outside world—for instance, from the app delegate—we should expose those methods in our interface file (Person.h): #import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; - (void) walkAtKilometersPerHour:(CGFloat)paramSpeedKilometersPerHour; - (void) runAt10KilometersPerHour; /* Do not expose the singSong:loudly: method to the outside world. That method is internal to our class. So why should we expose it? */ @end Given this interface file, a programmer can call the walkAtKilometersPerHour: and the runAt10KilometersPerHour methods from outside the Person class, but not the singSong:loudly: method because it has not been exposed in the file. So let’s go ahead and try to call all three of these methods from our app delegate to see what happens! - (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ Person *person = [[Person alloc] init]; [person walkAtKilometersPerHour:3.0f]; [person runAt10KilometersPerHour]; /* If you uncomment this line of code, the compiler will give you an error telling you this method doesn't exist on the Person class */ //[person singSong:nil loudly:YES]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } Now we know how to define and call instance methods, but what about class methods? Let’s first find out what class methods are and how they differ from instance methods. An instance method is a method that relates to an instance of a class. For instance, in our Person class, you can instantiate this class twice to create two distinct persons in a hypothetical game that you are working on and have one of those persons walk at the speed of 3 kilometers an hour while the other person walks at 2 kilometers an hour. 10 | Chapter 1: Implementing Controllers and Views
  • 37. Even though you have written the code for the walking instance method only once, when two separate instances of the Person class are created at runtime, the calls to the instance methods will be routed to the appropriate instance of this class. In contrast, class methods work on the class itself. For instance, in a game where you have instances of a class named Light that light the scenery of your game, you may have a dimAllLights class method on this class that a programmer can call to dim all lights in the game, no matter where they are placed. Let’s have a look at an example of a class method on our Person class: #import "Person.h" @implementation Person + (CGFloat) maximumHeightInCentimeters{ return 250.0f; } + (CGFloat) minimumHeightInCentimeters{ return 40.0f; } @end The maximumHeightInCentimeters method is a class method that returns the hypo‐ thetical maximum height of any person in centimeters. The minimumHeightInCentim eters class method returns the minimum height of any person. Here is how we would then expose these methods in the interface of our class: #import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; @property (nonatomic, assign) CGFloat currentHeight; + (CGFloat) maximumHeightInCentimeters; + (CGFloat) minimumHeightInCentimeters; @end We have also added a new floating point property to our Person class named currentHeight. This allows instances of this class to be able to store their height in memory for later reference, just like their first or last names. And in our app delegate, we would proceed to use these new methods like so: 1.0. Introduction | 11
  • 38. - (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ Person *steveJobs = [[Person alloc] init]; steveJobs.firstName = @"Steve"; steveJobs.lastName = @"Jobs"; steveJobs.currentHeight = 175.0f; /* Centimeters */ if (steveJobs.currentHeight >= [Person minimumHeightInCentimeters] && steveJobs.currentHeight <= [Person maximumHeightInCentimeters]){ /* The height of this particular person is in the acceptable range */ } else { /* This person's height is not in the acceptable range */ } self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } Conforming to Requirements of Other Classes with Protocols Objective-C has the concept of a protocol. This is a concept found in many other lan‐ guages (always under a different term, it seems); for instance, it is called an interface in Java. A protocol, as its name implies, is a set of rules that classes can abide by in order to be used in certain ways. A class that follows the rules is said to conform to the protocol. Protocols are different from actual classes in that they do not have an implementation. They are just rules. For instance, every car has wheels, doors, and a main body color, among many other things. Let’s define these properties in a protocol named Car. Simply follow these steps to create a header file that can contain our Car protocol: 1. In Xcode, while your project is open, from the File menu, select New → File... 2. In the new dialog, on the lefthand side, make sure that you’ve selected Cocoa Touch undertheiOSmaincategory.Oncedone,ontherighthandsideofthedialog,choose “Objective-C protocol” and then press the Next button. 3. On the next screen, under the Protocol section, enter Car as the protocol’s name and then press the Next button. 4. You will now be asked to save your protocol on disk. Simply choose a location, usually in your project’s folder, and press the Create button. Xcode will now create a file for you named Car.h with content like this: #import <Foundation/Foundation.h> @protocol Car <NSObject> 12 | Chapter 1: Implementing Controllers and Views
  • 39. @end So let’s go ahead and define the properties for the Car protocol, as we discussed earlier in this section: #import <Foundation/Foundation.h> @protocol Car <NSObject> @property (nonatomic, copy) NSArray *wheels; @property (nonatomic, strong) UIColor *bodyColor; @property (nonatomic, copy) NSArray *doors; @end Now that our protocol has been defined, let’s create a class for a car, such as Jaguar, and then make that class conform to our protocol. Simply follow the steps provided in “Creating and Taking Advantage of Classes” on page 5 to create a class named Jaguar and then make it conform to the Car protocol like so: #import <Foundation/Foundation.h> #import "Car.h" @interface Jaguar : NSObject <Car> @end If you build your project now, you will notice that the compiler will give you a few warnings such as this: Auto property synthesis will not synthesize property declared in a protocol This is simply telling you that your Jaguar class is attempting to conform to the Car protocol but is not really implementing the required properties and/or methods in that protocol. So you should now know that a protocol can have required or optional items, and that you denote them by the @optional or the @required keywords. The default qualifier is @required, and since in our Car protocol we didn’t specify the qualifier explicitly, the compiler has chosen @required for us implicitly. Therefore, the Jaguar class now has to implement everything that is required from it by the Car protocol, like so: #import <Foundation/Foundation.h> #import "Car.h" @interface Jaguar : NSObject <Car> @property (nonatomic, copy) NSArray *wheels; @property (nonatomic, strong) UIColor *bodyColor; @property (nonatomic, copy) NSArray *doors; @end 1.0. Introduction | 13
  • 40. Perfect. Now you have an understanding of the basics of protocols and how they work and how you can define them. We will read more about them later in this book, so what you know right now about protocols is quite sufficient. Storing Items in and Retrieving Them from Collections Collections are instances of objects and can hold other objects. One of the primary collections is an array, which instantiates either NSArray or NSMutableArray. You can store any object in an array, and an array can contain more than one instance of the same object. Here is an example where we create an array of three strings: NSArray *stringsArray = @[ @"String 1", @"String 2", @"String 3" ]; __unused NSString *firstString = stringsArray[0]; __unused NSString *secondString = stringsArray[1]; __unused NSString *thirdString = stringsArray[2]; The __unused macro tells the compiler not to complain when a vari‐ able, such as the firstString variable in our example, is declared but never used. The default behavior of the compiler is that it throws a warning to the console saying a variable is not used. Our brief exam‐ ple has declared the variables but not used them, so adding the afore‐ mentioned macro to the beginning of the variable declaration keeps the compiler and ourselves happy. A mutable array is an array that can be mutated and changed after it has been created. An immutable array, like we saw, cannot be tampered with after it is created. Here is an example of an immutable array: NSString *string1 = @"String 1"; NSString *string2 = @"String 2"; NSString *string3 = @"String 3"; NSArray *immutableArray = @[string1, string2, string3]; NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:immutableArray]; [mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:1]; [mutableArray removeObjectAtIndex:1]; [mutableArray setObject:string1 atIndexedSubscript:0]; 14 | Chapter 1: Implementing Controllers and Views
  • 41. NSLog(@"Immutable array = %@", immutableArray); NSLog(@"Mutable Array = %@", mutableArray); The output of this program is as follows: Immutable array = ( "String 1", "String 2", "String 3" ) Mutable Array = ( "String 1", "String 3" ) Another very common collection found throughout iOS programs is a dictionary. Dic‐ tionaries are like arrays, but every object in a dictionary is assigned to a key so that later you can retrieve the same object using the key. Here is an example: NSDictionary *personInformation = @{ @"firstName" : @"Mark", @"lastName" : @"Tremonti", @"age" : @30, @"sex" : @"Male" }; NSString *firstName = personInformation[@"firstName"]; NSString *lastName = personInformation[@"lastName"]; NSNumber *age = personInformation[@"age"]; NSString *sex = personInformation[@"sex"]; NSLog(@"Full name = %@ %@", firstName, lastName); NSLog(@"Age = %@, Sex = %@", age, sex); The output of this program is: Full name = Mark Tremonti Age = 30, Sex = Male You can also have mutable dictionaries, just as you can have mutable arrays. Mutable dictionaries’ contents can be changed after they are instantiated. Here is an example: NSDictionary *personInformation = @{ @"firstName" : @"Mark", @"lastName" : @"Tremonti", @"age" : @30, @"sex" : @"Male" }; NSMutableDictionary *mutablePersonInformation = [[NSMutableDictionary alloc] initWithDictionary:personInformation]; 1.0. Introduction | 15
  • 42. mutablePersonInformation[@"age"] = @32; NSLog(@"Information = %@", mutablePersonInformation); The output of this program is: Information = { age = 32; firstName = Mark; lastName = Tremonti; sex = Male; } You can also take advantage of sets. Sets are like arrays but must contain a unique set of objects. You cannot add the same instance of an object twice to the same set. Here is an example: NSSet *shoppingList = [[NSSet alloc] initWithObjects: @"Milk", @"Bananas", @"Bread", @"Milk", nil]; NSLog(@"Shopping list = %@", shoppingList); If you run this program, the output will be: Shopping list = {( Milk, Bananas, Bread )} Note how Milk was mentioned twice in our program but added to the set only once. That’s the magic behind sets. You can also use mutable sets like so: NSSet *shoppingList = [[NSSet alloc] initWithObjects: @"Milk", @"Bananas", @"Bread", @"Milk", nil]; NSMutableSet *mutableList = [NSMutableSet setWithSet:shoppingList]; [mutableList addObject:@"Yogurt"]; [mutableList removeObject:@"Bread"]; NSLog(@"Original list = %@", shoppingList); NSLog(@"Mutable list = %@", mutableList); And the output is: Original list = {( Milk, Bananas, 16 | Chapter 1: Implementing Controllers and Views
  • 43. Bread )} Mutable list = {( Milk, Bananas, Yogurt )} There are two other important classes that you need to know about, now that we are talking about sets and collections: NSOrderedSet An immutable set that keeps the order in which objects were added to it NSMutableOrderedSet The mutable version of the ordered set By default, sets do not keep the order in which objects were added to them. Take the following as an example: NSSet *setOfNumbers = [NSSet setWithArray:@[@3, @4, @1, @5, @10]]; NSLog(@"Set of numbers = %@", setOfNumbers); What gets printed to the screen after you run this program is: Set of numbers = {( 5, 10, 3, 4, 1 )} But that is not the order in which we created the set. If you want to keep the order intact, simply use the NSOrderedSet class instead: NSOrderedSet *setOfNumbers = [NSOrderedSet orderedSetWithArray :@[@3, @4, @1, @5, @10]]; NSLog(@"Ordered set of numbers = %@", setOfNumbers); And, of course, you can use the mutable version of an ordered set: NSMutableOrderedSet *setOfNumbers = [NSMutableOrderedSet orderedSetWithArray:@[@3, @4, @1, @5, @10]]; [setOfNumbers removeObject:@5]; [setOfNumbers addObject:@0]; [setOfNumbers exchangeObjectAtIndex:1 withObjectAtIndex:2]; NSLog(@"Set of numbers = %@", setOfNumbers); The results are shown here: 1.0. Introduction | 17
  • 44. Set of numbers = {( 3, 1, 4, 10, 0 )} Before we move off the topic of sets, there is one other handy class that you may need to know about. The NSCountedSet class can hold a unique instance of an object multiple times. However, the way this is done is different from the way arrays perform the same task. In an array, the same object can appear multiple times. But in a counted set, the object will appear only once, but the set keeps a count of how many times the object was added to the set and will decrement that counter each time you remove an instance of the object. Here is an example: NSCountedSet *setOfNumbers = [NSCountedSet setWithObjects: @10, @20, @10, @10, @30, nil]; [setOfNumbers addObject:@20]; [setOfNumbers removeObject:@10]; NSLog(@"Count for object @10 = %lu", (unsigned long)[setOfNumbers countForObject:@10]); NSLog(@"Count for object @20 = %lu", (unsigned long)[setOfNumbers countForObject:@20]); The output is: Count for object @10 = 2 Count for object @20 = 2 The NSCountedSet class is mutable, despite what its name may lead you to think. Adding Object Subscripting Support to Your Classes Traditionally, when accessing objects in collections such as arrays and dictionaries, programmers had to access a method on the array or the dictionary to get or set that object. For instance, this is the traditional way of creating a mutable dictionary, adding two keys and values to it, and retrieving those values back: NSString *const kFirstNameKey = @"firstName"; NSString *const kLastNameKey = @"lastName"; NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; 18 | Chapter 1: Implementing Controllers and Views
  • 45. [dictionary setValue:@"Tim" forKey:kFirstNameKey]; [dictionary setValue:@"Cook" forKey:kLastNameKey]; __unused NSString *firstName = [dictionary valueForKey:kFirstNameKey]; __unused NSString *lastName = [dictionary valueForKey:kLastNameKey]; But with all the advances in the LLVM compiler, this code can now be shortened to this: NSString *const kFirstNameKey = @"firstName"; NSString *const kLastNameKey = @"lastName"; NSDictionary *dictionary = @{ kFirstNameKey : @"Tim", kLastNameKey : @"Cook", }; __unused NSString *firstName = dictionary[kFirstNameKey]; __unused NSString *lastName = dictionary[kLastNameKey]; Youcanseethatweareinitializingthedictionarybyprovidingthekeysincurlybrackets. The same thing for arrays. Here is how we used to create and use arrays traditionally: NSArray *array = [[NSArray alloc] initWithObjects:@"Tim", @"Cook", nil]; __unused NSString *firstItem = [array objectAtIndex:0]; __unused NSString *secondObject = [array objectAtIndex:1]; And now with object subscripting, we can shorten this code, as follows: NSArray *array = @[@"Tim", @"Cook"]; __unused NSString *firstItem = array[0]; __unused NSString *secondObject = array[0]; LLVM didn’t even stop there. You can add subscripting to your own classes as well. There are two types of subscripting: Subscripting by key Withthis,youcansetthevalueforaspecifickeyinsideanobject,justlikeyouwould in a dictionary. You can also access/read-from values inside the object by providing the key. Subscripting by index As with arrays, you can set/get values inside the object by providing an index to thatobject.Thismakessenseforarray-likeclasseswheretheelementslieinanatural order that can be represented by an index. For the first example, we are going to look at subscripting by key. To do this, we are going to create a class named Person with a firstName and a lastName. Then we are going to allow the programmer to change the first and last names by simply providing the keys to those properties. The reason you may want to add subscripting by key to a class like this is if your property names are volatile and you want to allow the programmer to set the value of those 1.0. Introduction | 19
  • 46. properties without having to worry about whether the names of those properties will change later; otherwise, the programmer is better off using the properties directly. The other reason for implementing subscripting by key is if you want to hide the exact implementation/declaration of your properties from the programmer and not let her access them directly. In order to support subscripting by key on your own classes, you must implement the following two methods on your class and put the method signatures in your class’s header file; otherwise, the compiler won’t know that your class supports subscripting by key. #import <Foundation/Foundation.h> /* We will use these as the keys to our firstName and lastName properties so that if our firstName and lastName properties' names change in the future in the implementation, we won't break anything and our class will still work, as we can simply change the value of these constants inside our implementation file */ extern NSString *const kFirstNameKey; extern NSString *const kLastNameKey; @interface Person : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; - (id) objectForKeyedSubscript:(id<NSCopying>)paramKey; - (void) setObject:(id)paramObject forKeyedSubscript:(id<NSCopying>)paramKey; @end The objectForKeyedSubscript: method will be called on your class whenever the programmer provides a key and wants to read the value of that key in your class. The parameterthatwillbegiventoyouwillobviouslybethekeyfromwhichtheprogrammer wants to read the value. To complement this method, the setObject:forKeyedSub script: method will be called on your class whenever the programmer wants to set the value for a specified key. So in our implementation, we want to check whether the given keys are the first name and the last name keys, and if yes, we will set/get the values of the first name and last name in our class: #import "Person.h" NSString *const kFirstNameKey = @"firstName"; NSString *const kLastNameKey = @"lastName"; @implementation Person - (id) objectForKeyedSubscript:(id<NSCopying>)paramKey{ NSObject<NSCopying> *keyAsObject = (NSObject<NSCopying> *)paramKey; 20 | Chapter 1: Implementing Controllers and Views
  • 47. if ([keyAsObject isKindOfClass:[NSString class]]){ NSString *keyAsString = (NSString *)keyAsObject; if ([keyAsString isEqualToString:kFirstNameKey] || [keyAsString isEqualToString:kLastNameKey]){ return [self valueForKey:keyAsString]; } } return nil; } - (void) setObject:(id)paramObject forKeyedSubscript:(id<NSCopying>)paramKey{ NSObject<NSCopying> *keyAsObject = (NSObject<NSCopying> *)paramKey; if ([keyAsObject isKindOfClass:[NSString class]]){ NSString *keyAsString = (NSString *)keyAsObject; if ([keyAsString isEqualToString:kFirstNameKey] || [keyAsString isEqualToString:kLastNameKey]){ [self setValue:paramObject forKey:keyAsString]; } } } @end So in this code, in the objectForKeyedSubscript: method, we are given a key, and we are expected to return the object that is associated in our instance with that key. The key that is given to us is an object that conforms to the NSCopying protocol. In other words, it’s an object that we can make a copy of, if we want to. We expect the key to be a string so that we can compare it with the predefined keys that we have declared on top of our class, and if it matches, we will set the value of that property in our class. We will then use the NSObject method named valueForKey: to return the value associated with the given key. But obviously, before we do so, we ensure that the given key is one of the keys that we expect. In the setObject:forKeyedSubscript: method we do the exact opposite. We set the values for a given key instead of returning them. Now, elsewhere in your app, you can instantiate an object of type Person and use the predefined keys of kFirstNameKey and kLastNameKey to change the value of the first Name and lastName properties like so: Person *person = [Person new]; person[kFirstNameKey] = @"Tim"; person[kLastNameKey] = @"Cook"; __unused NSString *firstName = person[kFirstNameKey]; __unused NSString *lastName = person[kLastNameKey]; This code will achieve exactly the same effect as the more direct approach of setting the properties of a class: Person *person = [Person new]; person.firstName = @"Tim"; person.lastName = @"Cook"; 1.0. Introduction | 21
  • 48. __unused NSString *firstName = person.firstName; __unused NSString *lastName = person.lastName; You can also support subscripting by index, the same way arrays do. This is useful, as mentioned before, to allow programmers to access objects that have a natural order inside a class. But there are not many data structures besides arrays where it makes sense to order and number elements, unlike subscripting by key, which applies to a wide range of data structures. So the example I’ll use to illustrate subscripting by index is a bit contrived. In our previous example, we had the Person class with a first and last name. Now if you want to allow programmers to be able to read the first name by providing the index of 0 and the last name by providing the index of 1, all you have to do is declare the objectAtIndexedSubscript: and the setObject:atIndexedSubscript: methods in the header file of your class, and then write the implementation. Here is how we declare these methods in our Person class’s header file: - (id) objectAtIndexedSubscript:(NSUInteger)paramIndex; - (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex; The implementation is also quite simple. We take the index and act upon it in a way that makes sense to our class. We decided that the first name has to have the index of 0 and the last name the index of 1. So if we get the index of 0 for setting a value, we set the value of the first name to the incoming object, and so on: - (id) objectAtIndexedSubscript:(NSUInteger)paramIndex{ switch (paramIndex){ case 0:{ return self.firstName; break; } case 1:{ return self.lastName; break; } default:{ [NSException raise:@"Invalid index" format:nil]; } } return nil; } - (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex{ switch (paramIndex){ case 0:{ self.firstName = paramObject; break; } case 1:{ self.lastName = paramObject; 22 | Chapter 1: Implementing Controllers and Views
  • 49. break; } default:{ [NSException raise:@"Invalid index" format:nil]; } } } Now we can test out what we’ve written so far, like so: Person *person = [Person new]; person[kFirstNameKey] = @"Tim"; person[kLastNameKey] = @"Cook"; NSString *firstNameByKey = person[kFirstNameKey]; NSString *lastNameByKey = person[kLastNameKey]; NSString *firstNameByIndex = person[0]; NSString *lastNameByIndex = person[1]; if ([firstNameByKey isEqualToString:firstNameByIndex] && [lastNameByKey isEqualToString:lastNameByIndex]){ NSLog(@"Success"); } else { NSLog(@"Something is not right"); } If you’ve followed all the steps in this recipe, you should see the value Success printed to the console now. 1.1. Displaying Alerts with UIAlertView Problem You want to display a message to your users in the form of an alert. This could be used to ask them to confirm an action, to ask for their username and password, or simply to let them enter some simple text that you can use in your app. Solution Utilize the UIAlertView class. Discussion If you are an iOS user, you have most certainly already seen an alert view. Figure 1-1 depicts an example. 1.1. Displaying Alerts with UIAlertView | 23
  • 50. Figure 1-1. Example of an alert view in iOS The best way to initialize an alert view is to use its designated initializer: - (void) viewDidAppear:(BOOL)paramAnimated{ [super viewDidAppear:paramAnimated]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"You've been delivered an alert" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil]; [alertView show]; } 24 | Chapter 1: Implementing Controllers and Views
  • 51. Whenthisalertviewisdisplayedtotheuser,shewillseesomethingsimilartothatshown in Figure 1-2. Figure 1-2. A simple alert view displayed to the user In order to display an alert view to the user, we use the alert view’s show method. Let’s have a look at the description for each of the parameters that we passed to the initializer of the alert view: title The string that the alert view will display on the top when it is shown to the user. This string is Title in Figure 1-2. message The actual message that gets displayed to the user. In Figure 1-2, this message is set to Message. 1.1. Displaying Alerts with UIAlertView | 25
  • 52. delegate The optional delegate object that we pass to the alert view. This object will get notified whenever the alert’s state changes; for instance, when the user taps on a button on the alert view. The object passed to this parameter must conform to the UIAlertViewDelegate protocol. cancelButtonTitle A string that will get assigned to the cancel button on an alert view. An alert view that has a cancel button usually asks the user for an action. If the user isn’t com‐ fortable with performing that action, he will press the cancel button. This button’s title does not necessarily have to say Cancel. It is up to you to specify a title for this button. This parameter is optional; you could put up a dialog box with no cancel button. otherButtonTitles Titles of any other buttons that you want to have appear on the alert view. Separate the titles with commas and make sure you terminate the list of titles with a nil, which is called a sentinel. This parameter is optional. It is possible to create an alert view without any buttons. But the view cannot be dismissed by the user. If you create such a view, you, as the programmer, need to make sure this alert view will get dismissed au‐ tomatically; for instance, three seconds after it is displayed. An alert view without any buttons that does not dismiss itself automatically gives a really poor user experience. Not only will your app get low ratings on the App Store for blocking the UI from user access, but chances are that your app will get rejected by Apple. Alert views can take various styles. The UIAlertView class has a property called alert ViewStyle of type UIAlertViewStyle: typedef NS_ENUM(NSInteger, UIAlertViewStyle) { UIAlertViewStyleDefault = 0, UIAlertViewStyleSecureTextInput, UIAlertViewStylePlainTextInput, UIAlertViewStyleLoginAndPasswordInput }; Here is what each of these styles will do: UIAlertViewStyleDefault This is the default style of an alert view, as we saw in Figure 1-2. UIAlertViewStyleSecureTextInput With this style, the alert view will contain a secure text field, which hides the actual characters typed by the user. For instance, if you are asking the user for her online banking credentials, you might choose this style of alert view. 26 | Chapter 1: Implementing Controllers and Views
  • 53. UIAlertViewStylePlainTextInput Under this style, the alert view will display a nonsecure text field to the user. This style is great if you simply want to ask the user for a plain-text entry, such as her phone number. UIAlertViewStyleLoginAndPasswordInput With this style, the alert view will display two text fields: a nonsecure one for a username and a secure one for a password. If you need to get notified when the user interacts with the alert view, specify a delegate object to your alert view. This delegate must conform to the UIAlertViewDelegate protocol. The most important method defined in this protocol is the alertView:click edButtonAtIndex:method,whichiscalledassoonastheusertapsononeofthebuttons in the alert view. The button index is passed to you through the clickedButtonAtIn dex parameter. As an example, let’s display an alert view to the user and ask whether she would like to visit a website in Safari after having pressed a link to that website available in our UI. We will display two buttons on our alert view: Yes and No. In our alert view delegate, we will detect which button she tapped on and will take action accordingly. Let’s first implement two very simple methods that return the title of our two buttons: - (NSString *) yesButtonTitle{ return @"Yes"; } - (NSString *) noButtonTitle{ return @"No"; } Now we need to make sure that we are conforming to the UIAlertViewDelegate pro‐ tocol in our view controller: #import "ViewController.h" @interface ViewController () <UIAlertViewDelegate> @end @implementation ViewController ... The next step is to create and display our alert view to the user: - (void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; self.view.backgroundColor = [UIColor whiteColor]; 1.1. Displaying Alerts with UIAlertView | 27
  • 54. NSString *message = @"Are you sure you want to open this link in Safari?"; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Open Link" message:message delegate:self cancelButtonTitle:[self noButtonTitle] otherButtonTitles:[self yesButtonTitle], nil]; [alertView show]; } So now, our alert view will look similar to that shown in Figure 1-3. Figure 1-3. An alert view with Yes and No buttons Now we need a way to know whether the user selected the Yes or the No option in our alert view. For this, we will need to implement the alertView:clickedButtonAtIn dex: method of our alert view delegate: - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 28 | Chapter 1: Implementing Controllers and Views
  • 55. Another Random Document on Scribd Without Any Related Topics
  • 56. struggle for existence, the blind controller, instead of the provident God, that effects the changes of organic forms by a mutual action of the laws of heredity and adaptation. And there is no more trace of “design” in the embryology of the individual plant, animal, or man. This ontogeny is but a brief epitome of phylogeny, an abbreviated and condensed recapitulation of it, determined by the physiological laws of heredity. Baer ended the preface to his classical Evolution of Animals (1828) with these words: “The palm will be awarded to the fortunate scientist who succeeds in reducing the constructive forces of the animal body to the general forces or life-processes of the entire world. The tree has not yet been planted which is to make his cradle.” The great embryologist erred once more. That very year, 1828, witnessed the arrival of Charles Darwin at Cambridge University (for the purpose of studying theology!)—the “fortunate scientist” who richly earned the palm thirty years afterwards by his theory of selection. In the philosophy of history—that is, in the general reflections which historians make on the destinies of nations and the complicated course of political evolution—there still prevails the notion of a “moral order of the universe.” Historians seek in the vivid drama of history a leading design, an ideal purpose, which has ordained one or other race or state to a special triumph, and to dominion over the others. This teleological view of history has recently become more strongly contrasted with our monistic view in proportion as monism has proved to be the only possible interpretation of inorganic nature. Throughout the whole of astronomy, geology, physics, and chemistry there is no question to-day of a “moral order,” or a personal God, whose “hand hath disposed all things in wisdom and understanding.” And the same must be said of the entire field of biology, the whole constitution and history of organic nature, if we set aside the question of man for the moment. Darwin has not only proved by his theory of selection that the orderly processes in the life and structure of animals and plants have arisen by mechanical laws
  • 57. without any preconceived design, but he has shown us in the “struggle for life” the powerful natural force which has exerted supreme control over the entire course of organic evolution for millions of years. It may be said that the struggle for life is the “survival of the fittest” or the “victory of the best”; that is only correct when we regard the strongest as the best (in a moral sense). Moreover, the whole history of the organic world goes to prove that, besides the predominant advance towards perfection, there are at all times cases of retrogression to lower stages. Even Baer’s notion of “design” has no moral feature whatever. Do we find a different state of things in the history of peoples, which man, in his anthropocentric presumption, loves to call “the history of the world”? Do we find in every phase of it a lofty moral principle or a wise ruler, guiding the destinies of nations? There can be but one answer in the present advanced stage of natural and human history: No. The fate of those branches of the human family, those nations and races which have struggled for existence and progress for thousands of years, is determined by the same “eternal laws of iron” as the history of the whole organic world which has peopled the earth for millions of years. Geologists distinguish three great epochs in the organic history of the earth, as far as we can read it in the monuments of the science of fossils—the primary, secondary, and tertiary epochs. According to a recent calculation, the first occupied at least thirty-four million, the second eleven million, and the third three million years. The history of the family of vertebrates, from which our own race has sprung, unfolds clearly before our eyes during this long period. Three different stages in the evolution of the vertebrate correspond to the three epochs; the fishes characterized the primary (palæozoic) age, the reptiles the secondary (mesozoic), and the mammals the tertiary (cænozoic). Of the three groups the fishes rank lowest in organization, the reptiles come next, and the mammals take the highest place. We find, on nearer examination of the history of the three classes, that their various orders and families also advanced
  • 58. progressively during the three epochs towards a higher stage of perfection. May we consider this progressive development as the outcome of a conscious design or a moral order of the universe? Certainly not. The theory of selection teaches us that this organic progress, like the earlier organic differentiation, is an inevitable consequence of the struggle for existence. Thousands of beautiful and remarkable species of animals and plants have perished during those forty-eight million years, to give place to stronger competitors, and the victors in this struggle for life were not always the noblest or most perfect forms in a moral sense. It has been just the same with the history of humanity. The splendid civilization of classical antiquity perished because Christianity, with its faith in a loving God and its hope of a better life beyond the grave, gave a fresh, strong impetus to the soaring human mind. The Papal Church quickly degenerated into a pitiful caricature of real Christianity, and ruthlessly scattered the treasures of knowledge which the Hellenic philosophy had gathered; it gained the dominion of the world through the ignorance of the credulous masses. In time the Reformation broke the chains of this mental slavery, and assisted reason to secure its right once more. But in the new, as in the older, period the great struggle for existence went on in its eternal fluctuation, with no trace of a moral order. And it is just as impossible for the impartial and critical observer to detect a “wise providence” in the fate of individual human beings as a moral order in the history of peoples. Both are determined with iron necessity by a mechanical causality which connects every single phenomenon with one or more antecedent causes. Even the ancient Greeks recognized ananke, the blind heimarmene, the fate “that rules gods and men,” as the supreme principle of the universe. Christianity replaced it by a conscious Providence, which is not blind, but sees, and which governs the world in patriarchal fashion. The anthropomorphic character of this notion, generally closely connected with belief in a personal God, is quite obvious. Belief in a “loving Father,” who unceasingly guides the destinies of one billion
  • 59. five hundred million men on our planet, and is attentive at all times to their millions of contradictory prayers and pious wishes, is absolutely impossible; that is at once perceived on laying aside the colored spectacles of “faith” and reflecting rationally on the subject. As a rule, this belief in Providence and the tutelage of a “loving Father” is more intense in the modern civilized man—just as in the uncultured savage—when some good fortune has fallen him: an escape from peril of life, recovery from a severe illness, the winning of the first prize in a lottery, the birth of a long-delayed child, and so forth. When, on the other hand, a misfortune is met with, or an ardent wish is not fulfilled, “Providence” is forgotten. The wise ruler of the world slumbered—or refused his blessing. In the extraordinary development of commerce of the nineteenth century the number of catastrophes and accidents has necessarily increased beyond all imagination; of that the journal is a daily witness. Thousands are killed every year by shipwreck, railway accidents, mine accidents, etc. Thousands slay each other every year in war, and the preparation for this wholesale massacre absorbs much the greater part of the revenue in the highest civilized nations, the chief professors of “Christian charity.” And among these hundreds of thousands of annual victims of modern civilization strong, industrious, courageous workers predominate. Yet the talk of a “moral order” goes on. Since impartial study of the evolution of the world teaches us that there is no definite aim and no special purpose to be traced in it, there seems to be no alternative but to leave everything to “blind chance.” This reproach has been made to the transformism of Lamarck and Darwin, as it had been to the previous systems of Kant and Laplace; there are a number of dualist philosophers who lay great stress on it. It is, therefore, worth while to make a brief remark upon it. One group of philosophers affirms, in accordance with its teleological conception, that the whole cosmos is an orderly system, in which
  • 60. every phenomenon has its aim and purpose; there is no such thing as chance. The other group, holding a mechanical theory, expresses itself thus: The development of the universe is a monistic mechanical process, in which we discover no aim or purpose whatever; what we call design in the organic world is a special result of biological agencies; neither in the evolution of the heavenly bodies nor in that of the crust of our earth do we find any trace of a controlling purpose—all is the result of chance. Each party is right—according to its definition of chance. The general law of causality, taken in conjunction with the law of substance, teaches us that every phenomenon has a mechanical cause; in this sense there is no such thing as chance. Yet it is not only lawful, but necessary, to retain the term for the purpose of expressing the simultaneous occurrence of two phenomena, which are not causally related to each other, but of which each has its own mechanical cause, independent of that of the other. Everybody knows that chance, in its monistic sense, plays an important part in the life of man and in the universe at large. That, however, does not prevent us from recognizing in each “chance” event, as we do in the evolution of the entire cosmos, the universal sovereignty of nature’s supreme law, the law of substance.
  • 61. CHAPTER XV GOD AND THE WORLD The Idea of God in General—Antithesis of God and the World; the Supernatural and Nature—Theism and Pantheism—Chief Forms of Theism—Polytheism—Triplotheism—Amphitheism— Monotheism—Religious Statistics—Naturalistic Monotheism— Solarism—Anthropistic Monotheism—The Three Great Mediterranean Religions—Mosaism—Christianity—The Cult of the Madonna and the Saints—Papal Polytheism—Islam—Mixotheism —Nature of Theism—An Extra-mundane and Anthropomorphic God; a Gaseous Vertebrate—Pantheism—Intramundane God (Nature)—The Hylozoism of the Ionic Monists (Anaximander)— Conflict of Pantheism and Christianity—Spinoza—Modern Monism—Atheism For thousands of years humanity has placed the last and supreme basis of all phenomena in an efficient cause, to which it gives the title of God (deus, theos). Like all general ideas, this notion of God has undergone a series of remarkable modifications and transformations in the course of the evolution of reason. Indeed, it may be said that no other idea has had so many metamorphoses; for no other belief affects in so high a degree the chief objects of the mind and of rational science, as well as the deepest interests of the emotion and poetic fancy of the believer. A comparative criticism of the many different forms of the idea of God would be extremely interesting and instructive; but we have not space for it in the present work. We must be content with a passing glance at the most important forms of the belief and their relation to the modern thought that has been evoked by a sound study of
  • 62. nature. For further information on this interesting question the reader would do well to consult the distinguished work of Adalbert Svoboda, Forms of Faith (1897). When we pass over the finer shades and the variegated clothing of the God-idea and confine our attention to its chief element, we can distribute all the different presentations of it in two groups—the theistic and pantheistic group. The latter is closely connected with the monistic, or rational, view of things, and the former is associated with dualism and mysticism. I.—THEISM In this view God is distinct from, and opposed to, the world as its creator, sustainer, and ruler. He is always conceived in a more or less human form, as an organism which thinks and acts like a man—only on a much higher scale. This anthropomorphic God, polyphyletically evolved by the different races, assumes an infinity of shapes in their imagination, from fetichism to the refined monotheistic religions of the present day. The chief forms of theism are polytheism, triplotheism, amphitheism, and monotheism. The polytheist peoples the world with a variety of gods and goddesses, which enter into its machinery more or less independently. Fetichism sees such subordinate deities in the lifeless body of nature, in rocks, in water, in the air, in human productions of every kind (pictures, statues, etc.). Demonism sees gods in living organisms of every species—trees, animals, and men. This kind of polytheism is found in innumerable forms even in the lowest tribes. It reaches the highest stage in Hellenic polytheism, in the myths of ancient Greece, which still furnish the finest images to the modern poet and artist. At a much lower stage we have Catholic polytheism, in which innumerable “saints” (many of them of very equivocal repute) are venerated as subordinate divinities, and prayed to to exert their mediation with the supreme divinity.
  • 63. The dogma of the “Trinity,” which still comprises three of the chief articles of faith in the creed of Christian peoples, culminates in the notion that the one God of Christianity is really made up of three different persons: (1) God the Father, the omnipotent creator of heaven and earth (this untenable myth was refuted long ago by scientific cosmogony, astronomy, and geology); (2) Jesus Christ; and (3) the Holy Ghost, a mystical being, over whose incomprehensible relation to the Father and the Son millions of Christian theologians have racked their brains in vain for the last nineteen hundred years. The Gospels, which are the only clear sources of this triplotheism, are very obscure as to the relation of these three persons to each other, and do not give a satisfactory answer to the question of their unity. On the other hand, it must be carefully noted what confusion this obscure and mystic dogma of the Trinity must necessarily cause in the minds of our children even in the earlier years of instruction. One morning they learn (in their religious instruction) that three times one are one, and the very next hour they are told in their arithmetic class that three times one are three. I remember well the reflection that this confusion led me to in my early school-days. For the rest, the “Trinity” is not an original element in Christianity; like most of the other Christian dogmas, it has been borrowed from earlier religions. Out of the sun-worship of the Chaldean magi was evolved the Trinity of Ilu, the mysterious source of the world; its three manifestations were Anu, primeval chaos; Bel, the architect of the world; and Aa, the heavenly light, the all-enlightening wisdom. In the Brahmanic religion the Trimurti is also conceived as a “divine unity” made up of three persons—Brahma (the creator), Vishnu (the sustainer), and Shiva (the destroyer). It would seem that in this and other ideas of a Trinity the “sacred number, three,” as such—as a “symbolical number”—has counted for something. The three first Christian virtues—Faith, Hope, and Charity—form a similar triad. According to the amphitheists, the world is ruled by two different gods, a good and an evil principle, God and the Devil. They are engaged in a perpetual struggle, like rival emperors, or pope and
  • 64. anti-pope. The condition of the world is the result of this conflict. The loving God, or good principle, is the source of all that is good and beautiful, of joy and of peace. The world would be perfect if His work were not continually thwarted by the evil principle, the Devil; this being is the cause of all that is bad and hateful, of contradiction and of pain. Amphitheism is undoubtedly the most rational of all forms of belief in God, and the one which is least incompatible with a scientific view of the world. Hence we find it elaborated in many ancient peoples thousands of years before Christ. In ancient India Vishnu, the preserver, struggles with Shiva, the destroyer. In ancient Egypt the good Osiris is opposed by the wicked Typhon. The early Hebrews had a similar dualism of Aschera (or Keturah), the fertile mother- earth, and Elion (Moloch or Sethos), the stern heavenly father. In the Zend religion of the ancient Persians, founded by Zoroaster two thousand years before Christ, there is a perpetual struggle between Ormuzd, the good god of light, and Ahriman, the wicked god of darkness. In Christian mythology the Devil is scarcely less conspicuous as the adversary of the good deity, the tempter and seducer, the prince of hell, and lord of darkness. A personal devil was still an important element in the belief of most Christians at the beginning of the nineteenth century. Towards the middle of the century he was gradually eliminated by being progressively explained away, or he was restricted to the subordinate rôle he plays as Mephistopheles in Goethe’s great drama. To-day the majority of educated people look upon “belief in a personal devil” as a mediæval superstition, while “belief in God” (that is, the personal, good, and loving God) is retained as an indispensable element of religion. Yet the one belief is just as much (or as little) justified as the other. In any case, the much-lamented “imperfection of our earthly life,” the “struggle for existence,” and all that pertains to it, are explained much more simply and naturally by this struggle of a good and an evil god than by any other form of theism.
  • 65. The dogma of the unity of God may in some respects be regarded as the simplest and most natural type of theism; it is popularly supposed to be the most widely accepted element of religion, and to predominate in the ecclesiastical systems of civilized countries. In reality, that is not the case, because this alleged “monotheism” usually turns out on closer inquiry to be one of the other forms of theism we have examined, a number of subordinate deities being generally introduced besides the supreme one. Most of the religions which took a purely monotheistic stand-point have become more or less polytheistic in the course of time. Modern statistics assure us that of the one billion five hundred million men who people the earth the great majority are monotheists; of these, nominally, about six hundred millions are Brahma-Buddhists, five hundred millions are called Christians, two hundred millions are heathens (of various types), one hundred and eighty millions are Mohammedans, ten millions are Jews, and ten millions have no religion at all. However, the vast majority of these nominal monotheists have very confused ideas about the deity, or believe in a number of gods and goddesses besides the chief god—angels, devils, etc. The different forms which monotheism has assumed in the course of its polyphyletic development may be distributed in two groups— those of naturalistic and anthropistic monotheism. Naturalistic monotheism finds the embodiment of the deity in some lofty and dominating natural phenomenon. The sun, the deity of light and warmth, on whose influence all organic life insensibly and directly depends, was taken to be such a phenomenon many thousand years ago. Sun-worship (solarism, or heliotheism) seems to the modern scientist to be the best of all forms of theism, and the one which may be most easily reconciled with modern monism. For modern astrophysics and geogeny have taught us that the earth is a fragment detached from the sun, and that it will eventually return to the bosom of its parent. Modern physiology teaches us that the first source of organic life on the earth is the formation of protoplasm, and that this synthesis of simple inorganic substances, water, carbonic acid, and ammonia, only takes place under the influence of
  • 66. sunlight. On the primary evolution of the plasmodomous plants followed, secondarily, that of the plasmophagous animals, which directly or indirectly depend on them for nourishment; and the origin of the human race itself is only a later stage in the development of the animal kingdom. Indeed, the whole of our bodily and mental life depends, in the last resort, like all other organic life, on the light and heat rays of the sun. Hence in the light of pure reason, sun-worship, as a form of naturalistic monotheism, seems to have a much better foundation than the anthropistic worship of Christians and of other monotheists who conceive their god in human form. As a matter of fact, the sun-worshippers attained, thousands of years ago, a higher intellectual and moral standard than most of the other theists. When I was in Bombay, in 1881, I watched with the greatest sympathy the elevating rites of the pious Parsees, who, standing on the sea-shore, or kneeling on their prayer-rugs, offered their devotion to the sun at its rise and setting.[31] Moon-worship (lunarism and selenotheism) is of much less importance than sun-worship. There are a few uncivilized races that have adored the moon as their only deity, but it has generally been associated with a worship of the stars and the sun. The humanization of God, or the idea that the “Supreme Being” feels, thinks, and acts like man (though in a higher degree), has played a most important part, as anthropomorphic monotheism, in the history of civilization. The most prominent in this respect are the three great religions of the Mediterranean peoples—the old Mosaic religion, the intermediate Christian religion, and the younger Mohammedanism. These three great Mediterranean religions, all three arising on the east coast of the most interesting of all seas, and originating in an imaginative enthusiast of the Semitic race, are intimately connected, not only by this external circumstance of an analogous origin, but by many common features of their internal contents. Just as Christianity borrowed a good deal of its mythology directly from ancient Judaism, so Islam has inherited much from both its predecessors. All the three were originally monotheistic; all
  • 67. three were subsequently overlaid with a great variety of polytheistic features, in proportion as they extended, first along the coast of the Mediterranean with its heterogeneous population, and eventually into every part of the world. The Hebrew monotheism, as it was founded by Moses (about 1600 B.C.), is usually regarded as the ancient faith which has been of the greatest importance in the ethical and religious development of humanity. This high historical appreciation is certainly valid in the sense that the two other world-conquering Mediterranean religions issued from it; Christ was just as truly a pupil of Moses as Mohammed was afterwards of Christ. So also the New Testament, which has become the foundation of the belief of the highest civilized nations in the short space of nineteen hundred years, rests on the venerable basis of the Old Testament. The Bible, which the two compose, has had a greater influence and a wider circulation than any other book in the world. Even to-day the Bible—in spite of its curious mingling of the best and the worst elements—is in a certain sense the “book of books.” Yet when we make an impartial and unprejudiced study of this notable historical source, we find it very different in several important respects from the popular impression. Here again modern criticism and history have come to certain conclusions which destroy the prevalent tradition in its very foundations. The monotheism which Moses endeavored to establish in the worship of Jehovah, and which the prophets—the philosophers of the Hebrew race—afterwards developed with great success, had at first to sustain a long and severe struggle with the dominant polytheism which was in possession. Jehovah, or Yahveh, was originally derived from the heaven-god, which, under the title of Moloch or Baal, was one of the most popular of the Oriental deities (the Sethos or Typhon of the Egyptians, and the Saturn or Cronos of the Greeks). There were, however, other gods in great favor with the Jewish people, and so the struggle with “idolatry” continued. Still, Jehovah was, in principle, the only God, explicitly claiming, in the
  • 68. first precept of the decalogue: “I am the Lord thy God; thou shalt have no other gods beside me.” Christian monotheism shared the fate of its mother, Mosaism; it was generally only monotheistic in theory, while it degenerated practically into every kind of polytheism. In point of fact, monotheism was logically abandoned in the very dogma of the Trinity, which was adopted as an indispensable foundation of the Christian religion. The three persons, which are distinguished as Father, Son, and Holy Ghost, are three distinct individuals (and, indeed, anthropomorphic persons), just as truly as the three Indian deities of the Trimurti (Brahma, Vishnu, and Shiva) or the Trinity of the ancient Hebrews (Anu, Bel, and Aa). Moreover, in the most widely distributed form of Christianity the “virgin” mother of Christ plays an important part as a fourth deity; in many Catholic countries she is practically taken to be much more powerful and influential than the three male persons of the celestial administration. The cult of the madonna has been developed to such an extent in these countries that we may oppose it to the usual masculine form of monotheism as one of a feminine type. The “Queen of Heaven” becomes so prominent, as is seen in so many pictures and legends of the madonna, that the three male persons practically disappear. In addition, the imagination of the pious Christian soon came to increase this celestial administration by a numerous company of “saints” of all kinds, and bands of musical angels, who should see that “eternal life” should not prove too dull. The popes—the greatest charlatans that any religion ever produced—have constantly studied to increase this band of celestial satellites by repeated canonizations. This curious company received its most interesting acquisition in 1870, when the Vatican Council pronounced the popes, as the vicars of Christ, to be infallible, and thus raised them to a divine dignity. When we add the “personal Devil” that they acknowledge, and the “bad angels” who form his court, we have in modern Catholicism, still the most extensive branch of Christianity, a rich and variegated polytheism that dwarfs the Olympic family of the Greeks.
  • 69. Islam, or the Mohammedan monotheism, is the youngest and purest form of monotheism. When the young Mohammed (born 570) learned to despise the polytheistic idolatry of his Arabian compatriots, and became acquainted with Nestorian Christianity, he adopted its chief doctrines in a general way; but he could not bring himself to see anything more than a prophet in Christ, like Moses. He found in the dogma of the Trinity what every emancipated thinker finds on impartial reflection—an absurd legend which is neither reconcilable with the first principles of reason nor of any value whatever for our religious advancement. He justly regarded the worship of the immaculate mother of God as a piece of pure idolatry, like the veneration of pictures and images. The longer he reflected on it, and the more he strove after a purified idea of deity, the clearer did the certitude of his great maxim appear: “God is the only God”—there are no other gods beside him. Yet Mohammed could not free himself from the anthropomorphism of the God-idea. His one only God was an idealized, almighty man, like the stern, vindictive God of Moses, and the gentle, loving God of Christ. Still, we must admit that the Mohammedan religion has preserved the character of pure monotheism throughout the course of its historical development and its inevitable division much more faithfully than the Mosaic and Christian religions. We see that to-day, even externally, in its forms of prayer and preaching, and in the architecture and adornment of its mosques. When I visited the East for the first time, in 1873, and admired the noble mosques of Cairo, Smyrna, Brussa, and Constantinople, I was inspired with a feeling of real devotion by the simple and tasteful decoration of the interior, and the lofty and beautiful architectural work of the exterior. How noble and inspiring do these mosques appear in comparison with the majority of Catholic churches, which are covered internally with gaudy pictures and gilt, and are outwardly disfigured by an immoderate crowd of human and animal figures! Not less elevated are the silent prayers and the simple devotional acts of the Koran when compared with the loud, unintelligible verbosity of the Catholic Mass and the blatant music of their theatrical processions.
  • 70. Under the title of mixotheism we may embrace all the forms of theistic belief which contain mixtures of religious notions of different, sometimes contradictory, kinds. In theory this most widely diffused type of religion is not recognized at all; in the concrete it is the most important and most notable of all. The vast majority of men who have religious opinions have always been, and still are, mixotheists; their idea of God is picturesquely compounded from the impressions received in childhood from their own sect, and a number of other impressions which are received later on, from contact with members of other religions, and which modify the earlier notions. In educated people there is also sometimes the modifying influence of philosophic studies in maturer years, and especially the unprejudiced study of natural phenomena, which reveals the futility of the theistic idea. The conflict of these contradictory impressions, which is very painful to a sensitive soul, and which often remains undecided throughout life, clearly shows the immense power of the heredity of ancient myths on the one hand and the early adaptation to erroneous dogmas on the other. The particular faith in which the child has been brought up generally remains in power, unless a “conversion” takes place subsequently, owing to the stronger influence of some other religion. But even in this supersession of one faith by another the new name, like the old one, proves to be merely an outward label covering a mixture of the most diverse opinions and errors. The greater part of those who call themselves Christians are not monotheists (as they think), but amphitheists, triplotheists, or polytheists. And the same must be said of Islam and Mosaism, and other monotheistic religions. Everywhere we find associated with the original idea of a “sole and triune God” later beliefs in a number of subordinate deities—angels, devils, saints, etc.—a picturesque assortment of the most diverse theistic forms. All the above forms of theism, in the proper sense of the word— whether the belief assumes a naturalistic or an anthropistic form— represent God to be an extramundane or a supernatural being. He is always opposed to the world, or nature, as an independent being; generally as its creator, sustainer, and ruler. In most religions he has
  • 71. the additional character of personality, or, to put it more definitely still, God as a person is likened to man. “In his gods man paints himself.” This anthropomorphic conception of God as one who thinks, feels, and acts like man prevails with the great majority of theists, sometimes in a cruder and more naïve form, sometimes in a more refined and abstract degree. In any case the form of theosophy we have described is sure to affirm that God, the supreme being, is infinite in perfection, and therefore far removed from the imperfection of humanity. Yet, when we examine closely, we always find the same psychic or mental activity in the two. God feels, thinks, and acts as man does, although it be in an infinitely more perfect form. The personal anthropism of God has become so natural to the majority of believers that they experience no shock when they find God personified in human form in pictures and statues, and in the varied images of the poet, in which God takes human form—that is, is changed into a vertebrate. In some myths, even, God takes the form of other mammals (an ape, lion, bull, etc.), and more rarely of a bird (eagle, dove, or stork), or of some lower vertebrate (serpent, crocodile, dragon, etc.). In the higher and more abstract forms of religion this idea of bodily appearance is entirely abandoned, and God is adored as a “pure spirit” without a body. “God is a spirit, and they who worship him must worship him in spirit and in truth.” Nevertheless, the psychic activity of this “pure spirit” remains just the same as that of the anthropomorphic God. In reality, even this immaterial spirit is not conceived to be incorporeal, but merely invisible, gaseous. We thus arrive at the paradoxical conception of God as a gaseous vertebrate. II.—PANTHEISM Pantheism teaches that God and the world are one. The idea of God is identical with that of nature or substance. This pantheistic view is sharply opposed in principle to all the systems we have described,
  • 72. and to all possible forms of theism although there have been many attempts made from both sides to bridge over the deep chasm that separates the two. There is always this fundamental contradiction between them, that in theism God is opposed to nature as an extramundane being, as creating and sustaining the world, and acting upon it from without, while in pantheism God, as an intramundane being, is everywhere identical with nature itself, and is operative within the world as “force” or “energy.” The latter view alone is compatible with our supreme law—the law of substance. It follows necessarily that pantheism is the world-system of the modern scientist. There are, it is true, still a few men of science who contest this, and think it possible to reconcile the old theistic theory of human nature with the pantheistic truth of the law of substance. All these efforts rest on confusion or sophistry—when they are honest. As pantheism is a result of an advanced conception of nature in the civilized mind, it is naturally much younger than theism, the crudest forms of which are found in great variety in the uncivilized races of ten thousand years ago. We do, indeed, find the germs of pantheism in different religions at the very dawn of philosophy in the earliest civilized peoples (in India, Egypt, China, and Japan), several thousand years before the time of Christ; still, we do not meet a definite philosophical expression of it until the hylozoism of the Ionic philosophers, in the first half of the sixth century before Christ. All the great thinkers of this flourishing period of Hellenic thought are surpassed by the famous Anaximander, of Miletus, who conceived the essential unity of the infinite universe (apeiron) more profoundly and more clearly than his master, Thales, or his pupil, Anaximenes. Not only the great thought of the original unity of the cosmos and the development of all phenomena out of the all-pervading primitive matter found expression in Anaximander, but he even enunciated the bold idea of countless worlds in a periodic alternation of birth and death.
  • 73. Many other great philosophers of classical antiquity, especially Democritus, Heraclitus, and Empedocles, had, in the same or an analogous sense, a profound conception of this unity of nature and God, of body and spirit, which has obtained its highest expression in the law of substance of our modern monism. The famous Roman poet and philosopher, Lucretius Carus, has presented it in a highly poetic form in his poem “De Rerum Natura.” However, this true pantheistic monism was soon entirely displaced by the mystic dualism of Plato, and especially by the powerful influence which the idealistic philosophy obtained by its blending with Christian dogmas. When the papacy attained to its spiritual despotism over the world, pantheism was hopelessly crushed; Giordano Bruno, its most gifted defender, was burned alive by the “Vicar of Christ” in the Campo dei Fiori at Rome on February 17, 1600. It was not until the middle of the seventeenth century that pantheism was exhibited in its purest form by the great Baruch Spinoza; he gave for the totality of things a definition of substance in which God and the world are inseparably united. The clearness, confidence, and consistency of Spinoza’s monistic system are the more remarkable when we remember that this gifted thinker of two hundred and fifty years ago was without the support of all those sound empirical bases which have been obtained in the second half of the nineteenth century. We have already spoken, in the first chapter, of Spinoza’s relation to the materialism of the eighteenth and the monism of the nineteenth century. The propagation of his views, especially in Germany, is due, above all, to the immortal works of our greatest poet and thinker, Wolfgang Goethe. His splendid God and the World, Prometheus, Faust, etc., embody the great thoughts of pantheism in the most perfect poetic creations. Atheism affirms that there are no gods or goddesses, assuming that god means a personal, extramundane entity. This “godless world- system” substantially agrees with the monism or pantheism of the modern scientist; it is only another expression for it, emphasizing its negative aspect, the non-existence of any supernatural deity. In this
  • 74. sense Schopenhauer justly remarks: “Pantheism is only a polite form of atheism. The truth of pantheism lies in its destruction of the dualist antithesis of God and the world, in its recognition that the world exists in virtue of its own inherent forces. The maxim of the pantheist, ‘God and the world are one,’ is merely a polite way of giving the Lord God his congé.” During the whole of the Middle Ages, under the bloody despotism of the popes, atheism was persecuted with fire and sword as a most pernicious system. As the “godless” man is plainly identified with the “wicked” in the Gospel, and is threatened—simply on account of his “want of faith”—with the eternal fires of hell, it was very natural that every good Christian should be anxious to avoid the suspicion of atheism. Unfortunately, the idea still prevails very widely. The atheistic scientist who devotes his strength and his life to the search for the truth, is freely credited with all that is evil; the theistic church-goer, who thoughtlessly follows the empty ceremonies of Catholic worship, is at once assumed to be a good citizen, even if there be no meaning whatever in his faith and his morality be deplorable. This error will only be destroyed when, in the twentieth century, the prevalent superstition gives place to rational knowledge and to a monistic conception of the unity of God and the world.
  • 75. CHAPTER XVI KNOWLEDGE AND BELIEF The Knowledge of the Truth and Its Sources: the Activity of the Senses and the Association of Presentations—Organs of Sense and Organs of Thought—Sense-Organs and their Specific Energy—Their Evolution—The Philosophy of Sensibility— Inestimable Value of the Senses—Limits of Sensitive Knowledge —Hypothesis and Faith—Theory and Faith—Essential Difference of Scientific (Natural) and Religious (Supernatural) Faith— Superstition of Savage and of Civilized Races—Confessions of Faith—Unsectarian Schools—The Faith of Our Fathers—Spiritism —Revelation Every effort of genuine science makes for a knowledge of the truth. Our only real and valuable knowledge is a knowledge of nature itself, and consists of presentations which correspond to external things. We are incompetent, it is true, to penetrate into the innermost nature of this real world—the “thing in itself”—but impartial critical observation and comparison inform us that, in the normal action of the brain and the organs of sense, the impressions received by them from the outer world are the same in all rational men, and that in the normal function of the organs of thought certain presentations are formed which are everywhere the same. These presentations we call true, and we are convinced that their content corresponds to the knowable aspect of things. We know that these facts are not imaginary, but real. All knowledge of the truth depends on two different, but intimately connected, groups of human physiological functions: firstly, on the sense-impressions of the object by means of sense-action, and,
  • 76. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com