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

Obscure Topics In Cocoa Objectivec Mattt Thompson pdf download

The document discusses 'Obscure Topics in Cocoa Objective-C' by Mattt Thompson, which serves as a technical manual for Objective-C development, covering various aspects of the language and its frameworks. It emphasizes the importance of code organization, understanding nil values, and the nuances of boolean types in Objective-C. The book aims to deepen the reader's appreciation for coding craftsmanship and provides insights into effective programming practices.

Uploaded by

geovissatiko
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)
7 views77 pages

Obscure Topics In Cocoa Objectivec Mattt Thompson pdf download

The document discusses 'Obscure Topics in Cocoa Objective-C' by Mattt Thompson, which serves as a technical manual for Objective-C development, covering various aspects of the language and its frameworks. It emphasizes the importance of code organization, understanding nil values, and the nuances of boolean types in Objective-C. The book aims to deepen the reader's appreciation for coding craftsmanship and provides insights into effective programming practices.

Uploaded by

geovissatiko
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

Obscure Topics In Cocoa Objectivec Mattt

Thompson download

https://ebookbell.com/product/obscure-topics-in-cocoa-objectivec-
mattt-thompson-37518952

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.

Nshipster Obscure Topics In Cocoa Objective C Thompson Mattt

https://ebookbell.com/product/nshipster-obscure-topics-in-cocoa-
objective-c-thompson-mattt-36752360

Nshipster Obscure Topics In Cocoa Objective C Thompson Mattt


Chenjin5com

https://ebookbell.com/product/nshipster-obscure-topics-in-cocoa-
objective-c-thompson-mattt-chenjin5com-36752362

Obscure Invitations The Persistence Of The Author In Twentiethcentury


American Literature Benjamin Widiss

https://ebookbell.com/product/obscure-invitations-the-persistence-of-
the-author-in-twentiethcentury-american-literature-benjamin-
widiss-51932698

Obscure Locks Simple Keys The Annotated Watt Chris Ackerley

https://ebookbell.com/product/obscure-locks-simple-keys-the-annotated-
watt-chris-ackerley-51969942
Obscure Hands Trusted Men Textualization The Office Of The City Scribe
And The Written Management Of Information And Communication Of The
Council Of Reval Tallinn Before 1460 Tapio Salminen

https://ebookbell.com/product/obscure-hands-trusted-men-
textualization-the-office-of-the-city-scribe-and-the-written-
management-of-information-and-communication-of-the-council-of-reval-
tallinn-before-1460-tapio-salminen-36441432

Obscure Objects Of Desire Surrealism Fetishism And Politics New


Johanna Malt

https://ebookbell.com/product/obscure-objects-of-desire-surrealism-
fetishism-and-politics-new-johanna-malt-12261758

Obscure Krista Walsh

https://ebookbell.com/product/obscure-krista-walsh-48726246

Obscure Locks Simple Keys The Annotated Watt 1st Edition Chris
Ackerley

https://ebookbell.com/product/obscure-locks-simple-keys-the-annotated-
watt-1st-edition-chris-ackerley-11332606

Obscure Mosaic Chronicles Book Seven Pearson Andrea Pearson

https://ebookbell.com/product/obscure-mosaic-chronicles-book-seven-
pearson-andrea-pearson-23978426
first edition

nshipster

NS
obscure topics
in cocoa &
objective-c
mattt thompson
!
Mattt Thompson

NSHipster: Obscure
Topics In Cocoa &
Objective-C
!
!
!
!
!
!
!
!
!
!
!
!
Copyright © 2013 Mattt Thompson
All rights reserved

Illustrated by Conor Heelan

ISBN 978-0-9912182-1-9

NSHipster
Portland, Oregon
http://nshipster.com
Table of Contents

Objective-C 10
#pragma 11
nil / Nil /
NULL / NSNull 16
BOOL / bool /
Boolean / NSCFBoolean 20
Equality 24
Type Encodings 35
C Storage Classes 41
@ 47
__attribute__ 61
instancetype 71
NS_ENUM &
NS_OPTIONS 74
Foundation &
CoreFoundation 79
Key-Value Coding
Collection Operators 80
Key-Value Observing 86
NSError 99
NSOperation 108
NSSortDescriptor 115
NSPredicate 120
NSExpression 133
NSFileManager 141
NSValue 153
NSValueTransformer 156
NSDataDetector 160
CFBag 166
NSCache 171
NSIndexSet 174
NSOrderedSet 176
NSHashTable &
NSMapTable 181
UIKit 188
UIMenuController 189
UILocalizedIndexedCollation 197
UIAppearance 204

Localization,
Internationalization &
Accessibility 209
NSLocale 210
NSLocalizedString 217
UIAccessibility 222
NSFormatter 232
CFStringTransform 241
NSLinguisticTagger 246

API Design 254


The Law of Demeter 255
The Principle of
Least Surprise 265
Naming 269
Community 273
Stewardship 274
Empathy 284
Introduction

To be an NSHipster is to care deeply about the craft of writing


code. In cultivating a deep understanding and appreciation of
Objective-C, its frameworks and ecosystem, one is able to
create apps that delight and inspire users.

This book takes a structured approach to learning Objective-


C development, starting from the language and system
frameworks, and moving onto high-level concerns, like
internationalization, design, and community. It is as much a
technical manual as it is a meditation on the practice of
coding.

I hope that by reading this, you will share in the excitement of


discovering new insights, and taking pride in your work.

9
Objective-C

10
#pragma

#pragma declarations are a mark of craftsmanship in


Objective-C. Although originally used to make source code
portable across different compilers, the Xcode-savvy coder
uses #pragma declarations to very different ends.

In this modern context, #pragma skirts the line between


comment and code. As a preprocessor directive, #pragma
evaluates at compile-time, but unlike other macros, #pragma
is not used to change the runtime behavior of an application.
Instead, #pragma declarations are used by Xcode to
accomplish two primary tasks: organizing code and inhibiting
compiler warnings.

Organizing Your Code


Code organization is a matter of hygiene. How you structure
your code is a reflection on you and your work. A lack of
convention and internal consistency indicates either
carelessness or incompetence—and worse, makes a project
difficult to maintain and collaborate on.

11
Good habits start with #pragma mark:

@implementation ViewController
- (id)init {
...
}
#pragma mark - UIViewController
- (void)viewDidLoad {
...
}
#pragma mark - IBAction
- (IBAction)cancel:(id)sender {
...
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{

}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
}

Use #pragma mark in your @implementation to divide code


into logical sections. Not only do these sections make it easier
to read through the code itself, but it also adds visual cues to
the Xcode source navigator.

12
#pragma mark declarations starting with a dash (-) are preceded
with a horizontal divider.

Start by grouping methods according to their originating


class. For example, an NSInputStream subclass would have a
group marked NSInputStream, followed by a group marked
NSStream.

Things like IBAction outlets, or methods corresponding to


target / action, notification, or KVO selectors probably
deserve their own sections as well.

Finally, if a class conforms to any @protocols, group all of the


methods from each protocol together, and add a #pragma
mark header with the name of that protocol.

Your code should be clean enough to eat off of. So take the


time to leave your .m files better than how you found them.

Inhibiting Warnings
What's even more annoying than poorly-formatted code?
Code that generates warnings. Especially 3rd-party code.
There are few things as irksome as that one vendor library that
takes forever to compile, and finishes with 200+ warnings.
Even shipping code with a single warning is in poor form.

13
Try setting the -Weverything flag and checking the "Treat Warnings
as Errors" box your build settings.
This turns on Hard Mode in Xcode.

But sometimes there's no avoiding compiler warnings.


Deprecation notices and retain-cycle false positives are two
common examples where this might happen. In those rare
cases where you are absolutely certain that a particular
compiler warning should be inhibited, #pragma can be used
to suppress them:

