Objective-C Cheat Sheet

This cheat sheet is from this link, with highlighting added by myself.

// The Foundation framework contains many fundamental
// classes used to develop Objective C programs
#import 

// Used for classes in the project
#import "Animal.h"
#import "Koala.h"
#import "Animal+Exam.h"
#import "Dog.h"

// @1 becomes [NSNumber numberWithInteger:1] during the compiling. It's really just a shorthand means of creating an object out of a literal.

int main(int argc, const char * argv[]) {
    // Memory is set aside for the app and when objects
    // are no longer needed their allocated memory
    // is released for other apps

    // The ARC (Automatic Reference Counting)
    // signals for the destruction of objects
    // when they are not needed
    @autoreleasepool { 
  
        // Works like printf
        NSLog(@"Hello, World!");
  
        // nil is used to define a nonexistent object
        NSString *nothing = nil; 
        NSLog(@"Location of nil : %p", nothing); 
  
        // Create a pointer to where the NSString
        // object is
        // A NSString can hold unicode characters
        NSString *quote = @"Dogs have masters, while cats have staff"; 
  
        // You execute a method in the object you follow
        // the object name with the method (Message)
        NSLog(@"Size of String : %d", (int)[quote length]); 
  
        // Returns the data stored in NSString
        NSLog(@"NSString : %@", quote); 
  
        // Get the character at index 5
        // You pass arguments after the :
        NSLog(@"Character at 5 : %c", [quote characterAtIndex:5]); 
  
        // Use stringWithFormat to create a dynamic string
        char *name = "Derek"; 
        NSString *myName = [NSString stringWithFormat:@"- %s", name]; 
  
        // Test if 2 strings are equal
        BOOL isStringEqual = [quote isEqualToString:myName]; 
        printf("Are strings equal : %d\n", isStringEqual); 
  
        // How to convert a NSString to a String
        // How to nest messages
        // Also available: lowercaseString, capitalizedString
        const char *uCString = [[myName uppercaseString]UTF8String]; 
        printf("%s\n", uCString); 
  
        // How to combine strings
        NSString *wholeQuote = [quote stringByAppendingString:myName]; 
  
        // Searching for strings
        NSRange searchResult = [wholeQuote rangeOfString:@"Derek"]; 
        if (searchResult.location == NSNotFound) { 
            NSLog(@"String not found");
        } else { 
            printf("Derek is at index %lu and is %lu long\n",
                  searchResult.location,
                  searchResult.length);
        }
  
        // Replace a substring by defining at what index
        // to start and how many letters to replace
        NSRange range = NSMakeRange(42, 5); 
        const char *newQuote = [[wholeQuote stringByReplacingCharactersInRange:range withString:@"Anon"]UTF8String]; 
        printf("%s", newQuote); 
  
        // Create a mutable string with a starting capacity
        // of 50 characters, NSString or immutable, meaning every time they change, a new string is created
        NSMutableString *groceryList = [NSMutableString stringWithCapacity:50]; 
  
        // Append a value to the string
        [groceryList appendFormat:@"%s","Potato, Banana, Pasta"]; 
  
        NSLog(@"groceryList : %@", groceryList); 
  
        // Delete characters in a range (Start, Length)
        [groceryList deleteCharactersInRange:NSMakeRange(0,8)]; 
  
        NSLog(@"groceryList : %@", groceryList); 
  
        // Insert string at index
        [groceryList insertString:@", Apple" atIndex:13]; 
        NSLog(@"groceryList : %@", groceryList); 
  
        // Replace characters in a range
        [groceryList replaceCharactersInRange:NSMakeRange(15, 5) withString:@"Orange"]; 
        NSLog(@"groceryList : %@", groceryList); 
  
        // Create an Array
        NSArray *officeSupplies = @[@"Pencils", @"Paper"]; 
        NSLog(@"First : %@", officeSupplies[0]); 
        NSLog(@"Office Supplies : %@", officeSupplies); 
  
        // Search for item in array
        BOOL containsItem = [officeSupplies containsObject:@"Pencils"]; 
        NSLog(@"Need Pencils : %d", containsItem); 
  
        // Number of items in array
        NSLog(@"Total : %d", (int)[officeSupplies count]); 
  
        NSLog(@"Index of Pencils is %lu",(unsigned long)[officeSupplies indexOfObject:@"Pencils"]); 
  
        // Create a mutable array and add objects
        NSMutableArray *heroes = [NSMutableArray arrayWithCapacity:5]; 
        [heroes addObject:@"Batman"]; 
        [heroes addObject:@"Flash"]; 
        [heroes addObject:@"Wonder Woman"]; 
        [heroes addObject:@"Kid Flash"]; 
  
        // Insert into an index
        [heroes insertObject:@"Superman" atIndex:2]; 
  
        NSLog(@"%@",heroes);
  
        // Remove objects
        [heroes removeObject:@"Flash"]; 
        NSLog(@"%@",heroes);
  
        [heroes removeObjectAtIndex:0]; 
        NSLog(@"%@",heroes);
  
        [heroes removeObjectIdenticalTo:@"Superman" inRange:NSMakeRange(0, 1)]; 
        NSLog(@"%@",heroes);
  
        // Iterate through array
        for (int i=0; i < [heroes count]; i++) { 
            NSLog(@"%@",heroes[i]);
        }
  
        // ---------- Objects ----------
  
        // Allocate memory for an object and initialize it
        Animal *dog = [[Animal alloc] init]; 
  
        // Call the method for our object
        [dog getInfo]; 
  
        // How to get a value stored in an instance
        // variable
        NSLog(@"The dogs name is %@", [dog name]); 
  
        // Set the value for an instance variable
        [dog setName:@"Spot"]; 
  
        NSLog(@"The dogs name is %@", [dog name]); 
  
        // Call the custom init
        Animal *cat = [[Animal alloc]initWithName:@"Whiskers"]; 
  
        // You can also access variables with dot
        // notation
        NSLog(@"The cats name is %@", cat.name); 
  
        // Call the method weightInKg
        NSLog(@"180 lbs = %.2f kg", [dog weightInKg:180]); 
  
        // Pass attributes to be added
        NSLog(@"3 + 5 = %d", [dog getSum:3 nextNumber:5]); 
  
        // Pass in a NSString
        NSLog(@"%@", [dog talkToMe:@"Derek"]); 
  
        // Create a Koala that inherits from Animal
        Koala *herbie = [[Koala alloc]initWithName:@"Herbie"]; 
  
        // The overridden method is used
        NSLog(@"%@", [herbie talkToMe:@"Derek"]); 
  
        // Categories allow you to split a class into
        // many files to keep file sizes manageable
        // File > New > Objective-C file under Sources
        // Select Category and Animal class
        NSLog(@"Did %@ receive shots : %d", herbie.name, [herbie checkedByVet]); 
  
        [herbie getShots]; 
  
        // You can also allow files to import a
        // category and block access unless the
        // class is a subclass using protected
        // File > New > Objective-C file under Sources
        // Select Category and Animal class
  
        [dog getInfo]; 
  
        // A protocol is a bunch of properties and
        // methods that a any class can implement
        // File > New > Objective-C file under Sources
        // Select Protocol -> BeautyContest
        [herbie lookCute]; 
        [herbie performTrick]; 
  
        // A block is an anonymous function in Objective
        // C. First you declare it
        float (^getArea) (float height, float width); 
  
        // Create and assign the block
        getArea = ^float(float width, float height) { 
            return width * height; 
        };
  
        NSLog(@"Area of 3 width and 50 height : %.1f", getArea(3,50)); 
  
        // ---------- Enums ----------
        // Used to define a custom variable with
        // a set of constants
        enum Ratings { 
            Poor = 1, 
            OK = 2, 
            Average = 3, 
            Good = 4, 
            Great = 5 
        };
  
        enum Ratings matrixRating = Great; 
  
        NSLog(@"Matrix Rating %u", matrixRating); 
  
        // ---------- Dynamic Binding ----------
        Dog *grover = [[Dog alloc]initWithName:@"Grover"]; 
  
        NSArray *animals = [[NSArray alloc]initWithObjects: herbie, grover, nil]; 
  
        // An id is a pointer to any object type
        // and yet the correct method is called
        // automatically
        id object1 = [animals objectAtIndex:0]; 
        id object2 = [animals objectAtIndex:1]; 
  
        [object1 makeSound]; 
        [object2 makeSound]; 
  
        // ---------- Exceptions ----------
        // It is best to protect against possible
        // errors and inform the user of what happened
        // and we do that with exception handling
        // You can find the built in exceptions here
        /*  developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Concepts/PredefinedExceptions.html#//apple_ref/doc/uid/20000057-BCIGHECA
         */
        NSArray *dogs = @[@"Spot", @"Bowser"]; 
  
        @try { 
            NSLog(@"%@", dogs[3]); 
        }
        @catch(NSException *e) { 
  
            NSLog(@"Exception : %@", e); 
            return 0; 
        }
  
    }
    return 0; 
}






