0% found this document useful (0 votes)
56 views77 pages

Objectivec The Ultimate Guide Sufyan Bin Uzayr Download

Objective-C: The Ultimate Guide by Sufyan Bin Uzayr is a comprehensive resource for learning the Objective-C programming language, covering both basic and advanced topics. The book emphasizes practical lessons and real-world applications, aiming to help developers write optimized and well-structured code. It includes detailed discussions on object-oriented programming, memory management, and iOS development, making it suitable for both beginners and experienced programmers.

Uploaded by

kirilrbt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views77 pages

Objectivec The Ultimate Guide Sufyan Bin Uzayr Download

Objective-C: The Ultimate Guide by Sufyan Bin Uzayr is a comprehensive resource for learning the Objective-C programming language, covering both basic and advanced topics. The book emphasizes practical lessons and real-world applications, aiming to help developers write optimized and well-structured code. It includes detailed discussions on object-oriented programming, memory management, and iOS development, making it suitable for both beginners and experienced programmers.

Uploaded by

kirilrbt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Objectivec The Ultimate Guide Sufyan Bin Uzayr

download

https://ebookbell.com/product/objectivec-the-ultimate-guide-
sufyan-bin-uzayr-50848970

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.

The Ultimate Book On Stock Market Timing Volume 5 Technical Analysis


And Price Objectives Raymond Merriman

https://ebookbell.com/product/the-ultimate-book-on-stock-market-
timing-volume-5-technical-analysis-and-price-objectives-raymond-
merriman-46848006

Objectivec Programming The Big Nerd Ranch Guide 1st Edition Aaron
Hillegass

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-1st-edition-aaron-hillegass-2627310

Objectivec Programming The Big Nerd Ranch Guide 2e Big Nerd Ranch
Guides Hillegass

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-2e-big-nerd-ranch-guides-hillegass-38183932

Objectivec Programming The Big Nerd Ranch Guide 2nd Edition Aaron
Hillegass

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-2nd-edition-aaron-hillegass-4654516
Objectivec Programming The Big Nerd Ranch Guide 2e Big Nerd Ranch
Guides Hillegass

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-2e-big-nerd-ranch-guides-hillegass-22846750

Objectivec Programming The Big Nerd Ranch Guide 2e Big Nerd Ranch
Guides Aaron Hillegass Mikey Ward Hillegass

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-2e-big-nerd-ranch-guides-aaron-hillegass-mikey-ward-
hillegass-29287066

Objectivec Programming The Big Nerd Ranch Guide Aaron Hillegass Mark
Fenoglio

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-aaron-hillegass-mark-fenoglio-32632590

Objectivec Programming The Big Nerd Ranch Guide Big Nerd Ranch Guides
Hillegass Aaron Aaron

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-big-nerd-ranch-guides-hillegass-aaron-aaron-35406134

Objectivec Programming The Big Nerd Ranch Guide 2e Big Nerd Ranch
Guides Aaron Hillegass Ward

https://ebookbell.com/product/objectivec-programming-the-big-nerd-
ranch-guide-2e-big-nerd-ranch-guides-aaron-hillegass-ward-36156342
Objective-C

Objective-C is a general-purpose, object-oriented programming language that


extends the C programming language with Smalltalk-style messaging. While si-
multaneously developing for OS X and iOS, Objective-C’s capabilities have been
bolstered by the inclusion of a dynamic runtime and assistance for object-oriented
programming.

Objective-C: The Ultimate Guide walks developers and coders through a straight-
forward and practical method of learning the Objective-C programming language.
This book discusses the basics in brief, and then moves on to more advanced and
detailed exercises to help readers quickly gain the required knowledge. The focus in
this book remains on writing optimized and well-structured code in Objective-C.

Key Features:

• Follows a hands-on approach and offers practical lessons and tutorials


related to Objective-C
• Discusses Objective-C using real world industry concepts
• Includes at-length discussion of Objective-C concepts to help build robust
knowledge
Objective-C
The Ultimate Guide

Sufyan bin Uzayr


First edition published 2024
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton, FL 33431
and by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
CRC Press is an imprint of Taylor & Francis Group, LLC
© 2024 Sufyan bin Uzayr
Reasonable efforts have been made to publish reliable data and information, but the author and
publisher cannot assume responsibility for the validity of all materials or the consequences of their use.
The authors and publishers have attempted to trace the copyright holders of all material reproduced in
this publication and apologize to copyright holders if permission to publish in this form has not been
obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information
storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com
or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf.
co.uk
Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.

ISBN: 9781032413211 (hbk)


ISBN: 9781032413198 (pbk)
ISBN: 9781003357506 (ebk)

DOI: 10.1201/9781003357506

Typeset in Minion Pro


by KnowledgeWorks Global Ltd.
For Dad
Contents

About the Author, xix


Acknowledgments, xx

Chapter 1   ◾    Crash Course in Objective-C 1


OBJECTIVE-C SPECIFICS 2
WHY OBJECTIVE-C? 2
DIFFERENTIATING OBJECTIVE-C VERSUS SWIFT 3
DIFFERENTIATING OBJECTIVE-C FROM C++ 3
UPSIDES AND DOWNSIDES OF OBJECTIVE-C 4
Upsides 4
Downsides 4
FACTORS TO CONSIDER 5
OBJECTIVE-C OVERVIEW 5
FRAMEWORK FOR THE FOUNDATION 6
LEARNING OBJECTIVE-C 6
USING OBJECTIVE-C 6
SETUP OF THE OBJECTIVE-C ENVIRONMENT 6
LOCAL ENVIRONMENT CONFIGURATION 6
EDITOR OF TEXT 6
GCC COMPILER 7
UNIX/LINUX INSTALLATION 7
MAC OS INSTALLATION 8
WINDOWS INSTALLATION 9
STRUCTURE OF THE OBJECTIVE-C PROGRAM 9
vii
viii   ◾    Contents

OBJECTIVE-C EXAMPLE OF HELLO EVERYONE 9


BASIC SYNTAX IN OBJECTIVE-C 11
OBJECTIVE-C TOKENS 11
SEMICOLONS; 11
COMMENTS 11
IDENTIFIERS 12
KEYWORDS 12
WHITESPACE IN OBJECTIVE-C 12
DATA TYPES IN OBJECTIVE-C 13
TYPES OF INTEGERS 14
TYPES OF FLOATING-POINT 14
VOID TYPE 15
VARIABLES IN OBJECTIVE-C 15
OBJECTIVE-C VARIABLE DEFINITION 16
OBJECTIVE-C VARIABLE DECLARATION 17
OBJECTIVE-C lvalues AND rvalues 18
CONSTANTS IN OBJECTIVE-C 19
INTEGER LITERALS 19
FLOATING-POINT LITERALS 19
CHARACTER CONSTANTS 20
STRING LITERALS 21
CONSTANT DEFINITION 21
#define Preprocessor 21
const Keyword 22
OPERATORS IN OBJECTIVE-C 22
ARITHMETIC OPERATORS IN OBJECTIVE-C 23
RELATIONAL OPERATORS 23
LOGICAL OPERATORS IN OBJECTIVE-C 24
BITWISE OPERATORS 24
ASSIGNMENT OPERATORS 25
MISC OPERATORS ↦ SIZEOF & TERNARY 26
OPERATORS’ PRECEDENCE IN THE OBJECTIVE-C 26
Contents   ◾    ix

LOOPS IN OBJECTIVE-C 27
CONTROL STATEMENTS FOR LOOPS 28
INFINITE LOOP 28
DECISION MAKING IN OBJECTIVE-C 29
THE ? : OPERATOR 30
FUNCTIONS IN OBJECTIVE-C 30
CREATING A METHOD 31
DECLARATIONS OF METHOD 32
CALLING A METHOD 32
FUNCTION ARGUMENTS 34
BLOCKS IN OBJECTIVE-C 34
Simple Block Declaration Syntax 35
Implementation of a Simple Block 35
BLOCKS TAKE ARGUMENTS AND RETURN VALUES 35
BLOCKS USING THE TYPE DEFINITIONS 35
NUMBERS IN OBJECTIVE-C 36
ARRAYS IN OBJECTIVE-C 38
DECLARING ARRAYS 38
ARRAYS INITIALIZATION 39
ACCESSING ARRAY ELEMENTS 39
ARRAYS IN OBJECTIVE-C IN DEPTH 40
POINTERS IN OBJECTIVE-C 41
WHAT EXACTLY ARE POINTERS IN OBJECTIVE-C? 41
How Do Pointers Work? 42
OBJECTIVE-C NULL POINTERS 43
DETAILS ABOUT OBJECTIVE-C POINTERS 43
STRINGS IN OBJECTIVE-C 44
STRUCTURES IN OBJECTIVE-C 46
CREATING A STRUCTURE 47
ACCESS TO STRUCTURE MEMBERS 47
FUNCTION ARGUMENTS AS STRUCTURES 48
POINTERS TO STRUCTURES 50
x   ◾    Contents

