Slide 1

Slide 1 text

Introduction to Objective-C and Cocoa Touch Bryan Irace

Slide 2

Slide 2 text

I. Language

Slide 3

Slide 3 text

“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

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Add methods to existing classes Categories

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

Lambdas, closures, whatever you call them Blocks

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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;

Slide 19

Slide 19 text

II. SDK

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

// `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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

III. Demo

Slide 28

Slide 28 text

IV. Runtime

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

V. Tooling

Slide 33

Slide 33 text

Instruments