#pragma clang diagnostic push


#pragma clang diagnostic ignored "-Wunused-variable"
OSStatus status = SecItemExport(...);
NSCAssert(status == errSecSuccess, @"%d", status);
#pragma clang diagnostic pop

This code sample is an example of an otherwise unavoidable


warning from the static analyzer. When compiling in Release
mode, assertions are ignored, so Clang warns that status is an
unused variable.

Using #pragma clang diagnostic push/pop, you can tell the


compiler to ignore certain warnings for a particular section of
code (the original diagnostic settings are restored with the
final pop).

Just don't use #pragma as a way to sweep legitimate warnings


under the rug—it will only come back to bite you later.

14
You can read more about the LLVM's use of #pragma in the Clang
Compiler User's Manual.

Like a thrift store 8-track player turned into that lamp in the
foyer, #pragma remains a curious vestige of the past: Once the
secret language of compilers, it is now re-purposed to better-
communicate intent to other programmers.

How delightfully vintage!

15
nil / Nil /
NULL / NSNull

Understanding the concept of nothingness is as much a


philosophical issue as it is a pragmatic one. We are inhabitants
of a universe made up of somethings, yet reason in a logical
universe with existential uncertainties. As a physical
manifestation of a logical system, computers are faced with
the intractable problem of how to represent nothing with
something.

In Objective-C, there are several different varieties of nothing.

C represents nothing as 0 for primitive values, and NULL for


pointers (which is equivalent to 0 in a pointer context).

Objective-C builds on C's representation of nothing by


adding nil. nil is an object pointer to nothing. Although
semantically distinct from NULL, they are equivalent to one
another.

16
On the framework level, Foundation defines the NSNull class,
which defines a single class method, +null, which returns a
singleton NSNull instance. NSNull is different from nil or
NULL, in that it is an actual object, rather than a zero value.

Additionally, in Foundation/NSObjCRuntime.h, Nil is


defined as a class pointer to nothing. This lesser-known title-
case cousin of nil doesn't show up much very often, but it's at
least worth noting.

There's Something About nil


Newly-alloc'd NSObjects start life with their contents set to 0.
This means that all pointers an object has to other objects
begin as nil, so it's unnecessary to, for instance, set
self.association = nil in init methods.

Perhaps the most notable behavior of nil, though, is that it


handles messages sent to it.

In other languages, like C++, sending a message to a null


pointer would crash a program, but in Objective-C, invoking
a method on nil returns a zero value. This greatly simplifies
expressions, as it obviates the need to check for nil before
doing anything:

17
// For example, this expression...
if (name != nil && [name isEqualToString:@"Steve"])
{ ... }
!
// ...can be simplified to:
if ([name isEqualToString:@"steve"]) { ... }

Being aware of how nil works in Objective-C allows this


convenience to be a feature, rather than a source of hard-to-
find bugs.

Guard against cases where nil values are unwanted, either by


returning early, or adding a NSParameterAssert to throw an
exception.

NSNull: Something for Nothing


NSNull is used throughout Foundation and other system
frameworks to skirt around the limitations of collections like
NSArray and NSDictionary, which cannot contain nil values.
NSNull effectively boxes NULL or nil values, so that they can
be stored in collections:

18
NSMutableDictionary *mutableDictionary =
[NSMutableDictionary dictionary];
!
mutableDictionary[@"someKey"] = [NSNull null];
// Sets value of NSNull singleton for `someKey`
!
NSLog(@"Keys: %@", [mutableDictionary allKeys]);
// @[@"someKey"]

!
So to recap, here are the four values representing nothing that
every Objective-C programmer should know about:

Symbol Value Meaning

NULL (void *)0 literal null value for C pointers

nil (id)0 literal null value for Objective-C objects

Nil (Class)0 literal null value for Objective-C classes

NSNull [NSNull null] singleton object used to represent null

19
BOOL / bool /
Boolean /
NSCFBoolean

Truth, Vēritās: The entire charter of Philosophy is founded


upon the pursuit of it, and yet its exact meaning and
implications still elude us.

Does truth exist independently, or is it defined contingently?


Can a proposition be at once both true and false?
Is there absolute truth in anything, or is everything relative?

Once again, encoding our logical universe into the cold,


calculating bytecode of computers forces us to deal with these
questions one way or another. And as you'll see from our
discussion of boolean types in C & Objective-C, truth is
indeed stranger than fiction.

Objective-C defines BOOL to encode truth value. It is a


typedef of a signed char, with the macros YES and NO to
represent true and false, respectively.

20
Boolean values are used in conditionals, such as if or while
statements, to conditionally perform logic or repeat
execution. When evaluating a conditional statement, the value
0 is considered "false", while any other value is considered
"true". Because NULL and nil have a value of 0, they are
considered "false" as well.

In Objective-C, use the BOOL type for parameters,


properties, and instance variables dealing with truth values.
When assigning literal values, use the YES and NO macros.

The Wrong Answer to the Wrong Question


Novice programmers often include an equality operator when
evaluating conditionals:

if ([a isEqual:b] == YES) { ... }

Not only is this unnecessary, but depending on the left-hand


value, it may also lead to unexpected results. Consider this
function, which returns whether two integers are different:

static BOOL different (int a, int b) {


return a - b;
}

A programmer might take some satisfaction in the clever


simplicity of this approach: indeed, two integers are equal if
and only if their difference is 0.

21
However, because BOOL is typedef 'd as a signed char on 32-
bit architectures, this will not behave as expected:

different(11, 10) // YES


different(10, 11) // NO (!)
different(512, 256) // NO (!)

Now, this might be acceptable for JavaScript, but Objective-C


don't suffer fools gladly.

On a 64-bit iOS, BOOL is defined as a bool, rather than signed char,


which precludes the runtime from these type conversion errors.

Deriving truth value directly from an arithmetic


operation is never a good idea. Use the == operator, or cast
values into booleans with the ! (or !!) operator.

The Truth About NSNumber and BOOL


Pop quiz: what is the output of the following expression?

NSLog(@"%@", [@(YES) class]);

The answer:

__NSCFBoolean

Wait, what?

22
All this time, we've been led to believe that NSNumber boxes
primitives into an object representation. Any other integer or
float derived NSNumber object shows its class to be
__NSCFNumber. What gives?

NSCFBoolean is a private class in the NSNumber class cluster.


It is a bridge to the CFBooleanRef type, which is used to wrap
boolean values for Core Foundation collections and property
lists. CFBoolean defines the constants kCFBooleanTrue and
kCFBooleanFalse. Because CFNumberRef and
CFBooleanRef are different types in Core Foundation, it
makes sense that they are represented by different bridging
classes in NSNumber.

!
Wrapping things up, here is a table with the truth types and
values in Objective-C:

Name Type Header True False

BOOL signed char / bool objc.h YES NO

bool _Bool (int) stdbool.h TRUE FALSE

Boolean unsigned char MacTypes.h TRUE FALSE

NSNumber __NSCFBoolean Foundation.h @(YES) @(NO)

23
Equality

The concept of equality is a central point of debate and


inquiry in philosophy and mathematics, with far-reaching
implications for matters of ethics, justice, and public policy.

From an empiricist perspective of the universe, two objects


are equal if they are indistinguishable from one another in
measurable observations. Egalitarians, operating on a human
scale, hold that individuals should be considered equal
members of the societal, economic, political, and judicial
systems they inhabit.

It is the task of programmers to reconcile our logical and


physical understanding of equality with the semantic
domains we model.

Equality & Identity


First and foremost, it is important to make a distinction
between equality and identity.

24
Two objects may be equal or equivalent to one another, if they
share a common set of properties. Yet, those two objects may
still be thought to be distinct, each with their own identity.

In code, an object's identity is tied to its memory address.

NSObject tests equality with another object with the method


isEqual:. In its base implementation, an equality check is
essentially a test for identity:

@implementation NSObject (Approximate)


- (BOOL)isEqual:(id)object {
return self == object;
}
@end

isEqual
Subclasses of NSObject implementing their own isEqual:
method are expected to do the following:

• Implement a new isEqualToClassName: method, which


performs the meaningful value comparison.

• Override isEqual: to make class and object identity checks,


falling back on the aforementioned class comparison
method.

• Override hash, which will be described in the next section.

25
For container classes like NSArray, NSDictionary, and
NSString, equality deep equality comparison, testing equality
for each member in pairwise fashion:

@implementation NSArray (Approximate)


- (BOOL)isEqualToArray:(NSArray *)array {
if (!array || [self count] != [array count]) {
return NO;
}
!
for (NSUInteger idx = 0; idx < [array count]; idx++) {
if (![self[idx] isEqual:array[idx]]) {
return NO;
}
}
!
return YES;
}
!
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
!
if (![object isKindOfClass:[NSArray class]]) {
return NO;
}
!
return [self isEqualToArray:(NSArray *)object];
}
@end

!
26
isEqualTo____:
The following NSObject subclasses in Foundation have
custom equality implementations, with the corresponding
method:

NSAttributedString -isEqualToAttributedString:

NSData -isEqualToData:

NSDate -isEqualToDate:

NSDictionary -isEqualToDictionary:

NSHashTable -isEqualToHashTable:

NSIndexSet -isEqualToIndexSet:

NSNumber -isEqualToNumber:

NSOrderedSet -isEqualToOrderedSet:

NSSet -isEqualToSet:

NSString -isEqualToString:

NSTimeZone -isEqualToTimeZone:

NSValue -isEqualToValue:

When comparing two instances of any of these classes, one is


encouraged to use these high-level methods rather than
isEqual:.

However, our theoretical implementation is yet incomplete.


Let's turn our attention now to hash, after a quick detour to
clear something up about NSString.

27
The Curious Case of NSString Equality
As an interesting aside, consider the following:

NSString *a = @"Hello";
NSString *b = @"Hello";
BOOL wtf = (a == b); // YES (!)

To be perfectly clear: the correct way to compare two NSString


objects is -isEqualToString:. Under no circumstances should
NSString objects be compared with the == operator.

So what's going on here? Why does this work, when the same
code for NSArray or NSDictionary literals wouldn't do this?

It all has to do with an optimization technique known as


string interning, whereby one copy of immutable string
values. NSString *a and *b point to the same copy of the
interned string value @"Hello".

Again, this only works for statically-defined, immutable


strings. Constructing identical strings with NSString
+stringWithFormat: will objects with different pointers.

Interestingly enough, Objective-C selector names are also


stored as interned strings in a shared string pool.

28
Hashing
The primary use case of object equality tests for object-
oriented programming is to determine collection
membership. To keep this fast, subclasses with custom
equality implementations are expected to implement hash:

• Object equality is commutative


([a isEqual:b] [b isEqual:a])

• If objects are equal, their hash values must also be equal


([a isEqual:b] [a hash] == [b hash])

• However, the converse does not hold: two objects need not
be equal in order for their hash values to be equal
([a hash] == [b hash] ¬ [a isEqual:b])

Now for a quick flashback to Computer Science 101:

Hashing Fundamentals
A hash table is a fundamental data structure in programming,
and it's what enables NSSet & NSDictionary to have fast
(O(1)) lookup of elements.

We can best understand hash tables by contrasting them to


arrays.

29
Arrays store elements in sequential indexes, such that an
Array of size n will have slots at positions 0, 1, up to n - 1. To
determine where an element is stored in the array (if at all),
each position would have to be checked one-by-one (unless
the array happens to be sorted, but that's another story).

Hash Tables take a slightly different approach. Rather than


storing elements sequentially (0, 1, ..., n-1), a hash table
allocates n positions in memory, and uses a function to
calculate a position within that range.

A hash function is deterministic, and a good hash function


generates values in a relatively uniform distribution without
being too computationally expensive. A hash collision occurs
when two different objects calculate the same hash value.
When this happens, the hash table will seek from the point of
collision and place the new object in the first open slot. As a
hash table becomes more congested, the likelihood of
collision increases, which leads to more time spent looking
for a free space.

One of the most common misconceptions about


implementing a custom hash function is that hash values
must be distinct. This often leads to needlessly complicated
implementations, with incantations copied from Java
textbooks. In reality, a simple XOR over the hash values of
critical properties is sufficient most of the time.

30
The trick is in determining the critical values of an object.

For an NSDate, the time interval since a reference date would


be enough to go on:

@implementation NSDate (Approximate)


- (NSUInteger)hash {
return abs([self timeIntervalSinceReferenceDate]);
}

For a UIColor, a bit-shifted sum of RGB components would


be a convenient calculation:

@implementation UIColor (Approximate)


- (NSUInteger)hash {
CGFloat red, green, blue;
[self getRed:&red green:&green blue:&blue alpha:nil];
return ((NSUInteger)(red * 255) << 16) +
((NSUInteger)(green * 255) << 8) +
(NSUInteger)(blue * 255);
}
@end

Implementing -isEqual: and hash


in a Subclass
Bringing it all together, here's how one might override the
default equality implementation for a subclass:

31
Person.h

@interface Person
@property NSString *name;
@property NSDate *birthday;
!
- (BOOL)isEqualToPerson:(Person *)person;
@end

Person.m

@implementation Person
- (BOOL)isEqualToPerson:(Person *)person {
if (!person) {
return NO;
}
!
BOOL haveEqualNames = (!self.name && !person.name) ||
[self.name isEqualToString:person.name];

BOOL haveEqualBirthdays =
(!self.birthday && !person.birthday) ||
[self.birthday isEqualToDate:person.birthday];

return haveEqualNames && haveEqualBirthdays;


}
!

32
#pragma mark - NSObject
!
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
!
if (![object isKindOfClass:[Person class]]) {
return NO;
}
!
return [self isEqualToPerson:(Person *)object];
}
- (NSUInteger)hash {
return [self.name hash] ^ [self.birthday hash];
}
@end

Don't Overthink It
While all of this has been an interesting exercise in
epistemology and computer science, there is one lingering
pragmatic detail:

You don't usually need to implement this.

There are many situations where the default identity check


(two variables point to the same address in memory) is
indeed desirable behavior. Such is a consequence of data
modeling being inherently limited.

33
Take, for instance, the previous example of the Person class.
It's not inconceivable that two individuals would share a
common name and birthday. In reality, this crisis of identity
would be resolved by additional information, whether it's a
system-dependent identifier like a Social Security Number,
their parents' identities, or any other physical attributes.

Ultimately, it's up to the abstraction to isolate the significant,


identifying features that the system cares about, and disregard
the rest.

!
Hopefully, after all of this explanation, we all stand with equal
footing on this slippery subject.

As humans, we strive to understand and implement equality


in our society and economy; in the laws and leaders that
govern us; in the understanding that we extend to one
another as we journey through existence. May we continue
towards that ideal, where an individual is judged by the
contents of their character, just as we judge a variable by the
contents of its memory address.

34
Type Encodings

Number stations, numerology, hieroglyphs, hobo codes;


there is something truly fascinating about information that
hides in plain sight. Though hidden messages are rarely useful
or particularly interesting in and of themselves, it's the thrill
of the hunt that piques our deepest curiosities.

The secret codes of Objective-C are Type Encodings.

!
@encode, one of the @ Compiler Directives, returns a C string
that encodes the internal representation of a given type, for
example, @encode(int) → i. This is similar to the ANSI C
typeof operator.

Apple's Objective-C runtime uses type encodings internally


to help facilitate message dispatching.

Here's a rundown of the Objective-C Type Encodings:

35
Code Meaning

c A char

i An int

s A short

