$30 off During Our Annual Pro Sale. View Details »

Introduction to Objective-C and Cocoa Touch

Introduction to Objective-C and Cocoa Touch

Informal introduction to Objective-C/Cocoa Touch given to Tumblr engineering

Bryan Irace

March 26, 2014
Tweet

More Decks by Bryan Irace

Other Decks in Programming

Transcript

  1. Introduction to Objective-C
    and Cocoa Touch
    Bryan Irace

    View Slide

  2. I. Language

    View Slide

  3. “A superset of the C programming
    language and provides object-
    oriented capabilities and a
    dynamic runtime”
    • Inherits C syntax, primitives, flow control
    • Adds syntax for classes, methods, object literals
    • Dynamically typed, defers a lot to runtime

    View Slide

  4. Classes have separate header and
    implementation files
    !
    Header files declare a class’s “public” interface
    Class definitions

    View Slide

  5. // Import individual classes, or in this case, a whole framework
    #import
    !
    // Prefixed class name (no namespaces ) : superclass
    @interface BRYCalculator : NSObject
    !
    // Instance method with two arguments
    - (NSInteger)add:(NSInteger)number1 toNumber:(NSInteger)number2;
    !
    // Class method ("static" to you Java folk)
    + (void)initialize;
    !
    @end

    View Slide

  6. You don’t “invoke methods,” you “send
    messages.”
    !
    It’s kind of the same thing except any message
    can be sent to any object. More on this later.
    Message sending

    View Slide

  7. !
    [object doSomething];
    [object doSomethingWithObject:someArgument
    anotherObject:otherArgument];
    !
    [BRYObject initialize];

    View Slide

  8. NSString *string = nil;
    !
    // Won't crash
    [string description];
    !
    // Will return `NO`
    BOOL stringIsHTMLFileName = [string hasSuffix:@".html"];

    View Slide

  9. Properties are used to encapsulate your data.
    Accessor methods are created for you by the compiler.
    !
    Should pretty much always use them instead of direct
    instance variables.
    Properties

    View Slide

  10. @property (nonatomic, copy) NSString *firstName;
    !
    @property (nonatomic, copy) NSString *lastName;
    !
    @property (nonatomic, readonly) NSString *fullName;
    !
    @property (nonatomic, getter = isTumblrEmployee) BOOL tumblrEmployee;

    View Slide

  11. “Used to declare methods and properties that are
    independent of any specific class"
    Protocols

    View Slide

  12. // Protocols can extend other protocols
    @protocol TMTheming
    !
    !
    - (void)updateTheme:(TMTheme *)theme;
    !
    !
    @optional
    !
    !
    - (void)someOptionalMethod;
    !
    @end

    View Slide

  13. Add methods to existing classes
    Categories

    View Slide

  14. @interface NSArray (TumblrAdditions)
    !
    - (BOOL)isEmpty;
    !
    - (BOOL)isNotEmpty;
    !
    @end

    View Slide

  15. Lambdas, closures, whatever you call them
    Blocks

    View Slide

  16. view.alpha = 1;
    !
    [UIView animateWithDuration:0.2 animations:^{
    view.alpha = 0;
    }];
    !
    !
    !
    !
    NSArray *array = @[@0, @2, @3, @4, @5];
    !
    array = [array filteredArrayUsingBlock:^BOOL (NSNumber *number) {{
    return [number unsignedIntegerValue] % 2 == 0;
    }];

    View Slide

  17. Thankfully we no longer need to manually allocate and release memory (unless
    using C APIs)
    !
    Still need to be careful to not create retain cycles though
    Memory management

    View Slide

  18. BRYObject *object = [BRYObject new];
    BRYObject *otherObject = [[BRYObject alloc] init];
    object.childObject = otherObject;
    otherObject.childObject = object;
    !
    // Prevent a retain cycle by using a "weak reference"
    @property (nonatomic, weak) NSObject *childObject;

    View Slide

  19. II. SDK

    View Slide

  20. Comprised of numerous frameworks
    (Foundation, UIKit, TextKit, Core
    Data, AVFoundation, etc.)
    Cocoa Touch

    View Slide

  21. Singleton that allows you to handle application lifecycle events
    !
    • Application launches
    • Foreground/background
    • Push notifications
    • Inter-app communication
    App delegate

    View Slide

  22. Base class for almost all views
    !
    • Has a “frame” (coordinates and size), determines where it shows up on
    screen
    • Frame can be set manually or via constraints (AutoLayout)
    • Has an array of “subviews” (forming a hierarchy)
    • Can be configured in code or in Interface Builder
    UIView

    View Slide

  23. Generally one controller visible on screen at a time
    !
    • Provides hooks like “viewWillAppear”, “viewWillDisappear”, rotation
    • View controllers can have children
    • Can implement “container view controllers” (e.g. tab bar,
    navigation bar)
    UIViewController

    View Slide

  24. • Core Data: persistent object graph
    • SQLite
    • NSCoding: simple object serialization
    • User defaults: key/value preference store
    • Keychain: secure, encrypted container
    Persistence

    View Slide

  25. // `self` will be notified when the scroll view’s content offset changes
    [scrollView addObserver:self forKeyPath:@“contentOffset”];
    !
    // `[self wipeDatabase:]` will be called when notification is posted
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(wipeDatabase:)
    name:@"UserDidLogoutNotification"];
    Observing changes

    View Slide

  26. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 2;
    !
    [queue addOperationWithBlock:^{
    // Do something on a background thread
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    // Update the UI on the main thread
    }];
    }];
    Concurrency

    View Slide

  27. III. Demo

    View Slide

  28. IV. Runtime

    View Slide

  29. Can specify which objects respond to which
    selectors at runtime
    !
    Can kind of simulate multiple inheritance this way
    Dynamic method resolution

    View Slide

  30. SEL originalSelector = NSSelectorFromString(@"signRequest:withParameters:");
    SEL newSelector = NSSelectorFromString(@"addHeadersAndSignRequest:withParameters:");
    !
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method newMethod = class_getInstanceMethod(class, newSelector);
    method_exchangeImplementations(originalMethod, newMethod);
    !
    - (void)addHeadersAndSignRequest:(NSMutableURLRequest *)request
    withParameters:(NSDictionary *)parameters {
    // TODO: Add headers to request
    // Call original method by sending *new* message (because we swapped them,
    remember?)
    [self addHeadersAndSignRequest:request withParameters:parameters];
    }
    Swizzling

    View Slide

  31. Add state to objects without subclassing
    !
    objc_setAssociatedObject(self, UIViewShakeInitialFrameKey, self.frame,
    OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    self.frame = objc_getAssociatedObject(self, UIViewShakeInitialFrameKey);
    Associated objects

    View Slide

  32. V. Tooling

    View Slide

  33. Instruments

    View Slide