Slide 1

Slide 1 text

Objective-C A Beginner’s Dive

Slide 2

Slide 2 text

I Assume • A Background in Java or C++ • An understanding of OOP • A basic understanding of C

Slide 3

Slide 3 text

What is Objective-C? • Superset of C • Smalltalk style Object-Oriented • The Official Language for iOS and OS X

Slide 4

Slide 4 text

Cool! But before we dive in...

Slide 5

Slide 5 text

Hello World! // // main.m #include #include int main(int argc, const char **argv) { NSString *message = @"Hello World!"; printf("%s\n", [message cString]); return 0; }

Slide 6

Slide 6 text

Hello World! • Objective-C String Literal • @”Hello World!” • C Function • printf() • main() • Objective-C message • [message cString] // // main.m #include #include int main(int argc, const char **argv) { NSString *message = @"Hello World!"; printf("%s\n", [message cString]); return 0; }

Slide 7

Slide 7 text

Ok. Now, on to the teaching!

Slide 8

Slide 8 text

Objective-C Features • C Functions • C Structs • C Unions • C Pointers • C Arrays • C Everything Else

Slide 9

Slide 9 text

Objective-C Features • Objects • Methods • Inheritance • Properties • Protocols • Categories • Data and Collections • Object Literals • Object Subscripts • Forin loops • Blocks and Closures • ARC

Slide 10

Slide 10 text

You Will Learn About • Making and Using Objects • Using Foundation Framework Data Types • Automatic Reference Counting (ARC)

Slide 11

Slide 11 text

Writing Objects A Quick Run-Through

Slide 12

Slide 12 text

Objects • Interface • like Java’s Interface, but every object has one • placed in the header file • Implementation • must fill minimum requirements of Interface • placed in the implementation file

Slide 13

Slide 13 text

Example Object // // MyObject.h // Interface #import @interface MyObject : NSObject { int _myInt; } // method declarations go here @end // // MyObject.m // Implementation #import “MyObject.h” @implementation MyObject // method implementations go here @end

Slide 14

Slide 14 text

Objects (More Info) • Objects have Instance Variables (ivars) • No Class variables, use C static globals • No enforced “public” and “private” • Object Instances can be of type: •id •Class *

Slide 15

Slide 15 text

Object Methods • Class Method or Instance Method • Variables are “named” in the method’s signature (fancy word for method name) • Default return and variable type is id

Slide 16

Slide 16 text

Format of a Method +/- (return type)methodName; +/- (return type)methodWithVar:(var type)var; +/- (return type)methodWithVar1:(var type)var1 ! ! ! ! ! ! ! ! var2:(var type)var2; + Class Method!! - Instance Method

Slide 17

Slide 17 text

Method Examples // // MyObject.m // Implementation #import “MyObject.h” @implementation MyObject // setter - (void)setMyInt:(int)myInt { _myInt = myInt; } // getter - (int)myInt { return _myInt; } @end // // MyObject.h // Interface #import @interface MyObject : NSObject { int _myInt; } // setter - (void)setMyInt:(int)myInt; // getter - (int)myInt; @end

Slide 18

Slide 18 text

Object Method Calling • Not like C, C++, or Java • Based on Smalltalk message passing • The Square Brackets [] are your friend! [object method]; [object methodWithVar:value]; [object methodWithVar1:val1 ! ! ! ! ! ! ! ! var2:val2];

Slide 19

Slide 19 text

Testing Responsiveness to a Selector • The name of a method is its Selector SEL mySelector = selector(myMethodWithParameter:) • Every object inherits respondsToSelector: • Takes the selector to test for • Returns YES when the object can respond to that method • Returns NO when the object cannot respond to that method

Slide 20

Slide 20 text

Object Constructor • Not a special method (unlike Java) • Just an instance method to set up the Object’s Instance Variables • Generally named init

Slide 21

Slide 21 text