l A longl is treated as a 32-bit quantity on 64-bit


programs.

q A long long

C An unsigned char

I An unsigned int

S An unsigned short

L An unsigned long

Q An unsigned long long

f A float

d A double

B A C++ bool or a C99 _Bool

v A void

* A character string (char *)

@ An object (whether statically typed or typed id)

# A class object (Class)

: A method selector (SEL)

[array type] An array

{name=type...} A structure

(name=type...) A union

bnum A bit field of num bits

^type A pointer to type

? An unknown type (among other things, this code is


used for function pointers)

36
Of course, charts are fine, but experimenting in code is even
better:

NSLog(@"int : %s", @encode(int));


NSLog(@"float : %s", @encode(float));
NSLog(@"float * : %s", @encode(float*));
NSLog(@"char : %s", @encode(char));
NSLog(@"char * : %s", @encode(char *));
NSLog(@"BOOL : %s", @encode(BOOL));
NSLog(@"void : %s", @encode(void));
NSLog(@"void * : %s", @encode(void *));
!
NSLog(@"NSObject * : %s", @encode(NSObject *));
NSLog(@"NSObject : %s", @encode(NSObject));
NSLog(@"[NSObject] : %s", @encode(typeof([NSObject
class])));
NSLog(@"NSError ** : %s", @encode(typeof(NSError **)));
!
int intArray[5] = {1, 2, 3, 4, 5};
NSLog(@"int[] : %s", @encode(typeof(intArray)));
!
float floatArray[3] = {0.1f, 0.2f, 0.3f};
NSLog(@"float[] : %s", @encode(typeof(floatArray)));
!
typedef struct _struct {
short a;
long long b;
unsigned long long c;
} Struct;
NSLog(@"struct : %s", @encode(typeof(Struct)));

37
Result:

int : i
float : f
float * : ^f
char : c
char * : *
BOOL : c
void : v
void * : ^v
!
NSObject * : @
NSObject : #
[NSObject] : {NSObject=#}
NSError ** : ^@
!
int[] : [5i]
float[] : [3f]
struct : {_struct=sqQ}

There are some interesting takeaways from this:

• Whereas the standard encoding for pointers is a preceding


^, char * gets its own code: *. This makes sense conceptually,
since C strings are thought to be entities in and of
themselves, rather than a pointer to something else.

• BOOL is c, rather than i, as one might expect. Reason


being, char is smaller than an int, and when Objective-C
was originally designed in the 80's, bits (much like the US
Dollar) were more valuable than they are today.

38
• Passing NSObject directly yields #. However, passing
[NSObject class] yields a struct named NSObject with a
single class field. That is, of course, the isa field, which all
NSObject instances have to signify their type.

Method Encodings
As mentioned in Apple's "Objective-C Runtime
Programming Guide", there are a handful of type encodings
that are used internally, but cannot be returned with @encode.

These are the type qualifiers for methods declared in a


protocol:

Code Meaning

r const

n in

N inout

o out

O bycopy

R byref

V oneway

Anyone familiar with NSDistantObject should recognize


these as a vestige of Distributed Objects.

39
Although it has fallen out of fashion in the age of iOS, DO is
an interprocess messaging protocol used to communicate
between Cocoa applications. Under these constraints, there
were benefits to be had from the additional context.

By default, parameters in distributed object messages were


passed as proxies, except in situations where proxying would
be unnecessarily inefficient; the bycopy qualifier could be
specified to make sure a full copy of the object was sent
instead.

Parameters were also inout by default, signifying that objects


needed to be sent back and forth when sending the message.
By specifying a parameter as just in or out instead, the
application could avoid the round-trip overhead.

!
So what do we gain from our newfound understanding of
Objective-C Type Encodings? Honestly, not that much.

But as we said from the very outset, there is wisdom in the


pursuit of deciphering secret messages. Looking at type
encodings reveals details about Objective-C runtime
internals, which is a noble pursuit in and of itself.

40
C Storage Classes

In C, the scope and lifetime of a variable or function is


determined by its storage class. Each variable has a lifetime, or
the context in which they store their value. Functions, along
with variables, also exist within a particular scope, or visibility,
which dictates which parts of a program know about them.

There are 4 storage classes in C: auto, register, static & extern.

auto
There's a good chance you've never seen this keyword in the
wild. That's because auto is the default storage class, and
therefore rarely needs to be specified explicitly.

Automatic variables have memory automatically allocated


when a program enters a block, and released when the
program leaves that block. Access to automatic variables is
limited to only the block in which they are declared, as well as
any nested blocks.

41
register
Most Objective-C programmers probably aren't familiar with
register either, as it's not widely used in the NS world.

register behaves just like auto, except that instead of being


allocated onto the stack, they are stored in a register.

Registers offer faster access than RAM, but because of the


complexities of memory management, putting variables in
registers does not always guarantee a faster program—in fact,
it may very well end up slowing down execution by taking up
space on the register unnecessarily. As it were, using register is
no more than a mere suggestion to the compiler;
implementations may choose whether or not to honor this.

register's lack of popularity in Objective-C is instructive: it's


probably best not to bother with. It will sooner cause a
headache than any noticeable speedup.

static
Finally, one that everyone's sure to recognize: static.

As a keyword, static gets used in a lot of different ways, so it


can be confusing to figure out exactly what it means in every
instance. When it comes to storage classes, static means one of
two things.

42
1. A static variable inside a method or function retains its
value between invocations.

2. A static variable declared globally can called by any


function or method, so long as those functions appear in
the same file as the static variable. The same goes for static
functions.

Static Singletons
A common pattern in Objective-C is the static singleton,
wherein a statically-declared variable is initialized and
returned in either a function or class method:

+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
// any further configuration
});
!
return _sharedInstance;
}

The singleton pattern is useful for creating objects that are


shared across the entire application, such as a notification
manager, or objects that may be expensive to create, such as
date formatters.

43
extern
Whereas static makes functions and variables globally visible
within a particular file, extern makes them visible globally to
all files.

Global variables are not a great idea, generally speaking.


Having no constraints on how or when state can be mutated
is just asking for impossible-to-debug situations.

That said, there are two common and practical uses for extern
in Objective-C: constants and public functions.

Global String Constants


Any time your application uses a string constant in a public
interface, it should be declared as an external string constant.
This is especially true of NSNotification names, NSError
domains, and keys in userInfo dictionaries.

Declare an extern NSString * const in a public header, and


define that NSString * const in the implementation:

AppDelegate.h

extern NSString * const kAppErrorDomain;

44
AppDelegate.m

NSString * const kAppErrorDomain =


@"com.example.yourapp.error";

It doesn't particularly matter what the value of the string is, so


long as it's unique.

Public Functions
Some APIs may wish to expose helper functions publicly. The
pattern follows the same as in the previous example:

TransactionStateMachine.h

typedef NS_ENUM(NSUInteger, TransactionState) {


TransactionOpened,
TransactionPending,
TransactionClosed,
};
!
extern NSString *
NSStringFromTransactionState(TransactionState state);

45
TransactionStateMachine.m

NSString *
NSStringFromTransactionState(TransactionState state) {
switch (state) {
case TransactionOpened: return @"Opened"
case TransactionPending: return @"Pending";
case TransactionClosed: return @"Closed";
default: return nil;
}
}

To understand anything is to make sense of its context. What


we may see as obvious and self-evident, is all but unknown to
someone outside our frame of reference. Our inability to truly
understand or appreciate the differences in perspective
between ourselves and others is perhaps our most basic
shortcoming.

That is why, in our constructed logical universe of 0's and 1's,


we take such care to separate contexts, and structure our
assumptions based on these explicit rules. C storage classes
are essential to understanding how a program operates. Take
heed of these simple rules of engagement and go forth to code
with confidence.

46
@

Birdwatchers refer to it as "Jizz": those indefinable


