<<

COMP327 Mobile Computing

Lecture Set 8 - Introduction to Objective-

1 This material will not appear in the exam! It supportsAssignment the Second In this Lecture Set

• What is Objective-C? • Main elements • OO extensions to ANSI C • Syntax • Class definitions • Cocoa and Foundation Classes • Object Lifecycle • Memory Management • Autorelease

2 This material will not appear in the exam! It supportsAssignment the Second Provenance

• Many of these slides will be based on the Stanford University CS193P Notes • iPhone Application Development • These notes are (currently) available on the web • Lectures are also available on iTunesU • Also, notes on Apple’s Developer Web site

3 This material will not appear in the exam! It supportsAssignment the Second Provenance

• Objective C extends ANSI C • We may cover some ANSI C elements • Syntax and constructs are similar to Java • BUT... ANSI C is not Object Oriented!!! • To really understand the material, make sure you have a understanding of C • Read Kernighan and Ritchie (K&R) - The C

4 This material will not appear in the exam! It supportsAssignment the SecondOther sources of Help

• Use the Help menu within Xcode • Includes information on the Cocoa API objects • Conceptual Docs • Style Guides • Apple’s Developer Connection (ADC) Web Site • Sample Code • Tech notes • Documentation

5 This material will not appear in the exam! It supportsAssignment the Second What is Objective-C

• An object-oriented language • “..focused on simplicity and the elegance of object oriented design...” • A strict superset of ANSI C • Very Different (and somewhat simpler) to C++ • Exploits a number of object oriented principles • Inherits many priciples from • Used to develop the Cocoa API Framework • A variant for C++ also exists • ObjC++ • Originally used within NeXT’s NeXTSTEP OS • Precursor to Mac OS X

6 This material will not appear in the exam! It supportsAssignment the Second What is Objective-C

• A simple language, but introduces some new syntax • Single inheritance • Inherits from only one superclass • Protocols • Introduces the notion of multiple inheritance • A pattern that defines a list of methods that should be defined when implementing a class • Pre Objective-C 2.0, all protocol methods were mandatory • Different to the notion of protocols in Java • e.g. if you want to define a table, you would need a delegate to enter data into the table • Dynamic Runtime • Everything is looked up and dispatched at runtime (not compile time) • (Optionally) Loosely Typed

7 This material will not appear in the exam! It supportsAssignment the SecondObject Oriented Recap

• Object Oriented Vocabulary • Elements • Class: defines the grouping of data and code, the “type” of an object • Instance: a specific allocation of a class • Method: a “function” that an object knows how to perform • Instance Variable (or “ivar”): a specific piece of data belonging to an object

• Principles • Encapsulation: keep implementation private and separate from interface • Polymorphism: different objects, same interface • Inheritance: hierarchical organisation, share code, customise or extend behaviours

8 This material will not appear in the exam! It supportsAssignment the Second Inheritance • Hierarchical relationship between classes NSObject Subclass • Subclasses inherit from superclasses UI Control • Everything is an object!!! • Top Level class is NSObject UIButton UITextField • Takes care of memory management, introspection etc... • Typically not directly used, but often used as a superclass for other classes

9 This material will not appear in the exam! It supportsAssignment the Second Syntax Additions

• ANSI C extended with some syntax extensions • New Types • Anonymous object (id type) • Used for loosely typing • Language Level Constructs • Class • Selectors (for sending messages to objects) • Syntax for... • ...defining classes • ...defining message expressions

10 This material will not appear in the exam! It supportsAssignment the Second Dynamic Runtime

• Object Creation • Everything is allocated from the heap • No stack based objects!! • Message Dispatch • Everything is looked up and dispatched at runtime (not compile time) • If you send a message to an object, the existence of that object is checked at runtime • Introspection • A “thing” (class, instance, etc) can be asked at runtime what type it is • Can pass anonymous objects to a method, and get it to determine what to do depending on the object’s actual type

11 This material will not appear in the exam! It supportsAssignment the Second Classes and Objects

• Classes and instances are both objects Person Classes declare state and behaviour • NSString *name; int age; • State (data) is maintained using State instance variables - (NSString *)name; - (void)setName:(NSString *)value; • Behaviour is implemented using - (int)age; methods - (void)setAge:(int)age; - (BOOL)canLegallyVote; • Instance variables typically hidden Behaviour - (void)castBallot; • Accessible only using getter/setter methods