Amimal.h

#import <Foundation/Foundation.h>
  
// In Objective C your class is made up of an interface
// and implementation
// Define the properties and methods this class will have
@interface Animal : NSObject 
  
// Define attributes of your objects
// They can't be directly accessed, but getter and
// setter methods are automatically generated
  
// You could put (readonly) before a property if you
//don't want a getter generated :
// @property (readonly) NSString *name;
@property NSString *name; 
@property NSString *favFood; 
@property NSString *sound; 
  
// Primitive type doesn't require a *
@property float weight; 
  
// Must define this with custom init
-(instancetype) initWithName:(NSString*) defaultName; 
  
// Define what an object can do
// - means it is an instance method
// + means it is a class method and can't access instance data
- (void) getInfo; 
  
// Returns a float and receives a float
-(float) weightInKg:(float) weightInLbs; 
  
// If you are using objects you need pointers
-(NSString *) talkToMe: (NSString *) myName; 
  
// Receive multiple parameters
// nextNumber can be named anything
-(int) getSum: (int) num1 
     nextNumber: (int) num2; 
  
// Demonstrate dynamic binding
-(void) makeSound; 
  
@end




Animal.m

// NSObject
#import "Animal.h"
#import "Animal+Vet.h"
  
@implementation Animal 
// Here is where you define instance variables you don't
// want people to be able to access directly
{
    int shelterID; 
}
  