characteristics unique to a particular kind of thing.

This term can be appropriated to describe how seasoned


individuals might distinguish Rust from Go, or Ruby from
Elixir at a glance. Some just stick out like sore thumbs:

Perl, with all of its short variable names and special characters,
reads like Q*bert swearing.

Lisp's profusion of parentheses is best captured by that old


joke about a computer science student proving that they
actually finished their homework by showing the last page:

)))))
)))
))
)))) ))
)))) ))
)))
)

!
47
So if one were to go code-watching for the elusive Objective-
C species, what would we look for?

• Square brackets
• Ridiculously-long method names
• @'s

@, or "at" sign compiler directives, are as central to


understanding Objective-C's gestalt as its ancestry and
infrastructure. It's the sugary glue that allows Objective-C to
be such a powerful, expressive language, and yet still compile
all the way down to C.

Its uses are varied and disparate, such that the only way to
accurately describe what @ means by itself is "shorthand for
something to do with Objective-C". @ compiler directives
cover a broad range in usefulness and obscurity, with staples
like @interface and @implementation, as well as ones a
developer go their whole career without running into, like
@defs and @compatibility_alias.

But to anyone aspiring to be an NSHipster, intimate


familiarity with @ directives is tantamount to a music lover's
ability to list all of The Beatles albums in chronological order
(and most importantly, having unreasonably strong opinions
about each of them).

48
Interface & Implementation
@interface and @implementation are the first things you
learn about when you start Objective-C:

• @interface...@end
• @implementation...@end

What you don't learn about until later on, are categories and
class extensions.

Categories allow you to extend the behavior of existing classes


by adding new methods. As a convention, categories are
defined in their own .{h,m} files, like so:

MyObject+CategoryName.h

@interface MyObject (CategoryName)


+ (BOOL)barWithBaz:(NSInteger)baz;
- (void)foo;
@end

49
MyObject+CategoryName.m

@implementation MyObject (CategoryName)


+ (BOOL)barWithBaz:(NSInteger)baz {
return baz < 42;
}
!
- (void)foo {
// ...
}
@end

Categories are particularly useful for convenience methods


on standard framework classes (just don't go overboard with
your utility functions).

Rather than littering your code with random, arbitrary color values,
create an NSColor / UIColor category that defines class methods like
+appNameDarkGrayColor. You can then add a semantic layer on
top of that by creating method aliases like +appNameTextColor,
which returns +appNameDarkGrayColor.

Extensions look like categories, but omit the category name.


These are typically declared in the .m file before an
@implementation to specify a private interface, and even
override properties declared in the original @interface:

50
Another Random Scribd Document
with Unrelated Content
Returning now to the terrace below, common to both Mashonganavi
and Shipauluvi, the trail is descended to Shungopavi. A deep canyon
separates the mesa upon which this village is built from the one
upon which the two former are located. Near the foot of the trail the
government has established a schoolhouse, and close by are the
springs and pools of water. It is a sandy ride or walk, and on a hot
day—"a-tu-u-u"—wearisome and exhausting. For half a dollar or so
one may hire a burro and his owner as guide, and it is much easier
to go burro-back over the yielding sand than to walk. There are
straggling peach trees on the way, and a trail, rocky and steep, to
ascend ere we see Shungopavi.
The wagons may be driven to the village (as mine were), but it is a
long way around. The road to Oraibi across the mesa is taken, and
when about half-way across a crude road is followed which runs out
upon the "finger tip" where Shungopavi stands. Here the governor in
1901 was Lo-ma-win-i, and he and I became very good friends.
Knowing my interest in the Snake Dance, he sent for the chief
priests of the Snake and Antelope Clans (Kai-wan-i-wi-ya-ŭ-má and
Lo-ma-ho-in-i-wa), and from them I received a cordial invitation to
be present and participate in the secret ceremonials of the kiva at
their next celebration. I have been privileged to be present, but was
never invited before.
The governor is an expert silversmith, the necklace he wears being a
specimen of his own art. It is wonderful how, with their crude
materials and tools, such excellent work can be produced. Mexican
dollars are melted in a tiny home-made crucible, rude moulds are
carved out of sand—or other stone into which the melted metal is
poured, and then hand manipulation, hammering, and brazing
complete the work. Their silver articles of adornment are finger
rings, bracelets, and necklaces.
Oraibi is the most western and conservative of the Hopi villages. It is
by far the largest, having perhaps a third of the whole population. It
is divided into two factions, the so-called hostiles and friendlies, the
former being the conservative element, determined not to forsake
"the ways of the old," the ways of their ancestors; and the latter
being generally willing to obey orders ostensibly issued by
"Wasintonia"—as they call the mysterious Indian Department. These
divisions are a source of great sorrow to the former leaders of the
village. In the introduction to "The Oraibi Soyal Ceremony" by
Professor George A. Dorsey, of the Field Columbian Museum, and
Rev. H. R. Voth, his assistant, and formerly a Mennonite missionary
at Oraibi, this dissension is spoken of as follows: "During the year
1891 representatives of the Indian Department made strenuous
efforts to secure pupils for the government school located at Keam's
Canyon, about forty miles from Oraibi. This effort on the part of the
government was bitterly resented by a certain faction of the people
of Oraibi, who seceded from Lolúlomai, the village chief, and soon
after began to recognize Lomahungyoma as leader. The feeling on
the part of this faction against the party under Lolúlomai was further
intensified by the friendly attitude the Liberals took toward other
undertakings of the government, such as allotment of land in
severalty, the building of dwelling-houses at the foot of the mesa,
the gratuitous distribution of American clothing, agricultural
implements, etc. The division thus created manifested itself not only
in the everyday life of the people, but also in their religious
ceremonies. Inasmuch as the altars and their accessories are the
chief elements in these ceremonies, they soon became the special
object of controversy, each party contending for their possession;
and so it came about that the altars remained to that faction to
which the chief priests and those who had them in charge belonged,
the members of the opposing faction, as a rule, withdrawing from
further participation in the celebration of the ceremony."
The dance plaza is on the western side of the village, and there the
dances and other outdoor ceremonies take place.
One of my earliest visits to Oraibi was made in the congenial
company of Major Constant Williams, who was then the United
States Indian Agent, at Fort Defiance, for the Navahoes and Hopis.
We had driven across the Navaho Reservation from Fort Defiance to
Keam's Canyon, and then visited the mesas in succession. We drove
to the summit of the Oraibi mesa in his buckboard, a new
conveyance which he had had made to order at Durango, Colo. The
road was the same one up which the soldiers had helped the horses
drag the Gatling gun at the time of the arrest of the so-called
"hostiles," who were sent to Alcatraz for their refusal to forsake their
Oraibi ways and follow the "Washington way." It was a steep, ugly
road, rough, rocky, and dangerous. The Major's horses, however,
were strong, intelligent, and willing, so we made the ascent with
comparative ease. The return, however, was different. There were so
many things of interest at Oraibi that I found it hard to tear myself
away, and the "shades of night were falling fast"—far too fast for the
Major's peace of mind—ere I returned to the buckboard. By the time
we had traversed the summit of the mesa to the head of the "trail"
part of the descent, it was dark enough to make the cold tremors
perambulate up and down one's spine. But I had every confidence in
the Major's driving, his horses, and his knowledge of that fearfully
precipitous and dangerous road. Slowly we descended, the brake
scraping and often entirely holding the wheels. We could see and
feel the dark abysses, first on one side and then on the other, or feel
the overshadowing of the mighty rock walls which towered above us.
I was congratulating myself that we had passed all the dangerous
places, and in a few moments should be on the drifted sand, which,
though steep, was perfectly safe, when we came to the last "drop
off." This can best be imagined by calling it what it was, a steep,
rocky stairway, of two or three steps, with a precipice on one side,
and a towering wall on the other. Hugging the wall, the upper step
extended like a shelf for eight or ten feet, and the nigh horse,
disliking to make the abrupt descent of the step, clung close to the
wall and walked along the shelf. The off horse dropped down. The
result can be imagined. One horse's feet were up at about the level
of the other's back. The wheels followed their respective horses. The
nigh wheels stayed on the shelf, the off wheels came down the step.
The Major and I decided, very suddenly, to leave the buckboard. We
were rudely toppled out, down the precipice on the left,—I at the
bottom of the heap. Down came camera cases, tripods, boxes of
plates, and all the packages of odds and ends I had bought from the
Indians, bouncing about our ears. Like a flash the two horses took
fright and started off, dragging that overturned buckboard after
them. They did not swirl around to the left down the sandy road, but
to the right upon a terrace of the rocky mesa, and we saw the
sparks fly as the ironwork of the wagon struck and restruck the
rocks. The noise and roar and clatter were terrific. Great rocks were
started to rolling, and the echoes were enough to awaken the dead.
Suddenly there was a louder crash than ever, and then all was silent.
We felt our hearts thumping against our ribs, and the only sounds
we could hear were their fierce beatings and our own hard
breathing. Fortunately, we had landed on a narrow shelf some seven
feet down, covered deep with sand, so neither of us was seriously
hurt except in our feelings; but imagine the dismay that swept aside
all thoughts of thankfulness for our narrow escape when that crash
and dread silence came. No doubt horses and buckboard were
precipitated over one of the cliffs and had all gone to "eternal
smash." My conscience made me feel especially culpable, for had I
not detained the Major we should have left the mesa long before it
was so dark. I had caused the disaster! It was nothing that I had
been "spilt out," that doubtless my cameras were smashed, and the
plates I had exposed with so much care and in spite of the
opposition of the Hopis were in tiny pieces—for I had clearly heard
that peculiar "smash" that spoke of broken glass as I myself landed
on the top of my head. Think of that span of fine horses, and the
Major's new buckboard! The thought about completed the work of
mental and physical paralysis the shock of falling had begun. I was
suddenly awakened, not by the Major's voice, for neither of us had
yet spoken a word,—and indeed, I didn't know but that he was
dead,—but by the scratching of a match. Then he was alive! That
was cause for thankfulness. Setting fire to a dried cactus, the Major,
after thoroughly picking himself up and shaking himself together,
proceeded to gather up the photographic débris. Silently I aided
him. Still silently we piled it all together, as much under the shelter
of the rocks as possible, and then, still without a word, we climbed
back upon the road and started to walk to the house of Mr. Voth, the
missionary, where we were stopping. For half a mile or more we
trudged on wearily through the deep and yielding sand. Still never a
word. We both breathed heavily, for the sand was dreadfully soft. I
was wondering what I could say. My conscience so overpowered me
that I dared not speak. I was humbling myself, inwardly, into the
very dust for having been the unconscious and innocent, yet
nevertheless actual cause of this disaster. I simply couldn't break the
silence. To offer to pay for the horses and buckboard was easy
(though that would be a serious matter to my slender purse)
compared with appeasing the sturdy Major for the shock to his
mental and physical system. Then, too, how he must feel! At the
very thought the cold sweat started on my brow and I could feel it
trickling down my chest and back.
An Oraibi Basket Weaver.
An Admiring Hopi Mother.

