Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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

    declare a class’s “public” interface Class definitions
  3. // 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
  4. 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
  5. NSString *string = nil; ! // Won't crash [string description];

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

    *lastName; ! @property (nonatomic, readonly) NSString *fullName; ! @property (nonatomic, getter = isTumblrEmployee) BOOL tumblrEmployee;
  8. // Protocols can extend other protocols @protocol TMTheming <NSObject> !

    ! - (void)updateTheme:(TMTheme *)theme; ! ! @optional ! ! - (void)someOptionalMethod; ! @end
  9. 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; }];
  10. 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
  11. 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;
  12. Singleton that allows you to handle application lifecycle events !

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

    simple object serialization • User defaults: key/value preference store • Keychain: secure, encrypted container Persistence
  16. // `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
  17. 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
  18. Can specify which objects respond to which selectors at runtime

    ! Can kind of simulate multiple inheritance this way Dynamic method resolution
  19. 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
  20. Add state to objects without subclassing ! objc_setAssociatedObject(self, UIViewShakeInitialFrameKey, self.frame,

    OBJC_ASSOCIATION_RETAIN_NONATOMIC); self.frame = objc_getAssociatedObject(self, UIViewShakeInitialFrameKey); Associated objects