Generic Constructor - (id)init { if (self = [super init]) { // initialize variables } return self; }

Slide 22

Slide 22 text

Constructor Example // default constructor - (id)init { // calls my custom constructor return [self initWithInt:0]; } // custom constructor - (id)initWithInt:(int)myInt { if (self = [super init]) { _myInt = myInt; } return self; }

Slide 23

Slide 23 text

Inheritance • Single Inheritance from Objects • Method Overloading Supported • Superclass defined in the Interface • Super class referenced with super

Slide 24

Slide 24 text

Inheritance Example // // MyObject.m // Implementation #import “MyObject.h” @implementation MyObject - (id)init { if (self = [super init]) { _myInt = 5; } return self; } @end // // MyObject.h // Interface #import @interface MyObject : NSObject { int _myInt; } - (id)init; @end

Slide 25

Slide 25 text

Properties • Syntactic sugar for variable, accessor, and mutator declarations all-in-one • Properties are declared in the Interface and synthesized in the Implementation • Let you use “dot syntax” with getters and setters ! myObjectInstance.myInt = 5; ! int x = myObjectInstance.myInt;

Slide 26

Slide 26 text

Property Example // // NSString+Reverse.m // Category #import "NSString.h" @implementation MyObject // creates variable _myInt // creates getter myInt // creates setter setMyInt: @synthesize myInt = _myInt; @end // // NSString+Reverse.h // Category #import @interface MyObject : NSObject @property (assign, nonatomic) int myInt; @end

Slide 27

Slide 27 text

More on Properties • Attributes strong weak copy assign readonly atomic nonatomic • @synthesize vs @dynamic ! @synthesize variable = nameOfIvar; • Default ivar name for variable is _variable • Custom getters and setters getter = myGetter, setter = mySetter:

Slide 28

Slide 28 text

Protocols • Like an Objective-C Interface • Similar to Java Interfaces • Can implement multiple Protocols • Protocols can ‘inherit’ other Protocols

Slide 29

Slide 29 text

Example Protocol // // MyProtocol.h // Protocol #import @protocol MyProtocol @property (assign, nonatomic) int myInt; - (NSString *)stringMyInt; @end // // MyObject.h // Interface #import #import "MyProtocol.h" @interface MyObject : NSObject @end

Slide 30

Slide 30 text

Categories • The ability to add new methods to an Object • Changes apply to all instances of the object • Overwrites any methods that already exist in the class • Cannot add Properties and ivars • Can be dangerous

Slide 31

Slide 31 text

Example Category // // NSString+Reverse.m // Category #import "NSString+Reverse.h" #import @implementation NSString (Reverse) - (NSString *)reverse { int length = [self length]; char *newString = ! ! calloc(length+1, sizeof(char)); int current = 0; const char *cstr = [self cString]; for (int i=length-1; i >= 0; i--) { newString[current] = cstr[i]; current++; } NSString *new = ! ! [NSString stringWithCString:newString]; free(newString); return new; } @end // // NSString+Reverse.h // Category #import @interface NSString (Reverse) - (NSString *)reverse; @end

Slide 32

Slide 32 text

Class Extension • Like Categories, but with the ability to add ivars and Properties • Implementations of methods required in the main Implementation block • Can be used to declare “private” methods

Slide 33

Slide 33 text

Class Extension Example // // MyObject.m // Class Extension @interface MyObject () @property (assign) int myPrivateInt; @end // Implementation @implementation MyObject @synthesize myPrivateInt = _myPrivateInt; // more implementation here @end

Slide 34

Slide 34 text

Ok. Now, lets take a look at MyObject

Slide 35

Slide 35 text

MyObject // // MyObject.m #import "MyObject.h" @interface MyObject () @property (assign, nonatomic) int myPrivateInt; @end @implementation MyObject @synthesize myInt = _myInt; @synthesize myPrivateInt = _myPrivateInt; - (id)init { return [self initWithInt:0]; } - (id)initWithInt:(int)myInt { if (self = [super init]) { _myInt = myInt; ! ! _myPrivateInt = 5; } return self; } - (NSString *)stringMyInt { return [NSString stringWithFormat:@"%d", _myInt]; } @end // // MyObject.h #import #import "MyProtocol.h" @interface MyObject : NSObject @property (assign, nonatomic) int myInt; // default constructor - (id)init; // custom constructor - (id)initWithInt:(int)myInt; @end

Slide 36

Slide 36 text

Great But how do I use it?

Slide 37

Slide 37 text

Using MyObject MyObject *obj = [[MyObject alloc] init]; obj.myInt = 5; NSLog(@"%i\n", obj.myInt); MyObject *other = [MyObject alloc]; other = [other initWithInt:5]; [other setMyInt:10]; NSLog(@"%i\n", [obj myInt]);

Slide 38

Slide 38 text

Using MyObject • alloc class method • use of init and initWithInt: methods • splitting up the alloc and init method calls • use of dot syntax and generated methods • NSLog() for printing messages to the console MyObject *obj = [[MyObject alloc] init]; obj.myInt = 5; NSLog(@"%i\n", obj.myInt); MyObject *other = [MyObject alloc]; other = [other initWithInt:5]; [other setMyInt:10]; NSLog(@"%i\n", [obj myInt]);

Slide 39

Slide 39 text

One More Thing Imports and Forward Declarations

Slide 40

Slide 40 text

Imports • Objective-C introduces the #import Preprocessor Directive #import "MyHeaderFile.h" #import • Guarantees the file is only included once • Better Practice than C’s #include

Slide 41

Slide 41 text

Forward Declarations • A Promise to the Compiler that a Class or Protocol will exist at Compile Time @class PromisedObject; @protocol PromisedProtocol; • Minimizes the amount of #includes

Slide 42

Slide 42 text

Objective-C Data What you get with the Foundation Framework

Slide 43

Slide 43 text

nil • Represents the absence of an object • Messages passed to nil return nil • nil is for objects, NULL is for C pointers

Slide 44

Slide 44 text

YES and NO • Boolean type BOOL for “true” and “false” • Use BOOL with YES and NO • Dont use _Bool or bool with true and false from stdbool.h

Slide 45

Slide 45 text

NSNumber • Object Representation for Integers, Booleans, Floats, Doubles, Characters, etc. • Object Literal Syntax @1 @1.0 @YES @NO @(1+2) @'a'

Slide 46

Slide 46 text

NSString • Immutable string • NSMutableString for mutable strings • Object Literal Syntax @"Hello World!" @("Hello World!")

Slide 47

Slide 47 text

NSArray • Immutable object array • NSMutableArray for mutable arrays • Object Literal Syntax @[object1, object2, ..., objectN]; • Object Subscripting Syntax array[0] = object; id object = array[0];

Slide 48

Slide 48 text

NSDictionary • Immutable object dictionary • NSMutableDictionary for mutable • Object Literal Syntax @{key1:value1, key2:value2, ...}; • Object Subscripting Syntax dictionary[key] = object; id object = dictionary[key];

Slide 49

Slide 49 text

Implementing Array Subscripting • Accessing Objects objectAtIndexedSubscript: • Setting Objects setObject:atIndexedSubscript: • The index subscript must be an integral

Slide 50

Slide 50 text

Implementing Dictionary Subscripting • Accessing Object values with key Objects objectForKeyedSubscript: • Setting Object values with key Objects setObject:forKeyedSubscript:

Slide 51

Slide 51 text

Forin Loops • Loop over the contents of a collection • Foundation Framework collections NSArray NSDictionary • Any implementation of the NSFastEnumeration Protocol • Any Subclass of NSEnumerator

Slide 52

Slide 52 text

Forin Loops Example NSArray *array = @[@1, @2, @3, @4, @5]; for (NSNumber *num in array) { NSLog(@"%@", num); } for (id num in [array reverseObjectEnumerator]) { NSLog(@"%@", num); }

Slide 53

Slide 53 text

Objective-C Blocks • Functions you can declare within functions • Can close-over variables for later use • Can pass block functions around like data

Slide 54

Slide 54 text

Block Syntax • Similar to C Function Pointer Syntax return_type (^name)(parameter types) = ! ^(parameter list) { ! ! // do stuff ! }; return_type (^name)() = ^{ ! ! // do stuff ! ! // takes no parameters ! };

Slide 55

Slide 55 text

Block Example int multiplier = 5; int (^mult)(int) = ^(int num){ return num * multiplier; }; int num = mult(5); // num = 25 __block int number = 0; void (^increment)() = ^{ number++; }; increment(); // number = 1 increment(); // number = 2 The block itself has read access to variables defined in the lexical scope at the creation of the block. The block can close over outside variables and modify their values by declaring the variable with the __block modifier.

Slide 56

Slide 56 text

Type-Safe Enums • Enums that you can declare the type they enumerate over • int, char, unsigned char, NSUInteger, ... • Syntax similar to Object Subclassing typedef enum MyEnum : NSUInteger { A, B, C } MyEnum; enum MyUnsignedCharEnum : unsigned char { FIRST, SECOND, THIRD }; typedef enum MyUnsignedCharEnum MyUnsignedCharEnum; typedef enum : NSUInteger { ONE, TWO, THREE } AnotherEnum;

Slide 57

Slide 57 text

Automatic Reference Counting What it is, and what it means to you

Slide 58

Slide 58 text

Referencing Counting • Nearly-Manual Memory Management • Objects have a counter showing how many references are using them • Retain Objects when you receive them [object retain]; • Release Objects when you’re done using them [object release]; • Objects deallocate themselves when their retain count reaches 0

Slide 59

Slide 59 text

Automatic Reference Counting (ARC) • Almost Compile Time Garbage Collection • Retain and Release messages are added at compile time by the compiler • ARC manages when to do this for you • strong variables are Retained when assigned • weak variables are not Retained on assignment and are zeroed out when deallocated

Slide 60

Slide 60 text

Retain Cycle • Two Objects Reference Each Other • Their retain counts can never reach 0 • Set one of the references to weak to prevent one of the objects from retaining the other and causing a cycle

Slide 61

Slide 61 text

So there you have it Objective-C thrown at you

Slide 62

Slide 62 text

Useful References • Programming with Objective-C http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ ProgrammingWithObjectiveC/Introduction/Introduction.html http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf • Objective-C Cheat Sheet and Quick Reference http://cdn5.raywenderlich.com/downloads/RW-Objective-C-Cheatsheet-v1_2.pdf • Coding Guidelines for Cocoa http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/ CodingGuidelines.html http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/ CodingGuidelines.pdf • Ry’s Objective-C Tutorial http://rypress.com/tutorials/objective-c/index.html