Suddenly the Major stopped, and in the darkness I could dimly see
him take out his large white handkerchief, mop his brow and head,
and then, with explosive force, but in a voice charged with deepest
and sincerest feeling he broke the painful silence: "Thank God, the
sun isn't shining."
Brave-hearted, generous Major Williams! Not a word of reproach, no
suggestion of blame. What a relief to my burdened soul. I was
almost hysterical in my ready response. Yes, we could be thankful
that our lives and limbs were spared. We were both unhurt. New
horses and buckboard could be purchased, but life and health
preserved called for thankfulness to the Divine Protector.
Thus we congratulated ourselves as we slowly plodded along
through the sand. Arrived at Mr. Voth's, we soon retired,—he in the
bedroom prepared for him by kindly Mrs. Voth, I in my blankets
outside. The calm face of the sky soon soothed my disquieted
feelings and nerves, and in a short time I fell asleep. Not a thought
disturbed me until just as the faintest peepings of dawn began to
show on the eastern ridges, when, awakening, I heard a noise as of
a horse shaking his harness close by. Like a flash I jumped up, and,
in my night-robe though I was, rushed to the entrance to the corral.
There, unharmed and uninjured, with harness upon them complete,
the lines dangling down behind, the neck yoke holding them
together, as if they were just brought from the stable ready to be
hitched to the wagon, were the two horses which I had vividly
pictured to myself as dashed to pieces upon the cruel rocks at the
foot of one of the mesa precipices.
I could scarcely refrain from shouting my joy. Hastily I dressed, and
while dressing thought: "The horses are here; I'll go and hunt for
the wagon." So noiselessly I hitched them to Mr. Voth's buckboard
and drove off. When I came to the scene of the disaster, I found I
could drive upon the rocky terrace. There was no difficulty in
following the course of the runaways. Here was part of the seat,
farther on some of the ironwork, and still farther the dashboard. At
last I reached the overturned and dismantled vehicle. It was in a
sorry state. Two of the wheels were completely dished, the seat and
dashboard were "scraped" off, one whiffletree was broken, and the
whole thing looked as if it had been rudely treated in a tornado. I
turned it over, tied the wheels so that they would hold, and then,
fastening it behind Mr. Voth's buckboard, slowly drove back to the
house.
When the Major awoke he was as much surprised and pleased as I
was to find the horses safe and sound and the buckboard in a
repairable condition. With a little manɶuvring we got the vehicle as
far as Keam's Canyon, where old Jack Tobin, the blacksmith, fixed it
up so that it could be driven back to Fort Defiance, and thither, with
care and caution, the Major drove me. A few weeks later, under the
healing powers of the agency blacksmith, the buckboard renewed its
youth,—new wheels, new seat, new dashboard, and an all covering
new coat of paint wiped out the memories of our trip down from the
Oraibi mesa, except those we carried in the depths of our own
consciousness.
CHAPTER V
A FEW HOPI CUSTOMS

To know any people thoroughly requires many years of studied


