Types
-
short, int, long, NSInteger
-
Represent integers.
short holds smaller numbers
than int, which is smaller
than long. NSInteger is a type provided
by Apple that is an integer of the ideal size for the current
platform, be it iOS or OS X.
float, double, CGFloat
-
Decimal numbers,
double is capable of storing higher
precision numbers than float, but uses up double the
storage space. CGFloat is the decimal type used by the iOS Core
Graphics framework.
- Pointer
-
Pointers are variables that "point" to other variables. In
Objective-C, we never deal with objects directly, but instead pass
around pointers to them. This is why when we declare an object,
the variable that we store is a pointer to the object.
NSDate *today = [NSDate date];
Technically we say that "today is a pointer to an NSDate,"
however since objects are always stored as pointers, normally
you will just say that "today is an NSDate."
struct
-
Structures are composite types. They allow us to group together
data into a more complicated concept. For example I want a type
Location that knows the name, latitude, and longitude of a
location and the number of times I had visited that place.
typedef struct {
float latitude;
float longitude;
int visits;
} Location;
Elements of a struct are accessed using dot notation.
Location theFactory;
theFactory.latitude = 42.963107;
theFactory.longitude = -85.669407;
theFactory.visits = 42;
Structs are used frequently in iOS development. Try looking up NSRect
in the XCode documentation. NSRects are used to represent the
location of a user interface element
BOOL
-
Boolean values, takes two values,
YES
or NO.
Format Strings
- Integers
- %i
- Decimals (floats)
- %f
- NSString
- %@
NSString *name = @"The Tempest";
float height = 1.75;
int age = 42;
NSLog(@"%@ is my favorite Shakepear play", name);
NSLog(@"You must be at least %f meteres tall to ride this ride", height);
NSLog(@"That person over there is %i years old", age);
Functions
rtype functionName(type1 arg1, type2 arg2)
Including Libraries
#import <math.h> // Angle brackets for accessing built-in functions
#import "MyAwesomeUtility.h" // Quotes for accessing user functions
Conditionals
if (condition) {
// Do if condition is true
} else {
// Do if condition is false
}
Loops
While
while (condition) {
// Run this as long as condition is true
}
For
for (initialize; test; increment) {
// Run this as long as test passes, preform increment
// at the end of every loop
}
Exercises
-
Write a program that will convert temperatures from Celsius to
Farenheit and back. The program will do this until the user
decides to quit.
-
Write a text-based adventure game. The player starts at a random
location and must find the treasure. Represent the player, treasure,
and map extent with structs.
-
Search for a C library that performs a task you are interested in.
Write a small program that uses a function from that library.