// This is a comment
/* This is a comment
extending over two lines */
/*
* This is a comment expanding over...
* One...
* Two...
* 4 + 2 (Above and Below) = 6 lines!
*/
/*
Anything can go between these lines!
*/
int x = 1;
int y = 2;
int sum;
sum = x + y;
To output the value of sum we must use what is called a format specifier.
The most basic format specifiers include:
NSLog(@"The sum of x + y = %i", sum);
NSLog(@"The sum of %i + %i = %i", x, y, sum);
NSLog(@"The sum of %i + %i = %i", y, x, sum);
int x;
x = 10;
x = y + z;
x = y;
int x, y, z;
x = y = z = 10;
int x = 13, y = 5, remainder;
remainder = x % y;
// remainder = 3
One common use for modulo is to determine if an integer is odd or even. If it is even, then a modulus of two will equal zero. Otherwise it will equal another value.
int anInt;
//Some code that sets the value of anInt
if ((anInt % 2) == 0) {
NSLog(@"anInt is even");
} else {
NSLog(@"anInt is odd");
}
x = y * 10 + z - 5 / 4;
x++; Increment x by 1
x--; Decrement x by 1
int x = 9; int y; y = ++x;
// y = 10
int x = 9;
int y;
y = x--;
// y = 9
// x = 8
bool flag = true; //variable is true
bool secondFlag;
secondFlag = !flag; // secondFlag set to false
if ((10 < 20) || (20 < 10))
NSLog (@"Expression is true");
if ((10 < 20) && (20 < 10))
NSLog (@"Expression is true");
if ((10 < 20) ^ (20 < 10))
NSLog (@"Expression is true");
[condition] ? [true expression] : [false expression]
int x = 10;
int y = 20;
NSLog(@"Largest number is %i", x > y ? x : y );
// Largest number is 20
if (condition) {
// statement(s) if the condition is true;
} else {
// statement(s) if the condition is not true;
}
for (counter; condition; update counter) {
// statement(s) to execute while the condition is true;
}
// Example
for (int i = 0; i < 5; i++){
NSLog(@"%i", i);
}
for (Type newVariable in expression ) { // statement(s); } // or Type existingVariable;
for (existingVariable in expression) { // statement(s); } // Example for (NSString* currentString in myArrayOfStrings) { NSLog(currentString); } // Equivalent to... for (int i = 0; i < [myArrayOfStrings count]; i++) { NSLog([myArrayOfStrings objectAtIndex:i]); }
while (condition) {
// statement(s) to execute while the condition is true
}
// Example
int myCount = 0;
while ( myCount < 100 )
{
myCount++;
NSLog(@"myCount = %i", myCount);
}
// Prints 1 - 100
// Why not 1 - 99?
do {
// statement(s) to execute while the condition is true
} while (condition);
// Example
int i = 10;
do
{
NSLog(@"%i", i);
i--;
} while (i > 0);
// What should we see here?
BOOL isHuman = NO;
NSLog(@"It's alive: %i", isHuman);
Denotes a single-byte signed integer, and can be used to store values between -128 and 127 or an ASCII character.
char letter = 'z';
NSLog(@"The ASCII letter %c is actually the number %i", letter, letter);;
short int littleInt = 27000;
NSLog(@"The short int is: %hi", littleInt);
int normalInt = 1234567890;
NSLog(@"The normal integer is: %i", normalInt);
long int bigInt = 9223372036854775807;
NSLog(@"The big integer is: %li", bigInt);
Note: The idea behind having so many integer data types is to give developers the power to balance their program's memory footprint versus its numerical capacity.
float someRealNumber = 0.42f;
NSLog(@"The floating-point number is: %f", someRealNumber);
double anotherRealNumber = 0.42;
NSLog(@"The floating-point number is: %5.3f", anotherRealNumber);
typedef struct { float x; float y; } Point2D;
Point2D p1 = {10.0f, 0.5f};
NSLog(@"The point is at: (%.1f, %.1f)", p1.x, p1.y);
p1.x = -2.5f;
p1.y = 2.5f;
int someValues[5] = {15, 32, 49, 90, 14};
for (int i=0; i<5; i++) { NSLog(@"The value at index %i is: %i", i, someValues[i]); }
int someValues[5] = {15, 32, 49, 90, 14};
int *pointer = someValues;
int someValues[5] = {15, 32, 49, 90, 14};
int *pointer = someValues;
NSLog(@"The first value is: %i", *pointer);
pointer++;
NSLog(@"The next value is: %i", *pointer);
for (int i=0; i<5; i++) {
pointer++;
NSLog(@"The value at index %i is: %i", i, *pointer);
}
- (void)sayHello;
A method is a section of code that we can call from elsewhere in our code.
Basic syntax for calling a method on an object:
[object method];
[object methodWithInput:input];
Methods can return a value:
output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];
NSString *myString = [NSString string];
function1 ( function2() );
[NSString stringWithFormat:[prefs format]];
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];
[photo setCaption:@"Day at the Beach"];
output = [photo caption];
photo.caption = @"Day at the Beach";
output = photo.caption;
int someInteger = -27;
NSNumber *someNumber = [NSNumber numberWithInt:someInteger];
NSLog(@"The stored number is: %i", [someNumber intValue]);
//Accessors for other primitives follow the same pattern: floatValue, doubleValue, boolValue, etc.
NSDecimalNumber *subtotal = [NSDecimalNumber decimalNumberWithString:@"10.99"];
- decimalNumberByAdding:(NSDecimalNumber *)aNumber
- decimalNumberBySubtracting:(NSDecimalNumber *)aNumber
- decimalNumberByMultiplyingBy:(NSDecimalNumber *)aNumber
- decimalNumberByDividingBy:(NSDecimalNumber *)aNumber
- (NSUInteger)length // Return the number of characters in the string.
- (unichar)characterAtIndex:(NSUInteger)theIndex // Return the character at theIndex.
NSString *quote = @"Open the pod bay doors, HAL.";
for (int i=0; i<[quote length]; i++) {
NSLog(@"%c", [quote characterAtIndex:i]);
}
// Prints out "Open the pod bay doors, HAL." into the console one letter at a time.
+ (id)stringWithFormat:(NSString *)format ... - Create a string using the same placeholder format as NSLog().
- (NSString *)stringByAppendingString:(NSString *)aString - Append a string to the receiving object.
- (NSString *)stringByAppendingFormat:(NSString *)format ... - Append a string using the same placeholder format as NSLog().
- (NSString *)lowercaseString - Return the lowercase representation of the receiving string.
- (NSString *)substringWithRange:(NSRange)aRange - Return a substring residing in aRange.
- (NSRange)rangeOfString:(NSString *)aString - Search for aString in the receiving string and return the location and length of the result as an NSRange.
- (NSString *)stringByReplacingOccurancesOfString:(NSString *)target withString:(NSString *)replacement - Replace all occurrences of target with replacement.
- (void)appendString:(NSString *)aString - Append aString to the end of the receiving string.
- (void)appendFormat:(NSString *)format ... - Append a string using the same placeholder format as NSLog().
- (void)insertString:(NSString *)aString atIndex (NSUInteger)anIndex - Insert a string into the specified index.
- (void)deleteCharactersInRange:(NSRange)aRange - Remove characters from the receiving string.
- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString - Replace the characters in aRange with aString.
+ (id)arrayWithObjects:(id)firstObject, ... - Create a new array by passing in a list of objects.
- (NSUInteger)count - Return the number of elements in the array.
- (id)objectAtIndex:(NSUInteger)anIndex - Return the element in the array at index anIndex.
- (BOOL)containsObject:(id)anObject - Return whether or not anObject is an element of the array.
- (NSUInteger)indexOfObject:(id)anObject - Return the index of the first occurrence of anObject in the array. If the object is not in the array, return the NSNotFound constant.
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))compareFunction context:(void *)context - Sort an array by comparing objects with a user-defined function.
- (void)addObject:(id)anObject - Add the given object to the end of the existing array.
- (void)insertObject:(id)anObject atIndex:(NSUInteger)anIndex - Insert the given object into the specified index.
- (void)removeObjectAtIndex:(NSUInteger)anIndex - Remove the object at the specified index.
- (void)replaceObjectAtIndex:(NSUInteger)anIndex withObject:(id)anObject Overwrite the object at anIndex with anObject.
- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 - Swap the locations of two objects in the array.
id mysteryObject = [NSNumber numberWithInt:5];
NSLog(@"%@", mysteryObject);
mysteryObject = [NSDecimalNumber decimalNumberWithString:@"5.1"];
NSLog(@"%@", mysteryObject);
mysteryObject = @"5.2";
NSLog(@"%@", mysteryObject);
Class targetClass = [NSString class];
id mysteryObject = [NSNumber numberWithInt:5];
NSLog(@"%i", [mysteryObject isKindOfClass:targetClass]);
mysteryObject = [NSDecimalNumber decimalNumberWithString:@"5.1"];
NSLog(@"%i", [mysteryObject isKindOfClass:targetClass]);
mysteryObject = @"5.2";
NSLog(@"%i", [mysteryObject isKindOfClass:targetClass]);
The Class data type brings the same dynamic capabilities to classes that id brings to objects.