Learn Objective C in One Video

Objective C TutorialIn this video I’ll teach most of the objective C programming language in one video. I’ll also teach a great deal of the C programming language as well.

I’ll cover compiling, include, variables, data types, functions, pointers, structs, main, printf, formatting, scanf, comparison operators, logical operators, if, else, ternary operator, math, casting, order of operations, looping, ARC, NSLog, classes, objects, NSLog, NSString, NSRange, NSArray, NSMutableString, NSMutableArray, init, alloc, inheritance, categories, protocols, blocks, enums, dynamic binding and more.

If you like videos like this, please tell Google with a click here [googleplusone]

Code From the Video

main.c

//  main.c
//  OCTut

/*
 Multiline Comment
*/

// Imports prewritten functions we can use
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <stdbool.h>
#include <math.h>
#include <readline/readline.h>

// Code in main is executed when a program runs

// If you execute the program from the command
// line you can pass the number of words
// being passed and a list of words in an array

// gcc main.c -std=c99 compiles the program
// ./a.out Hello Here are Arguments executes

// ---------- Functions & Variables ----------
// Functions allow you to reuse and better organize code

// void means that the function doesn't return a value
// To pass a string you pass a pointer at the location
// in memory and the star provides the value

// A global variable can be accessed by any function
float piVal = 3.14159265;

// A static variable can only be accessed by functions in
// the file main.c
// static float eulerConstant = .57721;

void convertData(char *name, float height, float weight){
    name = "Phil";
    height = height * 12 * 2.54;
    weight = weight * .453592;
    printf("%s is %.1f cms tall and weighs %.2f kg\n",
           name, height, weight);
}

// Returns a float after the addition

float sum(float num1, float num2){
    return num1 + num2;
}

// If you are being passed an address use * for the attribute
void changeNumber(int *number){

    // You assign a value to an address by using *
    *number = 98765;
}

// ---------- Structs ----------
// Allows you to create a custom variable with more then
// one type of data

