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

3770c1b6a421c8d4de4177356911a829?s=128

Bryan Irace

March 26, 2014
Tweet

Transcript

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

  2. I. Language

  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
  4. Classes have separate header and implementation files ! Header files

    declare a class’s “public” interface Class definitions
  5. // Import individual classes, or in this case, a whole

    framework #import <Foundation/Foundation.h> ! // 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
  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
  7. ! [object doSomething]; [object doSomethingWithObject:someArgument anotherObject:otherArgument]; ! [BRYObject initialize];

  8. NSString *string = nil; ! // Won't crash [string description];

    ! // Will return `NO` BOOL stringIsHTMLFileName = [string hasSuffix:@".html"];
  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
  10. @property (nonatomic, copy) NSString *firstName; ! @property (nonatomic, copy) NSString

    *lastName; ! @property (nonatomic, readonly) NSString *fullName; ! @property (nonatomic, getter = isTumblrEmployee) BOOL tumblrEmployee;
  11. “Used to declare methods and properties that are independent of

    any specific class" Protocols
  12. // Protocols can extend other protocols @protocol TMTheming <NSObject> !

    ! - (void)updateTheme:(TMTheme *)theme; ! ! @optional ! ! - (void)someOptionalMethod; ! @end
  13. Add methods to existing classes Categories

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

    @end
  15. Lambdas, closures, whatever you call them Blocks

  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; }];
  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
  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;
  19. II. SDK

  20. Comprised of numerous frameworks (Foundation, UIKit, TextKit, Core Data, AVFoundation,

    etc.) Cocoa Touch
  21. Singleton that allows you to handle application lifecycle events !

    • Application launches • Foreground/background • Push notifications • Inter-app communication App delegate
  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
  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
  24. • Core Data: persistent object graph • SQLite • NSCoding:

    simple object serialization • User defaults: key/value preference store • Keychain: secure, encrypted container Persistence
  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
  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
  27. III. Demo

  28. IV. Runtime

  29. Can specify which objects respond to which selectors at runtime

    ! Can kind of simulate multiple inheritance this way Dynamic method resolution
  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
  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
  32. V. Tooling

  33. Instruments