12 This material will not appear in the exam! It supportsAssignment the Second Messaging Syntax

• Classes and Instance Methods • Instances respond to instance methods (“-”) - (id)init; - (float)height; - (void)walk; • Methods called on instances of a class • Classes respond to class methods (“+”) + (id)alloc; + (id)person; + (Person *)sharedPerson; • Methods called on the class itself • e.g. modifying class-wide static variables

13 This material will not appear in the exam! It supportsAssignment the Second Message Syntax

• A square brace syntax is used [receiver message] [receiver message:argument] [receiver message:arg1 andArg:arg2]

Object receiving The message The main (first) Subsequent the message itself argument named arguments

arg-name : arg-value

14 This material will not appear in the exam! It supportsAssignment the Second Message Examples

Person *voter; //assume this exists

[voter castVote];

int theAge = [voter age];

[voter setAge:21];

if ([voter canLegallyVote]) {

// do something voter-y

}

[voter registerForState:@"CA" party:@"Independent"];

NSString *name = [[voter spouse] name];

15 This material will not appear in the exam! It supportsAssignment the Second Terminology

• Message expression [receiver method: argument] • Message [receiver method: argument] • Selector [receiver method: argument] • Method • The code selected by a message

16 This material will not appear in the exam! It supportsAssignment the Second Dot Syntax

• Objective-C 2.0 introduced dot syntax • Convenient shorthand for invoking accessor methods float height = [person height]; float height = person.height;

[person setHeight:newHeight]; person.height = newHeight; • Follows the dots... [[person child] setHeight:newHeight]; // exactly the same as person.child.height = newHeight; • Essentially provides a shorthand • Assumes a setter naming convention (setX) etc • Dot syntax is automatically converted into the brace syntax

17 This material will not appear in the exam! It supportsAssignment the Second Dynamic and Static Typing • Dynamically-typed (loosely typed) object id anObject • Just id • Not id * (unless you really, really mean it...) • Dynamic typic can be very powerful • No type-checking, so can be very dangerous!!! • Statically-typed object Person *anObject • Compile-time (not runtime) type checking • Objective-C always uses dynamic binding

18 This material will not appear in the exam! It supportsAssignment the SecondThe null object pointer

• Test for nil explicitly if (person == nil) return; • Or implicitly if (!person) return; • Can use in assignments and as arguments if expected person = nil; [button setTarget: nil]; • Sending a message to nil? person = nil; [person castBallot]; • Most other systems would crash, Object-C would do nothing • Useful as it avoids crashing in unusual situations!!!

19 This material will not appear in the exam! It supportsAssignment the Second BOOL typedef

• When ObjC was developed, C had no boolean type • ObjC uses a typedef to define BOOL as a type BOOL flag = NO; • Macros included for initialisation and comparison • YES and NO if (flag == YES) if (flag) if (!flag) if (flag != YES) flag = YES; flag = 1;

20 This material will not appear in the exam! It supportsAssignment the Second Selectors identify methods by name • A selector has type SEL SEL action = [button action]; [button setAction:@selector(start:)]; • Conceptually similar to function pointer • Selectors include the name and all colons, for example: -(void)setName:(NSString *)name age:(int)age;

• would have a selector: SEL sel = @selector(setName:age:);

21 This material will not appear in the exam! It supportsAssignment the SecondWorking with selectors