struct Superhero {
    char *realName;
    char *superName;
    float height;
    float weight;
};

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

    // printf is a function that prints the text between
    // the quotes to the screen
    // \n is a newline that skips the screen to the
    // next line
    // Every statement ends with a semicolon
    printf("Hello, World!\n");

    // A for loop executes code the number of times
    // you specify

    // Keep printing words until none are left
    for( int i = 0; i < argc; i++ )
    {

        // Print the word number followed by the word
        // %d is used for numbers and %s for words or
        // Strings
        printf( "arg %d: %s\n", i, argv[i] );
    }

    // ---------- Variable Types ----------

    // short(%d), int(%d), long(%ld) : Whole Numbers
    // float(%f), double(%lf) : Numbers with decimals
    // char(%c) : Single Characters
    // struct : Custom Type
    // Pointer : Holds the location of data in memory

    float fTemp;

    printf("Enter Temp in F: ");

    // You can get user input with scanf
    scanf("%f", &fTemp);

    //°F =°C * 1.8000 + 32.00
    float cTemp = (fTemp - 32) / 1.8;

    printf("%.1f° Celsius\n", cTemp);

    // This is the biggest Integer
    int bigInt = 2147483647;
    printf("Big Int : %d\n", bigInt + 1);

    // This is the biggest Long
    long bigLong = 9223372036854775807;
    printf("Big Long : %ld\n", bigLong + 1);

    // Biggest Floats
    printf("Minimum Float : %e\n", FLT_MIN);
    printf("Maximum Float : %f\n", FLT_MAX);

    // Floats / Doubles lose precision after 6 digits
    float pi = 3.1415926;
    printf("3.1415926 + .0000001 = %.7f\n", pi + .0000001);
    printf("Precise Decimal Digits : %d", FLT_DIG);

    // ---------- if / else ----------
    // Comparison Operators : < > <= >= == !=

    int age = 13;

    if (age <= 6){
        printf("You're in Kindergarten\n");
    } else if (age <= 13) {
        printf("You're in Elementary School\n");
    } else {
        printf("You're in High School\n");
    }

    // Logical Operators : && || !

    if ((age >= 12) || (age <= 13)) {
        printf("You're in Elementary School\n");
    }

    // The Boolean type : true = 1 & false = 0
    bool isElementary = ((age >= 12) && (age <= 13));

    printf("Is in elementary : %d\n", isElementary);

    printf("Opposite of True : %d\n", (!true));

    // Ternary Operator
    bool isHighSchool = (age > 13) ? 1 : 0;
    printf("Is in HS : %d\n", isHighSchool);

    // Any variables declared in an if statement are not
    // available outside the if statement

     int total = 10;
     if (total < 11) {
     float randomFloat = 1.234;
     }
     printf("%f\n", randomFloat);

    // ---------- Math ----------

    printf("3 + 2 = %d\n", 3 + 2);
    printf("3 - 2 = %d\n", 3 - 2);
    printf("3 * 2 = %d\n", 3 * 2);
    printf("3 / 2 = %d\n", 3 / 2);
    printf("3 %% 2 = %d\n", 3 % 2);

    // Use cast to get decimals
    printf("3 / 2 = %f\n", 3 / (float) 2);

    // Order of operations
    printf("2 + 1 * 3  = %d\n", 2 + 1 * 3);
    printf("(2 + 1) * 3  = %d\n", (2 + 1) * 3);

    int i = 0;

    // Shorthand addition (++ or --)
    printf("i++ = %d\n", i++);
    printf("++i = %d\n", ++i);

    // You also use -= *= /= %=
    printf("i += 5 %d\n", i += 5);

    // Many math functions
    // ceil(double), floor(double), fabs(double)
    // sqrt(double), exp(double), exp2(double)
    // log(double), log2(double), pow(double, double)

    // ---------- Looping ----------

    for (int i = 1; i <= 10; i++) {

        if (i == 9) {

            // break throws you out of the loop
            break;
        }

        if (i == 7) {

            // Continue skips the rest of the code
            // in the loop
            continue;
        }

        // Only lets odds print because if the number
        // is divisible by 2 you get 0 or false
        if(i % 2){
            printf("i : %d\n", i);
        }

    }

    int j = 1;

    while (j <= 10) {
        printf("j : %d\n", j);
        j++;
    }

    int guess;

    // Used when you must loop once
    do {
        printf("Guess Between 0 and 20 : ");
        scanf("%d", &guess);

    } while (guess != 15);

    // ---------- Functions ----------

    // Call the function name and pass values

    char *name = "Derek";

    convertData(name, 6.25, 179);

    // This would cause an error because the value for height
    // is only in the function convertData
    // printf("%f", height);

    // Values changed in a function don't apply outside the
    // function (For Now)
    printf("Name in main : %s\n", name);

    printf("5 + 6 = %.1f\n", sum(5,6));

    // ---------- Pointers ----------
    // Data is stored in memory at addresses
    // Memory is like a bunch of boxes and the data type
    // used defines how many boxes you need

    int randNum = 12345;

    // Get the address of a variable
    printf("randNum Memory Location : %p\n", &randNum);

    // Store the address using the same data type and *
    int *addrRandNum = &randNum;

    // Store a different value in the same location
    *addrRandNum = 54321;

    printf("randNum Value : %d\n", randNum);

    // The memory location is the same with a new value
    printf("randNum Memory Location : %p\n", &randNum);

    // Get the number of bytes for our integer
    printf("randNum is %zu bytes\n", sizeof(randNum));

    // If you send the address of a var you can change
    // its value in a function (Pass By Reference)
    int number = 12345;
    changeNumber(&number);
    printf("number Value : %d\n", number);

    // ---------- Structs ----------

    struct Superhero superman;
    superman.realName = "Clark Kent";
    superman.superName = "Superman";
    superman.height = 6.25;
    superman.weight = 235;

    printf("%s is the hero named %s. He is %.2f ft tall and weighs %.1f lbs\n", superman.realName, superman.superName,
           superman.height, superman.weight);

    // returning 0 means everything is ok
    return 0;
}

main.m

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

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

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
        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;
}

Animal.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

// File > New > File > Cocoa Class > Objective C File
// 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

All the Other Files

---------- 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 <BeautyContest>

// 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);
}

@end

Leave a Reply

Your email address will not be published. Required fields are marked *