// Open Utilities Panel > Click {} > Type init
// Define initial values for object here
- (instancetype)init 
{
    // self refers to the instance being initialized
    // since I don't know its defined name
    // super is the superclass NSSObject init
    self = [super init]; 
    if (self) { 
        self.name = @"No Name"; 
    }
    return self; 
}
  
// Create a custom init and add it to the header file
- (instancetype)initWithName:(NSString*) defaultName 
{
    self = [super init]; 
    if (self) { 
        self.name = defaultName; 
    }
    return self; 
}
  
-(void) getInfo { 
    NSLog(@"Random Information");
  
    // Call protected category method
    [self getExamResults]; 
}
  
-(float)weightInKg:(float)weightInLbs { 
    return weightInLbs * 0.4535; 
}
  
-(int)getSum:(int)num1 nextNumber:(int)num2{ 
    return num1 + num2; 
}
  
-(NSString *)talkToMe:(NSString *)myName{ 
  
    NSString *response = [NSString stringWithFormat:@"Hello %@", myName]; 
    return response; 
}
  
// Demonstrate dynamic binding
-(void) makeSound{ 
    NSLog(@"Grrrrrrrr");
}
  
@end










---------- KOALA.H ---------- 
  
#import "Animal.h"
#import "BeautyContest.h" // Protocol
  
// With inheritance you can inherit all of a classes
// properties and methods
  
// Adopt the protocol by adding it here and then
// add the methods in Koala.m
@interface Koala : Animal  
  
// You can override methods
-(NSString *) talkToMe: (NSString *) myName; 
  
@end
  
---------- KOALA.M ---------- 
  
#import "Koala.h"
  
@implementation Koala 
  
-(NSString *)talkToMe:(NSString *)myName{ 
  
    NSString *response = [NSString stringWithFormat:@"Hello %@ says %@", myName, self.name]; 
    return response; 
}
  
-(void)lookCute{
    NSLog(@"%@ acts super cute", self.name); 
}
-(void)performTrick{
    NSLog(@"%@ performs a hand stand", self.name); 
}
  
-(void) makeSound{ 
    NSLog(@"%@ says Yawn", self.name); 
}
  
@end
  
---------- ANIMAL+EXAM.H ---------- 
  
#import "Animal.h"
  
@interface Animal (Exam) 
  
// At runtime these methods become part of the Animal
// class
- (BOOL)checkedByVet; 
- (void)getShots; 
  
@end
  
---------- ANIMAL+EXAM.M ---------- 
  
#import "Animal+Exam.h"
  
@implementation Animal (Exam) 
  
// Define method definitions
- (BOOL) checkedByVet{ 
    return 1; 
}
  
- (void) getShots { 
    NSLog(@"%@ got its shots", self.name); 
}
  
@end
  
---------- ANIMAL+VET.H ---------- 
  
#import "Animal.h"
  
@interface Animal (Protected) 
  
- (void)getExamResults; 
  
@end
  
---------- ANIMAL+VET.M ---------- 
  
#import "Animal+Vet.h"
  
@implementation Animal (Protected) 
  
-(void)getExamResults{
    NSLog(@"The exam for %@ came back fine", self.name); 
}
  
@end
  
---------- BEAUTYCONTEST.H ---------- 
  
#import <Foundation/Foundation.h>
  
@protocol BeautyContest <NSObject> 
  
-(void)lookCute;
-(void)performTrick;
  
@end
  
---------- DOG.H ---------- 
  
#import "Animal.h"
  
@interface Dog : Animal 
  
@end
  
---------- DOG.M ---------- 
  
#import "Dog.h"
  
@implementation Dog 
  
-(void) makeSound{ 
    NSLog(@"%@ says Woooff", self.name); 
}