• You can determine if an object responds to a given selector id obj; SEL sel = @selector(start:); if ([obj respondsToSelector:sel]) { // it responds to this selector, so call it [obj performSelector:sel withObject:self] }

• This sort of introspection and dynamic messaging underlies many Cocoa design patterns • You will see this in use within Interface Builder!!! -(void)setTarget:(id)target; -(void)setAction:(SEL)action;

22 This material will not appear in the exam! It supportsAssignment the Second Class Introspection

• You can ask an object about its class Class myClass = [myObject class]; NSLog(@"My class is %@", [myObject className]); • Testing for general class membership (subclasses included): if ([myObject isKindOfClass:[UIControl class]]) { // something } • Testing for specific class membership (subclasses excluded): if ([myObject isMemberOfClass:[NSString class]]) { // something string specific }

23 This material will not appear in the exam! It supportsAssignment the Second Identity vs Equality

• Identity—testing equality of the pointer values if (object1 == object2) { NSLog(@"Same exact object instance"); }

• Equality—testing object attributes if ([object1 isEqual: object2]) { NSLog(@"Logically equivalent, but may be different object instances"); }

24 This material will not appear in the exam! It supportsAssignment the Second - description

• NSObject implements -description - (NSString *)description; • Objects represented in format strings using %@ • Similar to % (int), %f (float), %c (char) etc... • When an object appears in a format string, it is asked for its description [NSString stringWithFormat: @”The answer is: %@”, myObject]; • You can log an object’s description with: NSLog([anObject description]); • Your custom subclasses can override description to return more specific information

25 This material will not appear in the exam! It supportsAssignment the SecondFoundation Framework

• Different to Cocoa • Supports all the underlying (common) classes • Common to all Apple platforms (OS X, iPhone etc) • Defines classes to support the following: • Value and collection classes • User defaults • Archiving • Notifications • Undo manager • Tasks, timers, threads • File system, pipes, I/O, bundles

26 This material will not appear in the exam! It supportsAssignment the Second Two useful foundation classes • NSObject • Root class • Implements many • Memory management • Introspection • Object equality • NSString • General-purpose string support • Unicode is a coding system which represents all of the world’s languages • Consistently used throughout Cocoa Touch instead of “char *” • Without doubt the most commonly used class • Easy to support any (spoken) language in the world with Cocoa

27 This material will not appear in the exam! It supportsAssignment the Second String Constants

• In C and Java, constant strings are “simple”

• In ObjC, constant strings are @“just as simple”

• Constant strings are NSString instances • The “@” converts the string into an NSString NSString *aString = @”Hello World!”;

28 This material will not appear in the exam! It supportsAssignment the Second Format Strings

• Similar to printf, but with %@ added for objects NSString *aString = @”Johnny”;

NSString *log = [NSString stringWithFormat: @”It’s ‘%@’”, aString]; • log would be set to It’s Johnny • Also used for logging NSLog(@”I am a %@, I have %d items”, [array className], [array count]); • would log something like: I am a NSArray, I have 5 items

29 This material will not appear in the exam! It supportsAssignment the Second More on NSString

• Often ask an existing string for a new string with modifications - (NSString *)stringByAppendingString:(NSString *)string; - (NSString *)stringByAppendingFormat:(NSString *)string; - (NSString *)stringByDeletingPathComponent; • Example: NSString *myString = @”Hello”; NSString *fullString; fullString = [myString stringByAppendingString:@” world!”]; • fullString would be set to Hello world!

30 This material will not appear in the exam! It supportsAssignment the Second More on NSString

• Common NSString methods - (BOOL)isEqualToString:(NSString *)string; - (BOOL)hasPrefix:(NSString *)string; - (int)intValue; - (double)doubleValue; • Example: NSString *myString = @”Hello”; NSString *otherString = @”449”; if ([myString hasPrefix:@”He”]) { // will make it here } if ([otherString intValue] > 500) { // won’t make it here }

31 This material will not appear in the exam! It supportsAssignment the Second NSMutableString

• NSMutableString subclasses NSString • Allows a string to be modified • Common NSMutableString methods + (id)string;

- (void)appendString:(NSString *)string;

- (void)appendFormat:(NSString *)format, ...;

NSMutableString *newString = [NSMutableString string];

[newString appendString:@”Hi”];

[newString appendFormat:@”, my favourite number is: %d”,

[self favouriteNumber]];

32 This material will not appear in the exam! It supportsAssignment the Second NSNumber

• In Objective-C, you typically use standard C number types • NSNumber is used to wrap C number types as objects • Subclass of NSValue • No mutable equivalent! • Typically better to use floats, ints etc, and only convert when necessary • Avoids having to unpack an NSNumber, modify it, and repackage it! • Common NSNumber methods: + (NSNumber *)numberWithInt:(int)value; + (NSNumber *)numberWithDouble:(double)value; - (int)intValue; - (double)doubleValue;

33 This material will not appear in the exam! It supportsAssignment the Second Collections

• Array - ordered collection of objects • Dictionary - collection of key-value pairs • Set - unordered collection of unique objects • Common enumeration mechanism • Immutable and mutable versions • Immutable collections can be shared without side effect • Prevents unexpected changes • Mutable objects typically carry a performance overhead

34 This material will not appear in the exam! It supportsAssignment the SecondWalkthrough - Designing a custom class • Design Phase • Create a class • Person • Determine the superclass • NSObject (in this case) • What properties should it have? • Name • Age • Boolean for whether or not they can vote • What actions can it perform? • Cast a vote

35 This material will not appear in the exam! It supportsAssignment the Second Quick Review

• Methods • Some behaviour associated with an object • Accessor methods • Getter method • use name of the property - (NSString *)name { ... } • Setter method • convention is to use the name of the property with the prefix “set” • first character is made upper case - (void)setName:(NSString *)name { ... }

36 This material will not appear in the exam! It supportsAssignment the Second Quick Review

• Selector • Name for referring to a method • Not the method call itself - that is the message • Includes colons to indicate arguments • Doesn’t actually include arguments or indicate types

SEL mySelector = @selector(name); SEL anotherSelector = @selector(setName:); SEL lastSelector = @selector(doStuff:withThing:andThing:);

37 This material will not appear in the exam! It supportsAssignment the Second Quick Review

• Message • The act of performing a selector on an object • With arguments, if necessary NSString *name = [myPerson name]; [myPerson setName:@“New Name”];

Remember - “@” before a converts it into an NSString

38 This material will not appear in the exam! It supportsAssignment the Second Class management

• Objective-C inherits the convention of typically defining two files for the code Header File • A header file • Contains the (public) definitions of the classes and/or procedures/functions • An implementation file • Contains the (private) procedural code Implementation File

39 This material will not appear in the exam! It supportsAssignment the Second Class Interface declared in header file

#import

@interface Person : NSObject { // instance variables NSString *name; int age; } // method declarations Header File - (NSString *)name; - (void)setName:(NSString *)value;

- (int)age; - (void)setAge:(int)age;

- (BOOL)canLegallyVote; - (void)castBallot;

@end

40 This material will not appear in the exam! It supportsAssignment the Second Class Implementation

#import "Person.h"

@implementation Person

- (int)age { return age; } Implementation File - (void)setAge:(int)value { age = value; }

//... and other methods

@end

41 This material will not appear in the exam! It supportsAssignment the Second Calling your own methods #import "Person.h"

@implementation Person Use “self” to refer to - (BOOL)canLegallyVote { the current object. return ([self age] >= 18); } REMEMBER: This - (void)castVote { specifies the object if ([self canLegallyVote]) { the message is sent to // do voting stuff } else { NSLog (@“I’m not allowed to vote!”); } }

@end

42 This material will not appear in the exam! It supportsAssignment the Second Superclass methods

• As we just saw, objects have an implicit variable named “self” • Like “this” in Java and C++ • Can also invoke superclass methods using “super” • Useful to refer to a parent method when redefining a method - (void)doSomething { // Call superclass implementation first [super doSomething];

// Then do our custom behaviour int foo = bar; // ... }

43 This material will not appear in the exam! It supportsAssignment the SecondMemory Management - how C does it! • When data types are declared, memory is allocated depending on the type • Varies, depending on compiler, but essentially: • 1 byte (8 bits): char, bool • 2 bytes (16 bits): short • 4 bytes (32 bits): int, float • 8 bytes (64 bits): long, double • 16 bytes (128 bits): long double • Enumerated Types are typically equivalent to an int • Structures equal to the sum of their elements • Pointers hold an address in memory, so depends on the architecture (e.g. 8 bytes on a 64-bit machine) • The expression sizeof(t) returns the size of the type t

44 This material will not appear in the exam! It supportsAssignment the Second Pointers in C

• In C, every value is stored somewhere in memory • Can therefore be identified with that address. • Such addresses are called pointers. • Because C is designed to allow to control data at the lowest level, pointers can be manipulated just like any other kind of data. • In particularly, you can assign one pointer value to another, which means that the two pointers end up indicating the same data value. • Pointers are references to an object or element in memory, not the object or element itself.

45 This material will not appear in the exam! It supportsAssignment the Second Declaring a Pointer Variable in C • Pointers are differentiated from regular variables by using the “*” syntax int x; int *px; • Declaring a variable allocates the memory for that variable • Declaring a pointer allocates the memory for the pointer • Some other action is needed to create the memory for the object the pointer ultimately points to • This is similar to the issue of creating instances in JAVA.

46 This material will not appear in the exam! It supportsAssignment the SecondPointer Operators in C

• There are two main operators • The address-of operator “&” • This is written before a variable name (or any expression to which you could assign a value) and returns the address of that variable. • Thus, the expression &total gives the address of total in memory. • The deference operator “*” • This is written before a pointer expression and returns the actual value to which the pointer points. • Example: double x = 2.5; double *px = &x; • Here, px points to the variable x, and *px contains the value 2.5

47 This material will not appear in the exam! It supportsAssignment the Second Pointers and Arrays

• All arrays are represented internally as a pointer to their first element. • For example if the following array is defined: int myArray[100]; • Then myArray points to the 0’th element in the array • The n’th element in the array is simply the pointer address myArray+n*sizeOf(int) • If a pointer is incremented (or decremented), then its value will be changed according to the type it points to • Often, C code will create a pointer to the first element of the array, and traverse the array using the increment expression “++”

48 This material will not appear in the exam! It supportsAssignment the Second Strings as arrays

• Strings are a special case of arrays • Essentially, a string is an array of characters char *message = “Hello World”; • The last character of a string is followed by a , to terminate the string

H e l l o W o r l d \0 message 0x83A483

0x83A4830x83A4840x83A4850x83A4860x83A4870x83A4880x83A4890x83A48A0x83A48B0x83A48C0x83A48D0x83A48E • This nearly always catches out newbie C programmers!!!

49 This material will not appear in the exam! It supportsAssignment the Second Advantages of C pointers • Pass values by reference • When calling methods, if a variable is passed to a method, a copy is made • This takes up space on the stack • The resulting value is immutable • By passing a pointer • Takes up less space if the pointer refers to a large object such as an array or string • Methods can side-effect external data • The method can write to the memory pointed to by the pointer, which is accessible by the calling function • Useful if a number of values are to be returned

50 This material will not appear in the exam! It supportsAssignment the Second Memory Management and C • Datatypes declared in code are statically allocated by the compiler • Memory for new data items have to be “allocated” from the heap • Typically using malloc() or calloc() • When the memory is no longer required, it can be freed • Typically using free() • Avoiding memory leaks is one of the most challenging aspects of programming in C!!!

• THERE IS NO GARBAGE COLLECTION IN C

51 This material will not appear in the exam! It supportsAssignment the Second Back to Objective C

• Object Creation • This is typically a two step process • allocate memory to store the object • initialise object state + alloc • Class method that knows how much memory is needed - init • Instance method to set initial values, perform other setup • Often combined as a single statement Person *person = nil; person = [[Person alloc] init];

52 This material will not appear in the exam! It supportsAssignment the SecondImplementing your own -init method

#import "Person.h"

@implementation Person

- (id)init { // allow superclass to initialise its state firs if (self = [super init]) { age = 0; name = @“Bob”;

// do other initialisation... } return self; }

@end

53 This material will not appear in the exam! It supportsAssignment the Second Multiple init methods

• Classes may define multiple init methods

- (id)init; - (id)initWithName:(NSString *)name; - (id)initWithName:(NSString *)name age:(int)age; • Less specific ones typically call more specific ones with default values

- (id)init { return [self initWithName:@“No Name”]; }

- (id)initWithName:(NSString *)name { return [self initWithName:name age:0]; }

54 This material will not appear in the exam! It supportsAssignment the Second Finishing up with an Object

Person *person = nil;

person = [[Person alloc] init]; There is no Garbage [person setName:@“Terry Payne”]; Collection within [person setAge:40]; [person setWishfulThinking:YES]; Objective-C for the iPhone !!! [person castVote];

// What do we do with person when we’re done?

55 This material will not appear in the exam! It supportsAssignment the SecondMemory Management in Objective C

Allocation Destruction C malloc free Objective-C allocation dealloc • Calls must be balanced • Otherwise your program may leak or crash • However, you’ll never call -dealloc directly • One exception, we’ll see in a bit...

56 This material will not appear in the exam! It supportsAssignment the Second Reference Counting

• Every object has a retain count • Defined on NSObject • As long as retain count is > 0, object is alive and valid • +alloc and -copy create objects with retain count == 1 • -retain increments retain count • -release decrements retain count

• When retain count reaches 0, object is destroyed • -dealloc method invoked automatically • One-way street, once you’re in -dealloc there’s no turning back

57 This material will not appear in the exam! It supportsAssignment the Second Balanced Calls

Person *person = nil;

person = [[Person alloc] init];

[person setName:@“Terry Payne”]; [person setAge:40]; [person setWishfulThinking:YES];

[person castVote];

// When we’re done with person, release it [person release];!// person will be destroyed here

58 This material will not appear in the exam! It supportsAssignment the Second Reference Counting in Action

person = [[Person alloc] init]; Retain count begins at 1 with +alloc

[person retain]; Retain count increases to 2 with -retain

[person release]; Retain count decreases to 1 with -release

[person release]; Retain count decreases to 0: -dealloc automatically called

59 This material will not appear in the exam! It supportsAssignment the Second Messaging deallocated objects • Program defensively when managing memory Person *person = [[Person alloc] init]; // ... [person release]; // Object is deallocated

[person doSomething]; // Crash! • Typically, it is good practice to set pointers to nil when they are not in use person = nil; • Easy to check • Avoids memory corruption if contents at the pointer address is mistakenly updated • Objective-C silently ignores messages to nil

60 This material will not appear in the exam! It supportsAssignment the SecondImplementing a -dealloc method

#import "Person.h"

@implementation Person

- (void)dealloc { // Do any cleanup that’s necessary // ...

// when we’re done, call super to clean us up [super dealloc]; } @end

61 This material will not appear in the exam! It supportsAssignment the SecondObject Lifecycle Recap

• Objects begin with a retain count of 1 • Increase with -retain • Decrease with -release • When the retain count reaches 0, the object is deallocated automatically • You never need to call dealloc explicitly in your code • The only exception is when redefining the dealloc method to do additional housekeeping • In this case, send a message to the superclass via [super dealloc] • You only deal with alloc, copy, retain, and release

62 This material will not appear in the exam! It supportsAssignment the Second Object Ownership

• It is important to know who owns an object • Hence who is responsible for its memory! • Can be mediated through -retain and -release • Sometimes, ownership can be ambiguous • For this, we have -autorelease • Also, mutability is an important consideration • Are objects retained or copied? • Can depend on the ’s paranoia...! • Typically depends on whether the object is mutable

63 This material will not appear in the exam! It supportsAssignment the Second Object Ownership

#import

@interface Person : NSObject { // instance variables NSString *name; // Person class “owns” the name int age; } The object name requires memory // method declarations management. It is owned by Person. - (NSString *)name; - may be returned by the getter - (void)setName:(NSString *)value; accessor - (int)age; - may be changed by the setter - (void)setAge:(int)age; accessor.

- (BOOL)canLegallyVote; - (void)castVote; @end

Header File

64 This material will not appear in the exam! It supportsAssignment the Second Object Ownership

#import "Person.h" If a new name string is sent to setName: - the previous string is released (i.e. it is @implementation Person not longer needed) - (NSString *)name { - the new string retained (i.e. this string return name; will also be owned by Person). }

- (void)setName:(NSString *)newName { if (name != newName) { [name release]; name = [newName retain]; // name’s retain count has been bumped up by 1 } }

@end

Implementation File

65 This material will not appear in the exam! It supportsAssignment the Second Object Ownership This version makes a copy of the #import "Person.h" string in the setter, rather than keeping the argument string. @implementation Person - The ownership of the argument string is not changed. - (NSString *)name { return name; - It remains the responsibility of its } previous owner...

- (void)setName:(NSString *)newName { if (name != newName) { [name release]; name = [newName copy]; // name now has a retain count of 1, we own it!!! } }

@end

Implementation File

66 This material will not appear in the exam! It supportsAssignment the Second Releasing Instance Variables

#import "Person.h" A newly defined dealloc may need to @implementation Person clean up (i.e. release) any objects - (NSString *)name { before it calls its superclass dealloc return name; method. }

- (void)dealloc { // Do any cleanup that’s necessary [name release];

// when we’re done, call super to clean us up [super dealloc]; } @end

Implementation File

67 This material will not appear in the exam! It supportsAssignment the Second Returning a newly created object • In some cases, objects may be passed with no clear or obvious ownership • Hence no responsibility to clean up - (NSString *)fullName { NSString *result; result = [[NSString alloc] initWithFormat:@“%@ %@”, firstName, lastName]; return result; } • In this case, result is leaked...! • result is passed as an allocated object with no owner

68 This material will not appear in the exam! It supportsAssignment the Second Returning a newly created object • Can’t release result before it is returned • Yet, after return, the method looses access to the object - (NSString *)fullName { NSString *result; result = [[NSString alloc] initWithFormat:@“%@ %@”, firstName, lastName]; [result autorelease] return result; } • result will be released some time in the future (not now) • caller can choose to retain it to keep it around!

69 This material will not appear in the exam! It supportsAssignment the Second Autorelease

• Calling -autorelease flags an object to be sent release at some point in the future • Let’s you fulfil your retain/release obligations while allowing an object some additional time to live • Makes it much more convenient to manage memory

• Very useful in methods which return a newly created object

70 This material will not appear in the exam! It supportsAssignment the SecondNaming conventions and predicting ownership • Methods whose names includes alloc or copy return a retained object that the caller needs to release

NSMutableString *string = [[NSMutableString alloc] init]; // We are responsible for calling -release or -autorelease [string autorelease]; • All other methods return autoreleased objects NSMutableString *string = [NSMutableString string]; // The method name doesn’t indicate that we // need to release it ... so don’t!!! • This is a convention • follow it in the methods that you define!

71 This material will not appear in the exam! It supportsAssignment the SecondHow does -autorelease work??? • Object is added to current autorelease pool • Autorelease pools track objects scheduled to be released • When the pool itself is released, it in turn sends the -release message to all its objects • UIKit automatically wraps a pool around every event dispatch • Important for event driven GUI programming

72 This material will not appear in the exam! It supportsAssignment the Second App Lifecycle

Launch App Pool App Initialized Pool Created

Load main nib

Wait for an event Autoreleased Event objects in the Handle Event Loop event loop are put in the Pool Exit App

73 This material will not appear in the exam! It supportsAssignment the Second App Lifecycle

Launch App Pool App Initialized

Load main nib

Wait for an event

Handle Event

Exit App Object Created

74 This material will not appear in the exam! It supportsAssignment the Second App Lifecycle

Launch App Pool App Initialized

Load main nib

Wait for an event

Handle Event [object autorelease]; Exit App

75 This material will not appear in the exam! It supportsAssignment the Second App Lifecycle [object release];

Launch App Pool App Initialized Pool Released

Load main nib [object release]; [object release]; Wait for an event

Handle Event

Exit App

76 This material will not appear in the exam! It supportsAssignment the Second App Lifecycle

Launch App Pool App Initialized

Load main nib

Wait for an event

Handle Event

Exit App

77 This material will not appear in the exam! It supportsAssignment the Second App Lifecycle

Launch App Pool App Initialized Pool Created

Load main nib

Wait for an event

Handle Event

Exit App

78 This material will not appear in the exam! It supportsAssignment the Second Hanging onto an autoreleased object • Many methods return autoreleased objects • Remember the naming conventions... • They’re hanging out in the pool and will get released later • If you need to hold onto those objects you need to retain them • Bumps up the retain count before the release happens name = [NSMutableString string];

// We want to name to remain valid! [name retain];

// ... // Eventually, we’ll release it (maybe in our -dealloc?) [name release];

79 This material will not appear in the exam! It supportsAssignment the Second To Recap...

• In this lecture set, we covered: • A crash course in Objective-C !!! • Recap on Object Oriented Programming • Classes and Objects • Messaging Syntax • Foundation Framework • NSObject, NSString and mutable objects • C Pointers • Memory Allocation in Objective-C • Retain, Release and Autorelease

80