BIT FIELDS52
PREPROCESSORS IN OBJECTIVE-C52
EXAMPLES OF PREPROCESSORS53
PREDEFINED MACROS54
OPERATORS OF PREPROCESSORS55
Macro Continuation (\)55
Stringize (#)55
Token Pasting (##)55
defined() Operator56
PARAMETERIZED MACROS56
Typedef IN OBJECTIVE-C57
typedef vs #define58
TYPE CASTING IN OBJECTIVE-C59
INTEGER PROMOTION59
USUAL ARITHMETIC CONVERSION60
LOG HANDLING IN OBJECTIVE-C61
NSLog METHOD61
DISABLING LOGS IN THE LIVE Apps61
ERROR HANDLING IN OBJECTIVE-C62
NSError62
COMMAND-LINE ARGUMENTS64
BIBLIOGRAPHY65

Chapter 2   ◾    OOP in Objective-C 67


OBJECT-ORIENTED PROGRAMMING67
OPERATIONS AND DATA67
IMPLEMENTATION AND INTERFACE68
THE OBJECT MODEL71
THE METAPHOR OF MESSAGING73
CHARACTERISTIC OF OBJECTIVE-C75
DEFINITIONS OF OBJECTIVE-C CLASSES75
ALLOCATING AND INITIALIZING OBJECTIVE-C OBJECTS76
Contents   ◾    xi

ACCESSING DATA MEMBERS76


Properties77
Modularity78
Reusability79
INHERITANCE IN OBJECTIVE-C80
BASE AND DERIVED CLASSES81
ACCESS THE CONTROL AND INHERITANCE83
Hierarchies of Class83
Definitions of Subclass84
DYNAMISM85
POLYMORPHISM IN OBJECTIVE-C85
DATA ENCAPSULATION IN OBJECTIVE-C88
EXAMPLE OF DATA ENCAPSULATION90
CREATING A STRATEGY91
CATEGORIES IN OBJECTIVE-C91
CATEGORY CHARACTERISTICS92
POSING IN OBJECTIVE-C93
POSING RESTRICTIONS93
EXTENSIONS IN OBJECTIVE-C 94
EXTENSIONS’ CHARACTERISTICS95
Example of Extensions95
PROTOCOLS IN OBJECTIVE-C96
DYNAMIC BINDING IN OBJECTIVE-C99
COMPOSITE OBJECTS IN OBJECTIVE-C101
CLASS CLUSTERS101
WHAT EXACTLY IS A COMPOSITE OBJECT?101
An Example of a Composite Object102
FOUNDATION FRAMEWORK IN OBJECTIVE-C104
Functionality-Based Foundation Classes105
FAST ENUMERATION IN OBJECTIVE-C106
COLLECTIONS IN THE OBJECTIVE-C106
MEMORY MANAGEMENT IN OBJECTIVE-C107
xii   ◾    Contents

“MANUAL RETAIN-RELEASE” OR MRR 108


Basic MRR Rules 109
“AUTOMATIC REFERENCE COUNTING” OR ARC 110
BIBLIOGRAPHY 112

Chapter 3   ◾    Interface and API 113


iOS IN OBJECTIVE-C 113
IMPLEMENTATION AND INTERFACE 113
OBJECT CREATION 114
METHODS 114
Class Methods 114
Instance Methods 115
IMPORTANT OBJECTIVE-C DATA TYPES 115
Printing Logs 115
CONTROL STRUCTURES 115
PROPERTIES 116
Properties of Accessing 116
CATEGORIES 116
Arrays 116
Dictionary 117
ENVIRONMENT SETUP 117
Installation of Xcode 117
INTERFACE BUILDER 118
SIMULATOR FOR iOS 118
FIRST iPHONE APPLICATION 118
FIRST iOS APPLICATION’S CODE 119
AppDelegate.h 120
AppDelegate.m 120
ViewController.h 123
ViewController.m 123
ACTIONS AND OUTLETS IN iOS 124
DELEGATES IN iOS 125
How to Create a Delegate 126
Contents   ◾    xiii

UI ELEMENTS128
What Are UI Elements?128
How Do We Insert UI Elements?128
Our Focus128
Our Strategy128
LIST OF UI ELEMENTS129
ACCELEROMETER IN iOS130
UNIVERSAL APPLICATIONS IN iOS131
CAMERA MANAGEMENT IN iOS132
LOCATION HANDLING IN iOS134
SQLite DATABASE IN iOS137
SENDING EMAIL ON iOS144
AUDIO AND VIDEO IN iOS146
FILE HANDLING IN iOS148
METHODS FOR FILE HANDLING148
Check to See If a File in Objective-C Exists at a Given Path148
Comparing the Contents of Two Files148
Check to See If It Is Writable, Readable, and Executable149
Move File149
Copy File149
Remove File149
Read File149
Write File149
ACCESSING MAPS ON iOS150
IN-APP PURCHASE IN iOS152
iAd INTEGRATION IN iOS158
GameKit IN iOS159
STORYBOARDS IN iOS162
AUTO LAYOUTS IN iOS163
Aim of Our Example163
Our Strategy163
The Involved Steps164
xiv   ◾    Contents

TWITTER AND FACEBOOK ON iOS167


MEMORY MANAGEMENT IN iOS170
MEMORY MANAGEMENT CHALLENGES170
RULES FOR MEMORY MANAGEMENT170
DEALING WITH MEMORY IN ARC170
MEMORY MANAGEMENT TOOLS170
ANALYTICAL METHODS FOR MEMORY ALLOCATIONS171
APPLICATION DEBUGGING IN iOS171
CHOOSING A DEBUGGER171
HOW TO LOCATE CODING ERRORS171
SET BREAKPOINTS171
BREAKPOINT EXCEPTION172
IN AN iOS App, WE MAY USE GOOGLE APIs172
NOTE 174
BIBLIOGRAPHY 174

Chapter 4 ◾ Functional Programming 177


WHY OBJECT-FUNCTIONAL PROGRAMMING? 178
OBJECTIVE-C FUNCTIONAL PROGRAMMING 178
On Functional Programming 180
On the ObjC Runtime 180
On Objective-C and Language Design 181
WRITE OBJECTIVE-C CODE 181
CLASSES AND OBJECTS 183
METHODS AND COMMUNICATION 185
CLASS METHODS 188
Properties and Accessor Methods Are Declared 188
BLOCKS 190
PROTOCOLS AND CATEGORIES 192
Types and Coding Strategies Are Defined 193
CREATE THE VIDEO App 195
Set the App’s Audio Behavior 195
Build View Controller Class Declaration 198
Contents   ◾    xv

Import the Brightcove Player SDK Header File


into the Program 198
Look at the Code 198
Construct the View Controller Implementation
in Objective-C 198
Customize the Project to Reflect Our Values 198
Declare Properties 199
DEFINE INITIALIZATION METHOD 200
Setup Player 200
Configure Player 201
Use the Brightcove Library to Request Material 202
Look at the Code 203
NOTE 205
BIBLIOGRAPHY 205

Chapter 5 ◾ Code Management 207


WHY MUST WE PERFORM THIS? 208
ANATOMY OF A FRAMEWORK 209
STATIC AND DYNAMIC FRAMEWORKS 209
ARCHITECTURES AND SLICING OF PROCESSORS 210
DEVELOPING A DYNAMIC STRUCTURE 210
SETTING UP OUR PROJECT 210
DEVELOPING OUR CODE 211
ACCESS CONTROL 211
UMBRELLA HEADER 211
UNIVERSAL SUPPORT 212
UTILIZING OUR DYNAMIC FRAMEWORK 215
DEVELOPING A STATIC FRAMEWORK 215
SETTING UP OUR PROJECT 215
DEVELOPING OUR CODE 215
ACCESS CONTROL 215
UMBRELLA HEADER 216
PACKAGING 216
xvi   ◾    Contents

MODIFY BUILD SETTINGS TO SUPPORT STATIC


FRAMEWORKS216
MODULE SUPPORT216
CREATING THE BUNDLE STRUCTURE217
UNIVERSAL SUPPORT218
UTILIZING OUR STATIC FRAMEWORK220
RECOMMENDATIONS220
COMPILING AND CONSTRUCTING THE FRAMEWORK221
UPLOADING AN APPLICATION’S FRAMEWORK TO THE
APP STORE221
MEMORY MANAGEMENT IN OBJECTIVE-C221
“MANUAL RETAIN-RELEASE” OR MRR222
Basic MRR Rules223
“AUTOMATIC REFERENCE COUNTING” OR ARC225
Effective Procedures Prevent Memory-Related Issues226
DEBUG MEMORY ISSUES USING ANALYSIS TOOLS226
THE GOAL OF MEMORY MANAGEMENT226
Avoid Crashing227
Strong vs Weak227
Atomic and Nonatomic228
DESIGN PATTERNS IN iOS228
FAÇADE229
When to Use the Facade Pattern?229
An Illustration of Facade Design Pattern 230
DECORATOR230
When Should We Use a Decorator Pattern?230
Example of Decorator Style Design 230
MEMENTO231
ADAPTER231
When to Use an Adapter?231
Illustration of Adapter Pattern 231
OBSERVER231
Contents   ◾    xvii

When Should We Use a Decorator Pattern?232


Example of Decorator Style Design 232
STRATEGY232
FACTORY232
COMMAND233
COMPOSITE233
ITERATOR233
MEDIATOR233
SINGLETON233
When Should We Use the Singleton Design Pattern?234
Illustration of Singleton Pattern 234
MVC234
MVP235
MVVM236
Feature Assessment236
VIPER237
WHAT ARE THE ADVANTAGES OF EMPLOYING iOS
DESIGN PATTERNS?237
Prepared to Develop iOS Applications Using iOS Design
Patterns238
BIBLIOGRAPHY238

Chapter 6   ◾    Code Optimization 239


OBJECTIVE-C CODE OPTIMIZATION AT COMPILE TIME239
OBJECTIVE-C PIPELINE240
SECURE CODE243
Security Breach through HTTPS Response Cache244
RESUME BACKGROUND DISCLOSURE OF SCREENSHOT
DATA245
SSL PINNING245
BEST PRACTICES WITH OBJECTIVE-C CODING
CONVENTION250
Operators250
xviii   ◾    Contents

Types 250
Methods 250
Pragma Mark and Implementation Organization 251
Control Structures 251
Switch 252
For 253
While 253
Import 253
Header Prefix 254
Properties 254
Private Methods and Properties 254
Extern, Const, and Static 255
Naming 255
Enums 256
HARDENING OF SYSTEMS 256
Hardening of Systems to Reduce the “Attack Surface” 256
Advantages of System Hardening 257
NOTE 257
BIBLIOGRAPHY 257

APPRAISAL, 259

OBJECTIVE-C CHEAT SHEET, 305

INDEX, 309
About the Author

Sufyan bin Uzayr is a writer, coder, and entrepreneur with over a decade
of experience in the industry. He has authored several books in the past,
pertaining to a diverse range of topics, ranging from History to Computers/IT.
Sufyan is the Director of Parakozm, a multinational IT company spe-
cializing in EdTech solutions. He also runs Zeba Academy, an online
learning and teaching vertical with a focus on STEM fields. He special-
izes in a wide variety of technologies such as JavaScript, Dart, WordPress,
Drupal, Linux, and Python. He holds multiple degrees including ones in
Management, IT, Literature, and Political Science.
Sufyan is a digital nomad, dividing his time between four countries.
He has lived and taught in numerous universities and educational institu-
tions around the globe. Sufyan takes a keen interest in technology, politics,
literature, history, and sports, and in his spare time, he enjoys teaching
coding and English to young students.
Learn more at sufyanism.com

xix
Acknowledgments

There are many people who deserve to be on this page, for this book would
not have come into existence without their support. That said, some names
deserve a special mention, and I am genuinely grateful to:

• My parents, for everything they have done for me.


• The Parakozm team, especially Divya Sachdeva, Jaskiran Kaur, and
Simran Rao, for offering great amounts of help and assistance during
the book-writing process.
• The CRC team, especially Sean Connelly and Danielle Zarfati, for
ensuring that the book’s content, layout, formatting, and everything
else remain perfect throughout.
• Reviewers of this book, for going through the manuscript and pro-
viding their insight and feedback.
• Typesetters, cover designers, printers, and everyone else, for their
part in the development of this book.
• All the folks associated with Zeba Academy, either directly or indi-
rectly, for their help and support.
• The programming community in general, and the web development
community in particular, for all their hard work and efforts.

Sufyan bin Uzayr

xx
Chapter 1

Crash Course in
Objective-C

IN THIS CHAPTER

➢ What is Objective-C
➢ Major Concepts
➢ Advantages and Disadvantages
➢ Syntax and Code Basics
➢ Additional Info

Objective-C language is a general-purpose, object-oriented programming


language that extends the C programming language with Smalltalk-style
messaging. Apple’s primary programming language for the OS X and iOS
operating systems and their associated APIs, Cocoa, and Cocoa Touch.
This book will walk you through a straightforward and practical method
of learning the Objective-C programming language.
Programming in Objective-C is a general-purpose programming lan-
guage. Although it is not unique to any platform or system, use it to con-
struct a wide range of frameworks. Programming in Objective-C adds
communications features to the language C.
Objective-C is one of the primary programming languages used by
Apple for the iOS platform and is used to develop mobile apps for this
platform. Being the superset of the C programming language, it allows
DOI: 10.1201/9781003357506-1 1
2   ◾    Objective-C

developers to be more detail-oriented and accommodating of objects and


other programming languages.
Numerous programming languages exist. Three programming lan-
guages are now in high demand: Swift, Objective-C , and C++. Let’s exam-
ine the fundamental distinctions between Objective-C and the other two
programming languages:

OBJECTIVE-C SPECIFICS
Objective-C is excellent for memory management; there are avail-
able compilers that can turn Objective-C code into static code analy-
sis, which the language then uses to distinguish important information
from “trash.”
The most crucial aspect of Objective-C to understand is that it is very
object-oriented. Using this additional language, you can move graphs and
modify files, but it is crucial to understand its limits to comprehend its
benefits.
Objective-C, a programming language created in the 1980s, retains
many features used in iOS-specific mobile app development. While there
has been no breakthrough that enables Objective-C to be utilized on all
platforms, Objective-C is compatible with C and other languages for iOS
apps.
Objective-C competes with Swift, a more recent iOS programming lan-
guage. Several discussions over whether programming language provides
superior iOS mobile application development outcomes.

WHY OBJECTIVE-C?
For several reasons, the Objective-C programming language is selected.
It’s an object-oriented language, first and foremost. Object-oriented
approaches are required to give the type of capability seen in the Cocoa
frameworks. Second, since Objective-C is an extension of ANSI C, exist-
ing C applications are converted to utilize the software frameworks with-
out sacrificing any of the efforts that went into their creation. Because
Objective-C includes C, you receive all of the advantages of C while deal-
ing with it.
You may select whether to use object-oriented programming methods
(for example, to create a new class) and when to use procedural program-
ming techniques (define a structure and some functions instead of a class).
Furthermore, Objective-C is a very basic programming language. It has
a simple, clear syntax that is simple to pick up.
Crash Course in Objective-C   ◾    3

Object-oriented programming poses a high learning curve to new


recruits with its self-conscious vocabulary and focuses on abstract design.
A well-structured language, such as Objective-C, may make becoming an
expert object-oriented programmer considerably easier.
Objective-C is exceptionally dynamic when compared to other C-based
object-oriented languages. For usage at runtime, the compiler saves a lot
of information about the objects themselves. Decisions taken at compile
time are deferred until after the program has been executed. Objective-C
programs have a lot of flexibility and power because of their dynamism. It
provides two major advantages that are difficult to get with other ostensi-
bly object-oriented languages.
Objective-C has an open, dynamic binding approach that can allow a
basic interactive user interface design. Messages are not always bound by
the receiver’s class or method name. Therefore a software framework may
enable users to make decisions at runtime and provide developers a cre-
ative latitude in their design. (Terms like dynamic binding, message, class,
and receiver will be defined later in this text.)
Dynamism allows for the creation of advanced development tools. It’s
feasible to construct tools that monitor, intervene, and disclose the underly-
ing structure and activity of Objective-C programs using an interface to the
runtime system, which offers access to information about running apps.

DIFFERENTIATING OBJECTIVE-C VERSUS SWIFT


Swift is the programming language that Apple introduced in June 2014.
Objective-C has all the flaws one would anticipate from a language derived
from C. To differentiate keywords and types from C types, Objective-C
prefixes new keywords with @. Swift is not based on C. Therefore, it may
combine all Objective-C types and object-related keywords and extract
their many @ symbols.
In addition to other modern programming languages, Swift code
nearly resembles natural English. This readability makes it easier for exist-
ing programmers from JavaScript, Java, Python, C#, and C++ to adopt
Swift as part of their toolchain, in contrast to the painful experience that
Objective-C programmers had.

DIFFERENTIATING OBJECTIVE-C FROM C++


Wilkerson states that C++ was introduced in 1979 to combine objects and
instance methods with the original C programming language. Objective-C
language was founded on the belief that object-oriented programming
4   ◾    Objective-C

would be more productive and successful for big software projects; several
senior experts see this as the cause for C++’s widespread acceptance in
the years that followed. According to programming community experts,
C++ is the language used to create most current desktop applications. As
a result of its popularity, many frameworks and libraries have been devel-
oped to extend C++ for functions such as high-performance graphics,
audio digital signal processing, and user interface design.
Both languages are derived from C, but they are two entirely distinct
languages. Objective-C relies heavily on its runtime library to handle
inheritance and polymorphism, while C relies heavily on compile-time
choices for transmission. Nevertheless, in C++, the focus is often on com-
pile-time conclusions. C++ is a middle-level programming language that
runs on several cross-platform operating systems including Windows,
UNIX, Mac OS, etc. Objective-C, in contrast, is a general-purpose, object-
oriented programming language that Apple uses in its operating systems
and Cocoa APIs, etc.

UPSIDES AND DOWNSIDES OF OBJECTIVE-C


Upsides

• Compatibility with both C++ and Objective-C++


• Effective attributes such as method swizzling
• More dependable assistance in coding Binary Frameworks.

Downsides

• Since Objective-C is built upon C, namespacing is required. All


classes inside an Objective-C program must be globally unique.
Therefore, there is a practice of prefixing class names to avoid con-
flict. This is why we own the “NS” prefix for Foundation Framework
classes and the “UI” prefix for UIKit classes.
• Specific pointers.
• The ability to send a message on a nil object without dropping
and the lack of strict type make it harder to identify and resolve
issues.
• The syntax of the language is tedious and complex.
Crash Course in Objective-C   ◾    5

FACTORS TO CONSIDER
Objective-C application development may be expedited and is an
excellent approach to adding object-based functionality to an appli-
cation. There are many important considerations about this superset
language:
Maintenance is essential; this pertains to upgrading Objective-C devel-
oped applications. Although the language is dated, it is not outdated. It
merely takes minimal maintenance to remain current.
Less adaption is necessary as many APIs still have a lot to catch up for
Swift-developed applications. This suggests that Objective-C may be sim-
pler to deploy to iOS mobile applications.
Object handling made simpler Apple is all about having an object net-
work. Using Objective-C, these objects are readily movable.
Objective-C may simplify iOS mobile applications in all Apple iOS
devices, including smartphones and tablets.

OBJECTIVE-C OVERVIEW
Objective-C supports object-oriented programming, along with the four
object-oriented development pillars.

• Encapsulation
• Data hiding
• Inheritance
• Polymorphism

Example:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {


NSAutoreleasePool * pool = [[NSAutoreleasePool
alloc] init];

NSLog (@"hello everyone");


[pool drain];
return 0;
}
6   ◾    Objective-C

FRAMEWORK FOR THE FOUNDATION


The Foundation Framework has a plethora of functionality, which are
described below.
It includes several expanded datatypes such as NSArray, NSDictionary,
NSSet, and others.
It has an extensive collection of functions for handling files, strings, etc.
It has URL processing functions and utilities like date formatting, data
handling, error handling, etc.

LEARNING OBJECTIVE-C
When studying Objective-C, the essential thing to remember is to stay
focused on principles rather than getting bogged down in language
technicalities.
The goal of studying a programming language is to become a better
programmer or become more successful at developing, implementing, and
maintaining existing systems.

USING OBJECTIVE-C
As previously stated, Objective-C is utilized in iOS and Mac OS X. It has
a sizable iOS user base and a rapidly growing Mac OS X user base. And
because Apple prioritizes quality, this is fantastic news for individuals who
have just begun learning Objective-C.

SETUP OF THE OBJECTIVE-C ENVIRONMENT

LOCAL ENVIRONMENT CONFIGURATION


If we want to create our own environment for the Objective-C program-
ming language, we must install Text Editor and The GCC Compiler on our
computer.

EDITOR OF TEXT
This is where we will type our program. Some editors are Windows
Notepad, the OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
On various operating systems, the name and version of the text editor
may differ. Notepad, for example, will be used on Windows, and use vim
or vi on both Windows and Linux or UNIX.
Source files are files that we produce with our editor that contain pro-
gram source code. Objective-C source files are commonly named with the
extension “.m.”
Crash Course in Objective-C   ◾    7

Before starting our programming, make sure we have one text editor
in place, and we have enough knowledge to develop a computer program,
store it in a file, compile it, and eventually run it.

GCC COMPILER
Our program’s source code is written in a source file and is human read-
able. It must “compiled” into machine code before our CPU can run the
program as instructed.
Use this GCC compiler to transform our source code into an executable
application. We’re assuming we’re familiar with programming language
compilers.
The GCC compiler is available for free on various systems, and the tech-
nique for installing it on those platforms is detailed here.

UNIX/LINUX INSTALLATION
The first step is to install gcc and the gcc Objective-C package. This is
accomplished by:

$ su -
$ yum install gcc
$ yum install gcc-objc

The following command is used to configure package dependencies:

$ yum install make libpng libpng-devel libtiff


libtiff-devel libobjc
libxml2 libxml2-devel libX11-devel libXt-devel
libjpeg libjpeg-devel

Download and install GNUStep to unlock all of Objective-functionality.


The package is obtained by visiting http://wwwmain.gnustep.org/resources/
downloads.php
Now we must navigate to the downloaded location and unpack the file
using:

$ tar xvfz gnustep-startup-.tar.gz

Now we must navigate to the folder GNUStep-startup, which is created


by using:

$ cd gnustep-startup-<version>
8   ◾    Objective-C

The construction procedure must then be configured.

$. /configure

Then we may construct by

$ make

We must eventually create the environment by

$ ./usr/GNUstep/System/Library/Makefiles/GNUstep.sh

We have a helloeveryone.m Objective-C file that looks like this:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {


NSAutoreleasePool * pool = [[NSAutoreleasePool
alloc] init];

NSLog (@"hello everyone");


[pool drain];
return 0;
}

Now we can build and execute an Objective-C file, say helloeveryone.m,


by using cd to get to the file’s location and then doing the following steps:

$ gcc 'gnustep-config --objc-flags'


-L/usr/GNUstep/Local/Library/Libraries
-lgnustep-base helloeveryone.m -o helloeveryone
$ ./helloeveryone

MAC OS INSTALLATION
If we’re running Mac OS X, the simplest method to get GCC is to down-
load Apple’s Xcode development environment and follow the straightfor-
ward installation instructions. Once we’ve installed Xcode, we’ll be able to
utilize the GNU C/C++ compiler.
Xcode is presently being downloaded at https://developer.apple.com/
xcode/.
Crash Course in Objective-C   ◾    9

WINDOWS INSTALLATION
To run an Objective-C program on Windows, we must first install MinGW
and GNUStep Core. Download both at: https://www.gnu.org/software/
gnustep/windows/installer.html.
We must first install the MSYS/MinGW System package. The GNUstep
Core package then is installed and both of which have a self-explanatory
Windows setup.
Then, go to Start -> All Programs -> GNUstep -> Shell to utilize
Objective-C and GNUstep.
Navigate to the helloeveryone.m folder.
We may use to compile the code.

$ gcc 'gnustep-config --objc-flags'


-L /GNUstep/System/Library/Libraries helloeveryone.m
-o hello -lgnustep-base -lobjc

STRUCTURE OF THE OBJECTIVE-C PROGRAM


Before we examine the fundamental building blocks of the Objective-C
programming language, let’s look at a bare minimum Objective-C pro-
gram structure that we can use as a reference in the later chapters.

OBJECTIVE-C EXAMPLE OF HELLO EVERYONE


A simple Objective-C program consists of the following components:

• Preprocessor Commands
• Interface
• Implementation
• Method
• Variables
• Statements & Expressions
• Comments

Consider a simple code that prints the words “Hello Everyone.”

#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
10   ◾    Objective-C

- (void)sampleMethod;
@end

@implementation SampleClass

- (void)sampleMethod {
NSLog(@"Hello, Everyone \n");
}

@end

int main() {
/* first program in the Objective-C */
SampleClass *sampleClass = [[SampleClass alloc]
init];
[sampleClass sampleMethod];
return 0;
}

Let’s examine several components of the code above:

• The first line of the code, #import <Foundation/Foundation.h>, is a


preprocessor instruction that instructs an Objective-C compiler to
import the Foundation.h file before real compilation.

• The following line @interface SampleClass:NSObject demonstrates


interface creation. It inherits the foundation class for all objects,
NSObject.

• (void)sampleMethod; demonstrates how to define a method.

• The following line, @end, signifies the end of an interface.

• The following line demonstrates how to implement the interface


SampleClass.

• The sampleMethod is implemented in the following line, (void)


sampleMethod.

• The next line @end signifies the conclusion of an implementation.

• The following line, int main(), is the program’s main function, where
execution starts.
Crash Course in Objective-C   ◾    11

• The next line /*…*/ will be disregarded by the compiler and has been
included to provide additional program comments. Therefore, these
lines are known as comments in the program.
• The following line NSLog(…) is an Objective-C function that causes
the message “Hello, Everyone” to appear on the screen.
• The next line return 0; concludes the main() function and returns
the number 0.

BASIC SYNTAX IN OBJECTIVE-C

OBJECTIVE-C TOKENS
A token is a keyword, an identifier, a constant, a string literal, or a symbol
in an Objective-C program. For instance, the following Objective-C state-
ment is made up of six tokens:

NSLog(@"Hello, Everyone \n");

Individual tokens are referred to as:

NSLog
@
(
"Hello, Everyone \n"
)
;

SEMICOLONS;
A semicolon is a statement terminator in an Objective-C program. That is, a
semicolon must follow each sentence. It denotes the end of a single logical entity.
For example, consider the following two statements:

NSLog(@"Hello, Everyone \n");


return 0;

COMMENTS
Comments are similar to help text in our Objective-C application and are
disregarded by the compiler. As illustrated below, they begin with/* and
end with the characters */.

/* first program in the Objective-C */


12   ◾    Objective-C

There can be no comments within comments, and they cannot be


within a string or character literals.

IDENTIFIERS
An Objective-C identifier recognizes a variable, function, or other user-
defined items. An identifier starts with a letter A to Z, a to z, or an under-
score and ends with zero or more letters, underscores, or numbers (0 to 9).
Punctuation characters such as @, $, and per cent are not permitted
within identifiers in Objective-C. Objective-C is a computer language
that is case sensitive. Thus, in Objective-C, Manpower and manpower
are two different IDs. The following are some instances of appropriate
identifiers:

Kohd lara bac move_name b_213


name50 _temp j b23b9 retVal

KEYWORDS
The following is a list of reserved terms in Objective-C. These reserved
terms are not permitted to be used as constant, variable, or other identifier
names.

auto else Return switch


break enum register typedef
case extern long union
const float short unsigned
Char goto signed void
continue for sizeof volatile
default if struct while
do int Static _Packed
double protocol interface implementation
NSObject NSInteger NSNumber CGFloat
property nonatomic; retain weak
strong unsafe_unretained; readwrite readonly

WHITESPACE IN OBJECTIVE-C
A blank line has simply whitespace, potentially with a remark, and is com-
pletely ignored by an Objective-C compiler.
In Objective-C, whitespace refers to blanks, tabs, newline charac-
ters, and comments. Whitespace divides one section of a statement from
Crash Course in Objective-C   ◾    13

another and allows the compiler to determine where one element, such
as int, ends, and the next element starts in a statement. As a result, in the
following sentence

int ages;

For the compiler to distinguish between int and age, there must be at
least one whitespace character (typically a space). In contrast, the follow-
ing statement,

fruit = grapes + apples; // get total fruit

There are no whitespace characters required between fruit and =, or


between = and grapes. However, we are allowed to include any for read-
ability purposes.

DATA TYPES IN OBJECTIVE-C


Data types are a comprehensive framework used in the Objective-C pro-
gramming language for declaring variables or functions of various sorts.
A variable’s type dictates how much storage space it takes up and how the
bit pattern recorded is interpreted.
Objective-C types can be classed as follows:

Sr. No. Types and Description


1 Basic types
They are arithmetic types divided into two categories:
(a) integer types and (b) floating-point types.
2 Enumerated types
They are arithmetic types once more, and they are used to
construct variables that can only be allocated discrete
integer values throughout the program.
3 The type void
The type specifier void signifies that there is no accessible
value.
4 Derived types
Among them are pointer types, array types, structure types,
union types, and function types.

The aggregate types are the array and structure types combined. A
function’s type indicates the type of the function’s return value.
14   ◾    Objective-C

TYPES OF INTEGERS
The table below contains information on standard integer types, including
storage sizes and value ranges.

Type Storage Size Value Range


char 1 byte −128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte −128 to 127
int 2 or 4 bytes −32,768 to 32,767 or −2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes −32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes −2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

The sizeof operator can determine the precise size of a type or variable
on a specific platform. The phrase sizeof(type) returns the object or type’s
storage size in bytes. The following is an example of determining the size
of an int type on any computer.

#import <Foundation/Foundation.h>

int main() {
NSLog(@"The Storage size for int : %d \n",
sizeof(int));
return 0;
}

TYPES OF FLOATING-POINT
The table below contains information on typical float-point types, includ-
ing storage sizes, value ranges, and precision.

Type Storage Size Value Range Precision


float 4 byte 1.2E − 38 to 3.4E + 38 6 decimal-places
double 8 byte 2.3E − 308 to 1.7E + 308 15 decimal-places
long double 10 byte 3.4E − 4932 to 1.1E + 4932 19 decimal-places

The float.h header file includes macros that let us use these values and
other information about the binary representation of real numbers in our
applications. The following example will output the storage space occupied
by a float type and its range values.
Crash Course in Objective-C   ◾    15

#import <Foundation/Foundation.h>

int main() {
NSLog(@"The Storage size for float : %d \n",
sizeof(float));
return 0;
}

VOID TYPE
The void type indicates that there is no value available. It is used in three
different contexts.

Sr. No. Types and Description


1 Function returns as void
Several Objective-C functions do not return a value or return a void. The
return type of a function with no return value is void. As an example,
consider void exit (int status).
2 Function arguments as void
Some Objective-C functions do not accept any parameters. A void can be
accepted by a function that has no parameters. For instance, int rand(void).

VARIABLES IN OBJECTIVE-C
A variable is just the name assigned to a storage location that our pro-
grams may access. In Objective-C, each variable has a type that governs
the amount and layout of the variable’s memory, the range of values stored
inside that memory, and the set of operations that can apply to the variable.
A variable’s name can be letters, numbers, and the underscore char-
acter. Start it with a letter or an underscore. Because Objective-C is case-
sensitive, upper and lowercase letters are different.

Sr. No. Type and Description


1 char
A single octet is typical (one byte). It is a type of integer.
2 int
The machine’s most natural integer size.
3 float
A floating-point value with single precision.
4 double
A floating-point value with double precision.
5 void
Represents absence of type.
16   ◾    Objective-C

The Objective-C programming language also defines different sorts of


variables, which we will discuss in later chapters, such as Enumeration,
Pointer, Array, Structure, Union, etc. Let us look at fundamental variable
types in this section.

OBJECTIVE-C VARIABLE DEFINITION


In Objective-C, a variable definition tells the compiler where and how
much storage to generate for the variable. A variable description describes
a data type and includes a list of one or more variables of that type, as seen
below.

type variablelist;

In this case, a type must be a valid Objective-C data type, such as char,
w char, int, float, double, bool, or any user-defined object. The variable list
can have one or more identifier names separated by commas. Here are
some examples of valid declarations.

int c, d, e;
char k, kh;
float g, salary;
double q;

The line int c, d, e; declares and defines the variables c, d, and e; and tells
the compiler to create variables of type int called c, d, and e.
In their declaration, variables can be initialized (given an initial value).
The initializer is made of an equal sign followed by a constant expression,
as seen below.

type variablename = value;

Example:
extern int c = 3, d = 5; // declaration of c
and d.
int c = 3, d = 5; // definition and
initializing c and d.
byte k = 22; // definition and
initializes k.
char y = 'y'; // the variable y has
the value 'y'.
Crash Course in Objective-C   ◾    17

For variables declared without an initializer, variables with static stor-


age duration are automatically initialized with NULL (all bytes have the
value 0). In contrast, the initial value of all other variables is indeterminate.

OBJECTIVE-C VARIABLE DECLARATION


A variable declaration assures the compiler that there is at least one vari-
able with the specified type and name, allowing the compiler to continue
with further compilation without requiring more information. A variable
declaration only has significance at the time of compilation; the compiler
requires the actual variable declaration when linking the program.
A variable declaration is essential when you are utilizing many files. You
specify your variable in one of the files accessible at the time of program
linking. To define a variable at any location, you will utilize the extern
keyword. Variables are declared several times in Objective-C programs,
but they can only be defined once per file, function, or code block.
Example: Try out the following example, in which variables are declared
at the top but defined and initialized inside the main function.
#import <Foundation/Foundation.h>

// Variable-declaration:
extern int x, y;
extern int z;
extern float f;

int main () {
/* variable-definition: */
int x, y;
int z;
float f;

/* actual-initialization */
x = 10;
y = 20;

z = x + y;
NSLog(@"The value of z : %d \n", z);

f = 70.0/3.0;
NSLog(@"The value of f : %f \n", f);

return 0;
}
18   ◾    Objective-C

The same idea applies to function declarations, where we offer a func-


tion name at the time of declaration, and its actual definition is provided
afterward. The following example uses a C function, and as we may know,
Objective-C also supports C style functions.

// function-declaration
int func();

int main() {
// function-call
int k = func();
}

// function-definition
int func() {
return 0;
}

OBJECTIVE-C lvalues AND rvalues


In Objective-C, there are two types of expressions.

• lvalue: Expressions that refer to a memory location are called “lvalue”


expressions. An lvalue can be on either the left or right side of an
assignment.
• rvalue: The word rvalue refers to a data value stored in memory at
some address. An rvalue is an expression that cannot be assigned a
value; therefore, it can occur on the right but not the left side of an
assignment.

Variables are lvalues and can thus appear on the left side of an assign-
ment. Because numerical literals are rvalues, they cannot be allocated
and cannot appear on the left-hand side. The following is a correct
statement:

int k = 20;

However, the following is not a legitimate statement and would result in


a compile-time error.
Crash Course in Objective-C   ◾    19

CONSTANTS IN OBJECTIVE-C
The constants denote values that the program cannot modify during its
execution. These values are also known as literals.
Any fundamental data type may include integer constants, floating
constants, character constants, and string literals. Additionally, there are
enumeration constants.
The constants are processed identically to regular variables, except their
values are not altered once they are defined.

INTEGER LITERALS
An integer literal may be a decimal, octal, or hexadecimal constant. The
base or radix is specified by a prefix: 0x or 0X for hexadecimal, 0 for octal,
and nothing for decimal.
A literal integer may also include a suffix consisting of U and L, which
stand for unsigned and long, respectively. Write the suffix with uppercase
or lowercase letters and in any sequence.
The following are instances of integer literals:

414 /* Legal */
235u /* Legal */
0xFeeL /* Legal */
068 /* Illegal: 8 is not octal digit */
032UU /* Illegal: cannot repeat suffix */

Other types of Integer literals are illustrated below.

95 /* decimal */
0215 /* octal */
0x6b /* hexadecimal */
50 /* int */
50u /* unsigned int */
50l /* long */
50ul /* unsigned long */

FLOATING-POINT LITERALS
An integer part, a decimal point, a fractional part, and an exponent part
comprise a floating-point literal. Floating-point literals can be represented
in either decimal or exponential form.
When representing in decimal form, including the decimal point, expo-
nent, or both; when representing in exponential form, include the integer
portion, fractional part, or both. e or E introduces the signed exponent.
20   ◾    Objective-C

The following are some instances of floating-point literal:

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: the incomplete exponent */
210f /* Illegal: no-decimal or exponent */
.e55 /* Illegal: missing integer or the
fraction */

CHARACTER CONSTANTS
Character literals, such as ‘x,’ are contained in single quotes and may be
kept in a simple char variable.
A character literal in Objective-C can be a simple character (for exam-
ple, ‘x’), an escape sequence (for example, ‘\t’), or a universal character (for
example, ‘u02C0’).
Certain letters in C have unique significance when followed by a back-
slash and signify things like newline (\n) or tab (\t). A list of some of these
escape sequence codes is as follows.

Escape Sequence Meaning


\\ \ character
\' ‘character
\" “character
\? ? character
\a Alert or bell
\b Backspace
\f Form-feed
\n Newline
\r Carriage return
\t Horizontal-tab
\v Vertical-tab
\ooo Octal number of the one to three digits
\xhh. . . Hexadecimal number of the one or more digits

The following is an example of a few escape sequence characters.

#import <Foundation/Foundation.h>

int main() {
NSLog(@"Hello\tEveryone\n\n");
return 0;
}
Crash Course in Objective-C   ◾    21

STRING LITERALS
Double quotes “” are used to surround string literals or constants.
Characters in a string are comparable to character literals in that they
are plain characters, escape sequences, and universal characters. We can
divide an extensive line into numerous lines using string literals and
whitespaces.
Here are some string literal instances. The strings in all three variants
are identical.

"hello, sweetie"

"hello, \

sweetie"

"hello, " "s" "sweetie"

CONSTANT DEFINITION
In C, there are two straightforward ways to define constants.

• Using #define preprocessor


• Using const keyword

#define Preprocessor
The following is the syntax for using the #define preprocessor to declare a
constant:

#define identifiervalue

Example:
#import <Foundation/Foundation.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;
22   ◾    Objective-C

area = LENGTH * WIDTH;


NSLog(@"The value of area : %d", area);
NSLog(@"%c", NEWLINE);
return 0;
}

const Keyword
Constants of a specific type can be declared with the const prefix, as seen
below.

const typevariable = value;

Example:
#import <Foundation/Foundation.h>
int main() {
const int LENGTH = 20;
const int WIDTH = 15;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
NSLog(@"The value of area : %d", area);
NSLog(@"%c", NEWLINE);
return 0;
}

OPERATORS IN OBJECTIVE-C
An operator in Objective-C is a symbol that instructs the compiler to do
particular mathematical or logical operations. The Objective-C language
has several built-in operators, including the following:

• Arithmetic Operators
• Assignment Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Misc Operators
Crash Course in Objective-C   ◾    23

This session will walk us through arithmetic, relational, logical, bitwise,


assignment, and other operators.

ARITHMETIC OPERATORS IN OBJECTIVE-C


The table mentioned below lists all the arithmetic operators offered by the
Objective-C programming language. Assume variable A has a value of 20,
and variable B has a value of 30, then.

Operator Description Example


+ Adds the two operands C + D will give 30
- Subtracts the second operand from the first C − D will give −12
* Multiplies both the operands C * D will give 100
/ Divides numerator by the denominator D / C will give 3
% Modulus Operator and the remainder of after D % C will give 0
integer division
++ The increment operator increases the integer C++ will give 14
value by one
−− The decrement operator decreases the integer C−− will give 7
value by one

RELATIONAL OPERATORS
The table below lists all the relational operations provided by the
Objective-C programming language. Assume variable C has a value of 20
and variable D has a value of 30, then.

Operator Description Example


== Compares the values of two operands; if they are (C == D) is not true.
equal, the condition becomes true.
!= Compares the values of two operands; if the values are (C != D) is true.
not equal, the condition evaluates to true.
> If value of the left operand is larger than the value of (C > D) is not true.
the right operand, the condition is determined to be
true.
< The condition is true if value of the left operand is (C < D) is true.
smaller than the value of the right operand.
>= The condition is true if value of the left operand is (C >= D) is not true.
larger than or equal to the value of the right operand.
<= The condition is true if value of the left operand is less (C <= D) is true.
than or equal to the value of the right operand.
24   ◾    Objective-C

LOGICAL OPERATORS IN OBJECTIVE-C


The table mentioned below lists all of the logical operators provided by the
Objective-C programming language. Assuming variable C is 1 and vari-
able D is 0, then.

Operator Description Example


&& Defined as the Logical AND operator. If both operands (C && D) is false.
are non-zero, the condition is satisfied.
|| Defined as the Logical OR Operator. If any of the two (C || D) is true.
operands are non-zero, the condition is satisfied.
! Defined as the Logical NOT Operator. In Objective-C to !(C && D) is true.
reverse the logical state of its operand, use. When a
condition is true, the Logical NOT operator returns
false.

BITWISE OPERATORS
The bitwise operator operates on bits and performs operations bit by bit.
The truth tables for &, |, and are shown below.

c d c&d c|d c^d


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if C = 70; and D = 23; now, in binary format, they will be as


follows:

C = 0011 1100
D = 0000 1101
-----------------
C&D = 0000 1100
C|D = 0011 1101
C^D = 0011 0001
˜C = 1100 0011

The bitwise operations provided by Objective-C are given in the table


below. Assume variable C has a value of 70 and variable D has a value of
23, then.
Crash Course in Objective-C   ◾    25

Operator Description Example


& Binary AND Operator copies a bit to the (C & D) will give 12, which is
result if it exists in both operands. 0000 1100
| If bit exists in both operands, the binary OR (C | D) will give 61, which is
operator copies it. 0011 1101
^ If bit is set in one operand but not both, the (C ^ D) will give 49, which is
binary XOR operator replicates it. 0011 0001
∼ Binary Ones Complement Operator is a (∼C) will give −61, which is
unary operator that ‘flipping’ bits. 1100 0011 in 2’s complement
form.
<< Left Shift Binary Operator: The left operand’s C << 2 will give 240, which is
value is shifted left by the number of bits 1111 0000
given by the right operand.
>> Right Shift Binary Operator: The value of the C >> 2 will give 15, which is
left operand is shifted right by the number 0000 1111
of bits given by the right operand.

ASSIGNMENT OPERATORS
The Objective-C language supports the following assignment operators:

Operator Description Example


= A simple assignment operator assigns Z = X + Y will assign value of X +
the right operands’ values to the left Y into Z
operand.
+= It adds the right operand to the left Z += X is equivalent to Z = Z + X
operand and assigns the resulting value
to the left operand.
-= It subtracts the right operand from the Z -= X is equivalent to Z = Z – X
left operand and assigns the resulting
value to the left operand.
*= Multiplication AND assignment, This Z *= X is equivalent to Z = Z * X
operation multiplies the right operand
by the left operand and assigns the
product to the left operand.
/= Divide AND assignment divide the left Z /= X is equivalent to Z = Z / X
operand by the right operand and
assign the resulting value to the left
operand.
%= AND assignment operator, modulus. It Z %= X is equivalent to Z = Z % X
uses two operands to calculate the
modulus and assigns the result to the
left operand.

(Continued)
26   ◾    Objective-C

Operator Description Example


<<= The assignment AND shift-left operator. Z <<= 2 is same as Z = Z << 2
>>= The assignment AND right shift Z >>= 2 is same as Z = Z >> 2
operator.
&= The AND bitwise assignment operator. Z &= 2 is same as Z = Z & 2
^= OR is a bitwise exclusive assignment Z ^= 2 is same as Z = Z ^ 2
and assignment operator.
|= OR inclusive bitwise and assignment Z |= 2 is same as Z = Z | 2
operator.

MISC OPERATORS ↦ SIZEOF & TERNARY


Other essential operations provided by Objective-C language include size
of and ? :

Operator Description Example


sizeof() Returns the size of the variable. sizeof(x), where a is an integer, will
return 4.
& Returns the address of a variable. &x; will give the actual address of the
variable.
* Pointer to a variable. *x; will pointer to a variable.
?: The Conditional Expression If the Condition is true ? Then value A :
Otherwise value B.

OPERATORS’ PRECEDENCE IN THE OBJECTIVE-C


Operator precedence controls how words in an expression are grouped.
This influences the evaluation of an expression.
Certain operators have greater precedence than others; for instance, the
multiplication operator has higher precedence than the addition operator.
For example, c = 17 + 3 * 4; here, c is assigned 29, not 80, because operator
* has higher precedence than +, so it first gets multiplied with 3*4 and then
added into 12.
Here, operators with the most significant precedence are positioned at
the top of the table, while those with the lowest precedence are positioned
at the bottom. Within an expression, operators with higher precedence
will be evaluated first.

Category Operator Associativity


Postfix () [] −>. ++ − − Left to right
Unary + − ! ∼ ++ − − (type)* & sizeof Right to left
Multiplicative */% Left to right
(Continued)
Crash Course in Objective-C   ◾    27

Category Operator Associativity


Additive +− Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += −= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

LOOPS IN OBJECTIVE-C
There may be events when we need to execute a code block numerous times.
In general, statements are performed in the following order: the first state-
ment in a function is executed first, then the second, and so on. Control
structures in programming languages allow for more sophisticated execu-
tion routes. A loop statement allows us to run a statement or collection of
statements many times. The Objective-C programming language includes
the following loop types to address looping needs.

Loop in Objective-C.
28   ◾    Objective-C

Sr. No. Loop Type and Description


1 while loop
While a specific condition is true, a sentence or set of statements is repeated.
Before running the loop body, it checks the condition.
2 for loop
The code that maintains the loop variable is abbreviated when a series of
statements is executed many times.
3 do...while loop
It’s similar to a while statement. Only it checks the condition after the loop body.
4 nested loops
A while, for, or do while loop can include one or more loops.

CONTROL STATEMENTS FOR LOOPS


Loop control statements alter the execution sequence. All automated
objects produced in that scope are deleted when execution exits that scope.
Objective-C supports the following control statements. To learn more
about the control statements, click the links below.

Sr. No. Control Statement and Description


1 break statement
The loop or switch statement is terminated, and execution is transferred to the
statement immediately after the loop or switch.
2 continue statement
The loop will skip the rest of its body and instantly retest its state before repetition.

INFINITE LOOP
If condition never becomes false, loop becomes endless. Traditionally, the
for loop is used for this purpose. Because none of the three for loop expres-
sions are necessary, we may create an infinite loop by leaving the condi-
tional expression empty.

#import <Foundation/Foundation.h>

int main () {

for( ; ; ) {
NSLog(@"loop will run forever.\n");
}

return 0;
}
Crash Course in Objective-C   ◾    29

It is believed to be true when the conditional statement is miss-


ing. Although we may use an initialization and increment expression,
Objective-C programmers prefer to use them for(;;) construct to represent
an endless loop.

DECISION MAKING IN OBJECTIVE-C


The programmer must define one or more conditions to be evaluated or
tested by the program, a statement or statements to be performed if the
condition is discovered to be true, and optionally, further statements to be
run if the condition is decided to be false.
The general shape of a common decision-making framework in most
programming languages is shown below.

Decision making in Objective-C.

The Objective-C programming language treats any non-zero and non-


null value as true, but any zero or null value is false.
The Objective-C programming language has the following decision-
making statements.
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XIV
Bennie Takes a Day Off to Do a Good Turn—
He Washes All the Dirty Clothes

The next day neither of the scouts felt much like


strenuous exertion. Their arms ached from pulling the
boat, and they both had blisters on their hands, and the
excitement had left them rather tired.

Mr. Stone looked at them while they were eating


breakfast.

“Well, Bennie,” he said, “what are you and Spider going


to do today? I can’t seem to think of anything left
around here that will give you as much exercise as you
want. Of course, you haven’t yet run all the way down
the trail and run all the way back again. You might try
that. Or you might row to Llao Rock and tow your other
boat home, before the launch has to go for it.”

“Naw, that’s too easy,” Bennie grinned. “I kind of


thought we might hike around the rim road. How far is
it—forty miles? We’d be back in time for dinner.”

“A good idea!” Uncle Billy exclaimed.

“What’s a good idea?” asked Bennie, beginning to be


sorry he’d made the joke.

“A hike,” said the doctor.


Spider and Bennie groaned. 138

“Not today!” the doctor laughed. “Tomorrow, maybe. We


haven’t had a real hike yet, and I heard you talking the
other day, didn’t I, Bennie, about wanting to work for a
merit badge in hiking?”

“Where’ll we hike to—how far?” put in Dumplin’. “Look


at those two lovely automobiles, just doing nothing.
Don’t seem right to me to let ’em loaf so.”

“Well, you can stay back in camp, and have the wood all
cut and the dinner cooked for us when we get back,”
said his father.

“Yes, I will!” Dumplin’ retorted. “I may be fat——”

“It’s just possible,” put in Bennie.

“I may be fat, but I can keep goin’ as long as any of


you, I guess!”

“You may not be so fat when we get back,” Uncle Billy


went on. “I think it would be a great idea to give Bennie
some regular exercise, about tomorrow, also the day
after, and the day after that. We’ll hike over to the base
of Mount Scott, because that’s the highest point around
here, packing our blankets and grub. Then the second
day we’ll climb Scott, and the third day we’ll hike back
again.”

“Ho, that’s no hike at all, if you take three days for it!”
Bennie said. “I been looking on the map. It’s less ’n ten
miles from here to the top of the mountain, and the top
is only 8,938 feet high, so it’s only a 2,000-foot climb.”

139
“How much better you know this country than I do,”
said his uncle, quietly, “and how skilfully you can read
the contour intervals on a map. Well, you may go over
and back the same day, if you want to. The rest of us
will take three, however.”

Bennie turned red. “I—I guess I’m a dumb-bell,” he


stammered.

“It’s just possible,” Dumplin’ put in, while the rest


shouted with mirth at the hit.

Spider, meanwhile, had gone to his pack and got out the
government topographical survey map of Crater Lake
Park.

“Do we go along the rim?” he asked.

“More or less. We’ll have to climb part way up Garfield,


and then find a way down on the other side, and work
along back of Dutton Cliff to Kerr Valley.”

Spider was studying the contour interval lines of the


map closely now.

“Let’s see, we go up at least 500 feet for a start, and


then we go along a mile or two, and then we—holy
mackerel!—then we drop right down ’most a thousand!
And then——”

“Yes?” said Bennie.

“And then we go up again ’most a thousand, and then


we walk a mile, and then—jumping bullfrogs and little
fish hooks!—then we just fall down, let’s see, about a
thousand feet into Kerr Valley. That’s less than 6,500
feet above the sea. Scott is almost 9,000. We’ve still got
a climb of 2,500 feet ahead of us.”

“Aw, go on, you’re making that up,” Bennie insisted.


“You can’t tell all that from the map. Let me look.”

“Maybe you can’t tell,” Spider retorted. “I always told 140


you you didn’t half read a map. Go on—look for
yourself.”

And he passed the map over.

Bennie studied it carefully. “I guess maybe you’re right,”


he finally confessed. “Well, exercise is just what I need!
How’s the path, Uncle Bill?”

“Path!” the doctor laughed. “You’ll cross the rim road at


the bottom of Kerr Valley, where it comes down from
the rim to get around the cliffs back to the hotel here.
But that’s the only path you’ll see. This is going to be a
hike, not a Sunday School picnic or a young ladies’
seminary out for a walk.”

“Suits me fine.”

“Good!” said his uncle. “I advise you to rest up for it


today, though.”

“I know what I’m going to do today, all right. Anybody


got any dirty clothes?”

“I haven’t got much else,” said Dumplin’.

“Fine. Bring ’em out, all of you. Mrs. Murphy’s on the


job this morning. I’m going to wash things up.”

“Want me to help?” Dumplin’ asked.


“No, you go off with Spider and collect pretty little
flowers. Don’t let ’em bite you, though. They’re wild
flowers, remember.”

Everybody groaned at this pun.

“Mrs. Noah threw a belaying pin at her husband for


making that one on the ark,” said Uncle Billy.

“What’s the difference,” Bennie began, “between Noah’s


ark and Joan of Arc?”

But everybody dove, with another groan, into the tents, 141
to get their dirty clothes.

When everybody but Bennie had gone from camp, he


heated a big pail of water, got out a cake of soap, and
washed all the dirty clothes, hanging them on a tent
rope in the sun to dry. Then he picked up camp as neat
as he could, aired all the bedding and remade the
sleeping bags, and finally went off and hunted up dead
branches for fuel, dragging them back to camp. After
lunch, while the rest were loafing, he took the fishing
rod and sneaked away unseen, went rapidly down the
trail, and working around on the rocks by the shore,
managed to hook three trout. He was just coming up
over the rim with them when Spider and Lester,
wondering at his long absence, had started out to look
for him.

“I sure hate a man who pins roses on himself,” Bennie


remarked, as he was cleaning the fish for dinner, “but I
just can’t help admitting that I’ve been mamma’s little
white-haired boy today. I’ve washed all your dirty shirts
and socks, and I’ve got wood, and I’ve cleaned up
camp, and now I’ve dragged my poor old aching bones
down a thousand feet and back again to catch you three
sweet little fishie-wishies for supper. Won’t somebody
please say ‘Thank you, Bennie, you are a good boy’?”

“Bennie doesn’t like himself a bit, does he?” remarked


Dumplin’, addressing a camp robber in a tree overhead.

“Can’t you prescribe something for his poor old aching


bones, Doc?” asked Mr. Stone.

“Try rubbing ’em with a little fish oil, Bennie,” Spider put 142
in.

“I think I shall prescribe exercise,” Uncle Billy laughed.

“Well, of all the ungrateful bunches, you sure get the


loving cup!” Bennie exclaimed. “I hope you all choke on
a fish bone.”

“The Bible says virtue is its own reward, Bennie,”


remarked Mr. Stone.

“Pretty skinny pickings for some of you guys, then,”


Bennie grinned.

But after supper Uncle Billy strolled out with Bennie to


the point of Victory Rock, to see the lake like a great
blue mirror in the twilight, and he said, quietly:

“We were all much obliged to you for what you did
today. Never mind the joshing.”

Bennie laughed. “Ho! I didn’t mind. Can’t get my goat


so easy as that! Besides, the old Bible is right, I guess.
You don’t do a good turn because you’re going to be
thanked for it. You do it ’cause it makes you feel better
inside.”
“That’s the idea, exactly,” Uncle Billy answered. “Bennie,
you’re a good scout. Your heart is just where it ought to
be every time. The only trouble with you is that you
haven’t quite got your head working yet. If you are
going to amount to anything as a mountaineer or
explorer—anywhere in the wilderness—you’ve got to
learn to use your head, and never bite off more than
you can chew. Will you try to remember that?”

“I sure will, Uncle Bill,” Bennie answered. “I’m awful 143


fresh, I guess, and I talk a lot, but I’m learning right
now, every day. You just sit on me hard when I need it.”

“You needn’t worry about my doing that,” the doctor


grinned.

“No, you’re some sitter,” said Bennie.

144
CHAPTER XV
The Long Hike—The Scouts Find Packing
Grub and Blanket Rolls Up and Down Cliffs
is Hard Work

Bright and early the next morning preparations for the


hike began. This was to be no ordinary jaunt. They
were going out for three days and two nights into a
wilderness, where they would have to make long,
severe climbs up and down treacherous lava ledges;
where they would have to sleep out in the open,
tentless, in a climate where water freezes at night;
where they couldn’t get a mouthful of food except what
they could carry with them.

“You see, boys,” said the doctor, “it’s going to be quite a


problem how to take along enough stuff to keep us
warm, and keep us fed, and yet be able to travel with it
on our backs.”

Each member of the party put in his shoulder pack his 145
own food ration, consisting of tea (because it is lighter
than coffee), some bacon, powdered egg, a little
dehydrated vegetables, a small bag of flour, a small bag
of sugar, a package of bouillon cubes, a can of
preserved fruit, a small can of condensed milk, two
pounds of raisins, two boiled potatoes, and several
cakes of sweet chocolate. In addition, each person put
in two extra pairs of wool socks, and a set of
underclothes. Then, out of their sleeping bags, they
each took a double blanket, and made a blanket roll,
fastening the ends with straps from the motors. Bennie
and Spider each had a boy scout individual cook-kit, in a
khaki case with a shoulder strap. These two kits, with a
tin cup and plate and spoon for the others, and one,
larger frying-pan and kettle carried by Uncle Billy, was
all the cooking outfit they carried. However, the doctor
made everybody carry a canteen, and Bennie, Spider
and Mr. Stone each carried a camera. Everybody had a
sweater, also, and two belt axes were taken. The doctor
had his rope.

When the shoulder packs were on, and the blanket rolls,
and the canteens, and the cameras and camp kits,
everybody was glad enough of the alpenstocks which
the doctor handed around.

“Say, I need this stock to help me stand up,” said


Dumplin’. “I feel like a walking department store.”

“I’ll bet we aren’t toting any more than a soldier has to


carry on a march, at that,” said Spider. “Are we, doctor?”

“No, I don’t believe we’re packing so much,” Uncle Billy


answered. “A gun’s heavier than a stock, too. But it’s
enough. Going to be hot today.”

As the little procession filed past the hotel (which by


now was full of tourists), a crowd came out to watch
them go past.

“Going on a hike, boys?” somebody called out.

“No,” Bennie answered, “we’re going over to Wizard


Island to play tennis.”

146
“Wonder what makes people ask foolish questions?”
Dumplin’ mused.

“It’s the——” Bennie began. Then he caught himself.


“Ha! thought you had me, didn’t you?—it’s the altitude!”

“You chaps won’t talk so much at three o’clock,”


remarked Mr. Stone.

For the first half mile, they had a trail, the trail they had
already taken up Garfield Peak. But half-way up, they
left the trail, and struck right out, without any path at
all, around the tumbled crags of broken lava, and over
the snow-fields and patches of soft pumice soil that
crown this part of the rim on the southeastern side of
the lake. The going was very slow and difficult, up hill
and down, in and out among the rises and dips, with
the sun beating down upon them till their packs and hot
blankets seemed almost unbearable. At first, they could
see the blue lake almost 2,000 feet below them, while
they worked along the crest of Eagle Crags, but after a
while they had to drop down behind the rim to avoid a
climb up Dyar Rock, and lost all sight of it.

After about two miles, they came out on the crest of a


slope that led down to Sun Creek, and saw the Sun
meadows below them. They would have rejoiced at this
sight if they hadn’t also seen the wall of the deep ravine
rising up on the other side, steeper and higher than
under their feet.

“Oh, for the wings of a dove!” sighed Dumplin’.

“Lot o’ good a dove’s wings would do you,” said Bennie.


“Take a dirigible to lift you.”

“A bridge across would do me,” said Spider.


“Meanwhile, we’ll get a little exercise crossing on our 147
own feet,” Uncle Billy smiled. “Come on, now, and watch
your step. Sound your footing with your alpenstocks,
and keep out of line, so if anybody starts a slide, it
won’t spill all the rest.”

They made the descent slowly and painfully over the


first steep pitches, and then more rapidly till they sank
at last on the ground by the water of Sun Creek, which
came down from a snow-bank up on the rim at the
head of the ravine, threw off packs and blankets, and
plunged their mouths in.

“Do we lunch here? I’m hungry——” from Dumplin’.

“We do,” the doctor answered. “And it’s a brief lunch,


too. Everybody take one handful of raisins, and half a
cake of chocolate.”

“Oh, gee, is that all?” cried Dumplin’.

“That’s all. John Muir used to climb for two or three


days in the high Sierras on a pocketful of raisins, and
didn’t even carry a blanket. Come on, get busy.”

Everybody obeyed, and the doctor saw to it that they


didn’t take too many of their raisin supply, either.

“I consider this a Lucullan feast,” remarked Mr. Stone.

“Whatever that is,” said Bennie. “If you mean some


banquet, I’m right along with you. Always did like these
seven-course dinners.”

“Anyhow, it won’t take long to wash the dishes,” Spider


reflected.
As soon as the raisins and chocolate were eaten, and 148
the canteens refilled, they picked up their packs and
blankets again and put them on.

“Gosh! mine weighs more’n it did,” said Bennie.


“Somebody’s put something into it.”

“Mine, too.”

“Mine, too.”

“Mine, too.”

“Wait till they get really heavy before you kick,” said
Uncle Billy. “Forward, march!”

The thousand-foot wall of the Sun Creek ravine which


faced them was just about the height from the lake to
the rim at the hotel, but it was not so steep, except for
a little distance at the start. On the other hand, there
was no trail at all, no sign that any other human being
had ever been up it, and when the going was not amid
treacherous lava fragments which broke if you put your
weight on them, it was over soft pumice into which your
feet sank deep, and then began to slide backwards.
Finally Bennie took his uncle’s rope and scrambled up
ahead with it, till he could find anchorage, so the rest
could have its help. When he was fagged, somebody
else took a turn. It took them more than an hour to
make the half mile up the wall, and at the top they
pitched off their packs and blankets, their shoulders and
backs dripping wet with perspiration, and everybody set
his mouth to his canteen and drank.

After a rest, they crossed Dutton ridge, a mile of broken 149


going, and then began to descend into the next ravine,
called Kerr Valley, which is the deepest ravine on the
slopes of old Mount Mazama, and lies right at the foot
of Scott Peak. The descent was not dangerously steep
till the last three hundred feet, and there they used the
rope again to help them.

As they came out at last into the mile wide ravine of


Kerr Valley, out of which the snow had pretty well
melted except under the trees, and in which the wild
flowers were springing up, they saw where the rim road
came down from the rim and descended the valley to
get around the mass of ledges and ravines they had
been crossing. It was now three o’clock, and, as Mr.
Stone had predicted, nobody was saying much.

They could see the round, dome-like pile of Scott’s


Peak, directly across the valley, and Bennie did ask how
far it was from there to the top.

“Thinking of keeping on up today?” his uncle asked.

“Aw, don’t rub it in,” said Bennie. “I couldn’t climb an


ant-hill now.”

“Well, a mile more will take us across the valley to


water,” his uncle laughed. “Guess we can all stick that
out.”

On the other side of the valley, across the still deserted


and useless rim road, they found a stream, called Sand
Creek, which came down, the doctor said, from a spring
on the cliffs of Scott, just above them.

Here they dumped their packs again, stripped off their


clothes, and the three boys were only restrained by
main force from falling in.

150
“You’re too hot to go in that ice water,” the doctor said,
grabbing Bennie. “Wash your feet all you want to, and
splash yourselves.”

After the wash, they put on their dry underclothes, and


spread the other set in the sun (which was fast
dropping down the west), and then set about making
camp.

“I say we find a straight-faced rock to build the fire


against,” Bennie suggested, “so it will throw the heat all
one way, and we can sleep around it in a half circle, out
of the wind.”

“I move we find a place where the ground is dry and a


snow-drift hasn’t just melted off it,” added Spider.

“And where it’s nice and soft,” added Dumplin’.

“And where it’s near wood,” added Mr. Stone.

“Maybe you’d like a room with a bath, and have your


breakfast brought up to you,” Uncle Billy laughed. “Well,
go to it. Find your rock, Bennie. Whoever’s got the axes,
cut wood, and lots of it.”

A smooth place was finally found in the lee of a block of


lava, some little way from the stream, but near a patch
of firs and hemlocks, where there was plenty of dead
wood. Dumplin’ started stoning up a big fireplace, while
the two scouts chopped wood and Mr. Stone brought
water in the big kettle and two little kettles of the camp
kits and in the canteens, and the doctor mixed a
pancake batter, and made the bacon and egg powder
ready to cook, and peeled one of the two potatoes in
each pack.
As the sun dropped down behind the high ridge to the 151
west, a chill almost immediately came into the air. In
less than an hour everybody, who had been so hot all
day, was thinking about putting on his sweater. But the
fire burned brightly, the potatoes smelled delicious in
the frying-pan, and as soon as they were done, the
smell of bacon and eggs rose from the same pan. Water
for bouillon tablets and tea boiled in the kettles. The
food disappeared down hungry mouths, and every plate
was scraped clean, ready for the pancakes to follow.
They had no syrup to eat on the cakes, but nobody
seemed to mind that. After the cakes, they drew lots to
see whose can of fruit should be opened, because the
lucky one would have so much less to carry in his pack.
Dumplin’ won, to his delight. His can was peaches, and
how good they tasted—after the can was finally pried
open, with the aid of a scout ax, a stone and a broken
jack-knife blade!

Then the dishes were washed, more wood heaped on


the fire, sweaters donned, and in the gathering
darkness, and the utter silence of the wilderness, the
five hikers sat in a close ring before the fire, and relaxed
their weary muscles.

“Well, I’m glad I lugged that grub,” said Bennie. “’Bout


three o’clock, though, I would have dumped the whole
pack over the rim for two cents.”

“Me, too,” said Dumplin’. “Gosh, this hiking is hard work!


Don’t see much adventure in it. Here we’ve come about
eight or nine miles, and took us all day, and nothin’
happened.”

“What did you expect to happen?” his father asked. 152


“Expect to meet an elephant, or have the mountain
erupt?”
“Gee, I think it’s a wonderful adventure!” Spider
exclaimed. “It’s been a kind of battle. I—I can’t say
what I mean, but it was just the same when Bennie and
I were getting up Llao Rock. We were sort of fighting
up. Only instead of fighting another man, who tries to
hit you back, you are fighting just—just—well, just the
wilderness.”

“And it’s against you all the time,” said Mr. Stone.

Bennie had grown very thoughtful. “No, it’s not against


you all the time,” he said. “Excuse me for contradicting,
Mr. Stone. I don’t mean to be fresh. But the way I feel is
that it’s against you if you don’t know how to meet it,
but if you do know, it is always kind of putting out
things to help you.”

“Such as——?” asked his uncle.

“Well, such as dead wood for a fire, and a chimney to


crawl up in, if you know how, when you strike a
precipice, and maybe food to eat. I bet we could find
food in the roots of some of these wild flowers, if we
had to.”

“Give me bacon,” said Dumplin’.

“Gee, Dump, you go to church behind your belt buckle,”


said Bennie scornfully. “But I’m with Spider, though, that
a hike like this is a regular adventure, ’cause it’s a sort
of fight all the way, and it’s all up to you whether you
get through or not. Gee, I wish I was an explorer!”

Uncle Billy smiled. “We may get a little exploring yet, 153
before we get back to Portland. You never can tell. Well,
who’s going to sleep tonight?”
“I guess we all are.”

“Till the cold wakes us up,” said Mr. Stone.

“And a rock grows up through our shoulder blades,” said


Spider.

“Whenever that happens, put some more wood on the


fire,” said Uncle Billy.

Then everybody rolled up in his blanket, feet to the fire,


with his pack for a pillow, and in spite of the bare
ground, in place of a nice air mattress, was soon asleep.

154
CHAPTER XVI
The Climb Up Scott Peak—Bennie Begins
Work for a Merit Badge for Hiking

But the night wasn’t very old before everybody had


discovered that there is a big difference between
sleeping on an air mattress, inside four or five blankets
in a sleeping bag, under a tent, and sleeping on the
bare ground, in one blanket. Bennie and Spider had
slept on the bare ground, to be sure, many a time on
their scout hikes at home, but that was always in
summer, when it was warm. To be sure, it was summer
now, but they were more than 6,000 feet up, on the
crest of the Cascades, with snow all around them.

It seemed to Bennie as if he had been asleep only


fifteen minutes, when he was waked up by cold. He
didn’t fully wake up at first, but only just enough to feel
the wind getting down around his neck, and to feel his
whole body stiff and uncomfortable. He yanked the
blanket tighter around him, and tried to go to sleep
again. But, instead, he woke up still more.

At last he was awake enough to prop himself up on one 155


elbow, and look at the fire. It had burned down to a few
glowing embers in the stone pit against the lava block.
Overhead the stars were extremely bright, but the night
itself seemed dark. There wasn’t a sound in the world.
Yes! Hark! Bennie’s ears grew alert in the darkness. Far
off he heard a roar, starting low, then growing louder,
then dying away. At first he couldn’t understand it; then
he realized it was a landslide somewhere on a steep
slope, perhaps over on the rim of the lake a mile and a
half away. He listened again, but there was no further
sound—only a whisper of wind in the fir trees close by,
and the gentle run of the water in the creek. Suddenly
Bennie realized that he was in the very heart of the
wilderness, that except for his four companions asleep
beside him, there wasn’t a human being within a day’s
hike. He also realized that if he didn’t put some wood on
the fire pretty quick, it would be out entirely.

So he crawled out of his blanket as gently as he could,


and tried to make no noise as he put on more fuel. He
blew on the coals till the new wood caught, and then
turned his cold back to the flames. As he did so, he saw
Spider’s eyes open in the sudden light. Spider blinked a
second, and then sat up.

“Hello,” he whispered. “You cold?”

“Gosh, I was most frozen,” Bennie whispered back.

“Me, too. Been sleeping on a rock, right in the middle of


my hip. Ow, it’s sore!”

Spider now got up also, and came close to the fire.

When they were warmed up again, they lay down once 156
more, and managed to doze off. But long before
morning, Bennie woke to see first Mr. Stone and then
his uncle putting more wood on the fire. It wasn’t yet
dawn—just the first hint of lightness in the sky—when
Bennie finally woke up so cold and so stiff and
uncomfortable from the hard ground, that further sleep
seemed impossible. He was just rousing himself to put
on more wood when he heard Spider stir, and then sit
up.

“I’m going to stay up,” he whispered. “Let’s take a trot


around to get warm.”

Spider rose, and after building up the fire and huddling


over it a few minutes, they walked away from camp.

“Let’s go up the valley to the rim,” Spider said. “We can


go on the rim road, and have easy walking. Gee, I’d like
to run all the way, and get up some circulation.”

They set out rapidly, and reached the rim in fifteen


minutes. It was lighter now, and they could see plainly.
The lake at this point was only 500 feet below them, for
they had come out on the lowest point on the entire
rim. But, even so, they seemed to be looking down into
the clouds. They looked up into clouds, too, whole
masses of clouds around the peak of Scott, of Dutton
Cliff, of Garfield. Then the daylight increased rapidly, the
clouds began mysteriously to disappear, holes came in
them showing the blue water—and suddenly Spider
grabbed Bennie’s arm and pointed half-way down the
side.

Bennie looked, and saw a small deer—a mule deer, as it


is called—coming rapidly up the steep incline, directly
toward them! He could not get their scent from so far
below, and he quite evidently hadn’t seen them. On he
came, bounding easily up the incline, where a man
would have toiled breathlessly.

“Wow! I’d like to be able to go up a mountain like that!” 157


Bennie exclaimed.
Almost at his first word, they saw the deer’s big ears
prick up. He landed stock still and rigid, and raised his
eyes. Then he saw the two boys above him, and with a
single bound, so quick the scouts couldn’t detect how
he made the turn, he was off at right angles, along the
slope. Working upward as he leapt along, he reached
the rim three hundred yards away from them, and
disappeared like smoke into a stand of fir.

“What a shot!” breathed Bennie.

“Aw, you couldn’t have hit him in a year,” Spider


laughed.

“Why couldn’t I?”

“First place, you can’t shoot well enough, and second


place I’d have knocked up your gun,” said Spider. “I
wouldn’t shoot a deer as long as I had anything else to
eat.”

“He was kind o’ pretty,” Bennie agreed.

“’Tisn’t that so much. But he’s wild. He’s part of the


wilderness. He belongs to it. Killing a deer is just as bad
as knocking off the top of a mountain, or spoiling all the
forest trees.”

“Maybe you’re right,” Bennie admitted. “But how about


going back and getting grub?”

The sun was up when they reached camp again, and so


were the other three campers.

“’Smatter, boys?” asked Mr. Stone. “Getting an appetite


before breakfast?”

“So cold we couldn’t sleep,” they answered.


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

You might also like