observation. The work of such men as A. M. Stephen, Dr. Fewkes,
Rev. H. R. Voth, and Dr. George A. Dorsey reveals the vast field the
Hopis offer to students. To the published results of these
indefatigable workers the student is referred for fuller knowledge.
There are certain things of interest, however, that the casual
observer cannot fail to note.
The costume of the men is undoubtedly a modification of the dress
of the white man. Trousers are worn, generally of white muslin, and
from the knee down on the outer side they are split open at the
seam. Soleless stockings, home-spun, dyed and knit, are worn,
fastened with garters, similar in style and design, though smaller, to
the sashes worn by the women. The feet are covered with rawhide
moccasins. The shirt is generally of colored calico, though on special
occasions the "dudes" of the people appear in black or violet velvet
shirts or tunics, which certainly give them a handsome appearance.
The never-failing banda, wound around the forehead, completes the
costume, though accessories in the shape of silver and wampum
necklaces, finger rings, etc., are often worn.
The costume of the women is both picturesque and adapted to their
life and customs. It is neat, appropriate, and modest. The effort our
government feels called upon to make to lead them to change it for
calico "wrappers," in accordance with a principle adopted which
regards as "bad" and "a hindrance to civilization" anything native, is
to my mind vicious and senseless. The Indians are not to be civilized
by making them wear white people's costumes, nor by any such
nonsense. There are those who condemn their basket weaving,
because, forsooth, it is not a Christian art. True civilizing processes
come from within, and desire for change must precede the outward
manifestation if permanent results are desired.
To return to the costume. It consists mainly of a home-woven robe,
dyed in indigo. When made, it looks more like an Indian blanket than
a dress, but when the woman throws it over her right shoulder, sews
the two sides together, leaving an opening for the right arm, and
then wraps one of the highly colored and finely woven sashes
around her waist, the beholder sees a dress at once healthful and
picturesque. As a rule, it comes down a little below the knee, and
the left shoulder is uncovered. Of late years many of the women and
girls have learned to wear a calico slip under the picturesque native
dress, so that both arms and shoulders are covered.
Most of the time the legs and feet are naked, but when a woman
wishes to be fully attired, she wraps buckskins, cut obliquely in half,
around her legs, adroitly fastening the wrappings just above the
knee with thongs cut from buckskin, and then encases her feet in
shapely moccasins. There is no compression of her solid feet, no
distortion with senseless high heels. She is too self-poised, mentally,
to care anything about Parisian fashions. Health, neatness, comfort,
are the desiderata sought and obtained in her dress. The question is
sometimes asked, however, if the heavy leg swathings of buckskin
are not a mere fashion of Hopi dress. Undoubtedly there is a
following of custom here as well as elsewhere, and, as I have before
remarked, one of the keys to the Hopi character is his conservatism.
But the buckskin leggings have a decided reason for their existence.
In a desert country where cacti, cholla, many varieties of prickly
shrubs, sharp rocks, and dangerous reptiles abound, it is necessary
that the women whose work calls them into these dangers should so
dress as to be prepared to overcome them. Many a man wearing the
ordinary trousers of civilization and finding himself off the beaten
paths of these desert regions has longed for just such protection as
the Hopi women give themselves. The cow-boys who ride pell-mell
through the brush wear leather trousers, and their stirrups are
covered with tough and thick leather to protect their shoes from
being pierced by the searching needles of the cactus, cholla, and
buck-brush.
The adornments that a Hopi maiden of fashion affects are silver
rings and bracelets made by native silversmiths, and necklaces of
coral, glass, amber, or more generally of the shell wampum found all
over the continent. The finer necklets of wampum are highly prized,
and when very old and ornamented with pieces of turquoise, can not
be purchased for large sums. Occasionally ear pendants are worn.
These are made of wood, half an inch broad and an inch long, inlaid
on one side with pieces of bright shell, turquoise, etc.
When a girl reaches the marriageable age, she is required by the
customs of her people to fix up her hair in two large whorls, one on
each side of her head. This gives her a most striking appearance.
The whorl represents the squash blossom, which is the Hopi emblem
of purity and maidenhood. Girls mature very early, the young
maidens herewith represented being not more than from twelve to
fifteen years of age.
Shupela, Father of Kopeli, Late
Snake Priest at Walpi.
A Hopi Girl, Oraibi.

When a woman marries she must no longer wear the nash-mi


(whorls). A new symbolism must be introduced. The hair is done up
in two pendant rolls, in imitation of the ripened fruit of the long
squash, which is the Hopi emblem of fruitfulness.
In my book on "Indian Basketry" I have described in detail the
basketry of the Hopis. There are two distinct varieties made at the
four villages of the middle and western mesas. Those made on the
middle mesa are of yucca fibre (mo-hu) coiled around a core of
grass or broom-corn (sű-ű). Those of Oraibi are of willow and
approximate as nearly to the crude willow work of civilization as any
basketry made by the aborigines. In both cases the splints are dyed,
commonly nowadays with the startling aniline dyes, and with
marvellous fertility of invention the weavers make a thousand and
one geometrical designs, in imitation of natural objects, katchinas,
etc. These are mainly plaques, but the yucca fibre weavers make a
treasure or trinket basket, somewhat barrel-shaped, oftentimes with
a lid, that is both pretty and useful. The name for all the yucca
variety is pű-ű-ta. The Oraibi willow plaques are called yung-ya-pa,
while a bowl-shaped basket is sa-kah-ta, and the bowls made of
coiled willow splints bought from the Havasupai are sű-kű-wű-ta.
The Hopi weavers when at work invariably keep a blanket full of
moist sand near them in which the splints are buried. This keeps
them flexible, and the moist sand is better than water.
A reddish-brown native dye is made from Ohaishi (Thelesperma
gracile), with which the splints are colored.
Unfortunately, the introduction of aniline dyes has almost killed the
industry of making native dyes, but there are some few
conservatives—God bless them!—who adhere to the ancient colors
and methods of preparing them.
It cannot be said that the Hopis are devoid of musical taste, for in
the early morning especially, as the youths and men take their
ponies or flocks of goats and sheep out to pasture, they sing with
sweet and far-reaching voices many picturesque melodies.
Of the weird singing at their religious ceremonials I have spoken in
the chapter devoted to that purpose.
To most civilized ears Hopi instrumental music, however, is as much
a racket and din as is Chinese music. The lelentu, or flute, however,
produces weird, soft, melancholy music. Their rattles are of three
kinds, the gourd rattle (ai-i-ya), the rattle used by the Antelope
priests, and the leg rattle of turtle shell and sheep's trotters (yȕng-
ush-o-na). The drum and hand tombe are crude affairs, the former
made by hollowing out a tree trunk and stretching over each end
wet rawhide, the lashings also being of strips of wet rawhide (with
the hair on), which, when dry, tightens so as to give the required
resonance. The hand tombe is as near like a home-made tambourine
as can be. It has no jingles, however. Another instrument is the
strangest conception imaginable. It consists of a large gourd shell,
from the top of which a square hole has been cut. Across this is
placed a notched stick, one end of which is held in the performer's
left hand. In the other hand is a sheep's thigh-bone, which is worked
back and forth over the notched stick, and the resultant noise is the
desired music. This instrument is the zhe-gun´-pi.
They do not seem to have many games, so many of their religious
ceremonials affording them the diversion other peoples seek in
athletic sports. Their racing is purely religious, as I have elsewhere
shown, and they get much fun out of some of their semi-religious
exercises.
A game that they are very fond of, and that requires considerable
skill to play, is wē-la. The game consists in several players, each
armed with a feathered dart, or ma-te´-va, rushing after a small
hoop made of corn husks or broom-corn well bound together—the
wē-la, and throwing their darts so that they stick into it The hoop is
about a foot in diameter and two inches thick, the ma-te´-va nearly
a foot long. Each player's dart has a different color of feathers, so
that each can tell when he scores. To see a dozen swarthy and
almost nude youths darting along in the dance plaza, or streets, or
down in the valley on the sand, laughing, shouting, gesticulating,
every now and then stopping for a moment, jabbering over the
score, then eagerly following the motion of the thrower of the wē-la
so as to be ready to strike the ma-te´-va into it, and then, suddenly
letting them fly, is a picturesque and lively sight.
The Hopi is quite a traveller. Though fond of home, I have met
members of the tribe in varied quarters of the Painted Desert
Region. They get a birch bark from the Verdi Valley with which they
make the dye for their moccasins. A yellowish brown color, called
pavissa, is obtained from a point near the junction of the Little
Colorado and Marble Canyon. Here they obtain salt, and at the
bottom of the salt springs, where the waters bubble up in pools, this
pavissa settles. Bahos, or prayer sticks, are always deposited at the
time of obtaining this ochre, as it is to be used in the painting of the
face of the bahos used in most sacred ceremonies. The so-called
Moki trail is evidence of the long association between the Hopis and
the Havasupais in Havasu (Cataract) Canyon, and I have often met
them there trading blankets, horses, etc., for buckskin and the finely
woven wicker bowl-baskets—kű-űs—of the Havasupais, which are
much prized by the Hopis.
Occasionally he reaches as far northeast as Lee's Ferry and even
crosses into southern Utah, and at Zuni to the southeast he is ever a
welcome visitor. The Apaches in the White Mountains tell that on
occasions the Hopis will visit them, and when visiting the Yumas in
1902 they informed me that long ago the Snake Dancing Mokis were
their friends, and sometimes came to see them.
Dr. Walter Hough has written a most interesting paper on
"Environmental Interrelations in Arizona," in which are many items
about the Hopis. He says they brought from their priscan home corn,
beans, melons, squash, cotton, and some garden plants, and that
they have since acquired peaches, apricots, and wheat, and among
other plants which they infrequently cultivate may be named onions,
chili, sunflowers, sorghum, tomatoes, potatoes, grapes, pumpkins,
garlic, coxcomb, coriander, saffron, tobacco, and nectarines. They
are great beggars for seeds and will try any kind that may be given
to them.
Owing to their dependence upon wild grasses for food when their
corn crops used to fail,—that is, in the days before a paternal
government helped them out at such times,—every Hopi child was a
trained botanist from his earliest years; not trained from our
standpoint, but from theirs. We should say much of his knowledge
was unscientific, and it goes far beyond the use of grasses and
plants as food. Dr. Hough in his paper gives a number of examples
of the uses to which the various seeds, etc., are put. The botanist as
well as the ethnologist will find this a most comprehensive and
useful list. For food forty-seven seeds, berries, stems, leaves, or
roots are eaten. The seeds of a species of sporobolus are ground
with corn to make a kind of cake, which the Hopis greatly enjoy. The
leaves of a number are cooked and eaten as greens.
A large amount of folk-lore connected with plants has been collected
by Drs. Fewkes and Hough. From the latter's extensive list I quote.
For headache the leaves of the Astragalus mollissimus are bruised
and rubbed on the temples; tea is made from the root of the Gaura
parviflora for snake bite; women boil the Townsendia arizonica into a
tea and drink it to induce pregnancy; a plant called by the Hopi
wűtakpala is rubbed on the breast or legs for pain; Verbesina
enceloides is used on boils or for skin diseases; Croton texlusis is
taken as an emetic; Allionia linearis is boiled to make an infusion for
wounds; the mistletoe that grows on the juniper (Phoradendron
juniperinum) makes a beverage which both Hopi and Navaho say is
like coffee, and a species that grows on the cottonwood, called lo
mapi, is used as medicine; the leaves of Gilia longiflora are boiled
and drank for stomach ache; the leaves of the Gilia multiflora (which
is collected forty miles south of Walpi at an elevation of six thousand
feet), when bruised and rubbed on ant bites is said to be a specific;
Oreocarya suffruticosa is pounded up and used for pains in the
body; Carduus rothrockii is boiled and drank as tea for colds which
give rise to a prickling sensation in the throat; the leaves of
Coleosanthus wrightii are bruised and rubbed on the temples for
headache, as also is the Artemisia canadensis; and so on throughout
a list as long again as this.
In connection with this list Dr. Hough calls attention to the workings
of the Hopi mind in a manner which justifies an extensive quotation:

"The word 'medicine' as applied by the Hopi and other tribes is


very comprehensive, including charms to influence gods, men,
and animals, or to cure a stomach ache. As stated, from
experiments with the plants some have been discovered which
are uniform in action and which would have place in a standard
pharmacopœia. Thus there are heating plasters, powders for
dressing wounds, emetics, diuretics, purges, sudorific infusions,
etc. Other plants are of doubtful value, and in their use other
animistic ideas may enter, though some of them, such as those
infused for colds, headache, rheumatism, fever, etc., may have
therapeutic properties. The obligation of the civilized to the
uncivilized for healing plants is very great. Another class is
clearly out of the domain of empirical medicine. Tea made from
the thistle is a remedy for prickling pains in the larynx, milkweed
will induce a flow of milk, and there are other examples of
inferential medicine. Perhaps another class is shown by the
employment of the plant named for the bat, in order to induce
sleep in the daytime.
"It may be interesting to look into the workings of the Indian
mind as shown by his explanation of the uses of certain of these
plants.
"A beautiful scarlet gilia (Gilia aggregata Spreng) grows on the
talus of the giant mesa on which ancient Awatobi stood. This is
the only locality where the plant has been collected in this
region, but it grows in profusion on the White Mountains, one
hundred and twenty-five miles southeast.
"The herdsman of our party was asked the name and use of the
plant. He replied: 'It is the pala katchi, or red male flower, and it
is very good for catching antelope. Before going out to kill
antelope, hunters rub up the flowers and leaves of the plant and
mix them with the meal which they offer during their prayer to
the gods of the chase.'
"'Why is that?' was asked.
"'Because,' he replied, 'the antelope is very fond of this plant
and eats it greedily when he can find it.' (Animistic idea.)
"Another creeping plant (Solanum triflorum Nutt.), which bears
numerous green fruit about the size of a cherry, filled with small
seeds, is called cavayo ngahu, or watermelon medicine. The
plant may be likened to a miniature watermelon vine. It was
explained that if one took the fruit and planted it in the same
hill with the watermelon seeds, would there be many
watermelons,—that is, the watermelon would be influenced to
become as prolific as the small plant.
"Every one is familiar with the clematis bearing fluffy bunches of
seeds having long, hair-like appendages. An Indian lecturing on
a collected specimen of the clematis said: 'This is very good to
make the hair grow. You make a tea of it and rub it on the
head, and pretty quick your hair will hang down to your hips,'
indicating by a gesture the extraordinary length. For the same
reason the fallugia is a good hair tonic."

The Hopi uses a weapon for catching rabbits which, for want of a
better name, white men call a boomerang. It possesses none of the
strange properties of the Australian weapon, yet in the hands of a
skilled Hopi it is wonderfully effective. I have seen fifty Oraibis on
horseback, and numbers of men and boys on foot, each armed with
one of these weapons, on their rabbit drive. They determine on a
certain area and then beat it thoroughly for rabbits, and woe be to
the unhappy cottontail or even lightning-legged jack-rabbit if a Hopi
throws his boomerang. Like the wind it speeds true to its aim and
seldom fails to kill or seriously wound.
Though most of the men have guns and many of the youths
revolvers, the bow and arrow as a weapon is not entirely discarded.
All the young boys, even little tots that can scarcely walk, use the
bow and arrow with dexterity. A small hard melon or pumpkin is
thrown into the air and a child will sometimes put two or even three
arrows into it before it reaches the ground. Old men who are too
poor to own modern weapons are often seen sitting like the
proverbial and oft-pictured fox, stealthily watching for a ground
squirrel, prairie-dog, or rat to come out of his hole, when the speedy
and certain arrow is let fly to his undoing.
Except for a little wild meat of this kind, secured seldom, or a sheep,
which is too valuable for its wool to kill on any except very special
and rare occasions, the Hopis are practically vegetarians. They are
not above taking what the gods send them, however, in the shape of
a dead horse. A few years ago Mr. D. M. Riordan, formerly of
Flagstaff, conducted a party of friends over a large section of the
region presented in these pages, and when near Oraibi a beautiful
mare of one of the teams suddenly bloated and speedily died. In
less than an hour after they were told they might take the flesh; the
Hopis had skinned it, cut up the carcass, and removed every shred
of it. I afterwards saw the flesh cut into strips, hung outside the
houses of the fortunate possessors to dry, and I doubt not that
horse meat made many a happy meal for them during the months
that followed.

Hopi Children, at Oraibi, Waiting for a Scramble of Candy.

When a Hopi feels rich he may buy a sheep or a goat from a


Navaho, or even kill a burro in order to vary his dietary.
Corn is his staple food. It is cooked in a variety of ways, but the
three principal methods are piki, pikami, and pū-vū-lū. Piki is a thin,
wafer-like bread, cooked as I have before described.
On one occasion, at Oraibi, an old friend, Na-wi-so-ma, was making
piki for the Snake Dancers. When I took my friends to see her, they
all ate of the bread and asked her all manner of questions about it.
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