Download - Objective-C Crash Course

Transcript
Page 1: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 1/33

1 The Objective-C Crash Course

Page 2: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 2/33

Legal Notices

This publication is protected under the US Copyright Act of 1976 and all

other applicable international, federal, state and local laws, and all rights are

reserved, including resale rights: you are not allowed to give or sell this

book to anyone else. If you received this publication from anyone other than

How to Make iPhone Apps or App Shop, LLC, you've received a pirated copy.

Please contact us via e-mail at [email protected] and notify us of the

situation.

Please note that much of this publication is based on personal experience

and anecdotal evidence. Although the author and publisher have made every

reasonable attempt to achieve complete accuracy of the content in this book,

they assume no responsibility for errors or omissions. Also, you should use

this information as you see fit, and at your own risk. Your particular situation

may not be exactly suited to the examples illustrated here; in fact, it's likely

that they won't be the same, and you should adjust your use of the

information and recommendations accordingly.

Any trademarks service marks, product names or named features are

assumed to be the property of their respective owners, and are used only for

reference. There is no implied endorsement if we use one of these terms.

iPhone™, iPod™ and iTunes™ are trademarks of Apple Inc., registered in the

U.S. and other countries.

Finally, use your head. Nothing in this book is intended to replace common

sense, legal, medical, metaphysical or other professional advice, and is

meant to inform and entertain the reader. So have fun with The Objective-C

Crash Course, and get your stuff done.

Copyright © 2009 App Shop, LLC. All rights reserved worldwide.

2 The Objective-C Crash Course

Page 3: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 3/33

......................................................................Introduction 6

..............................................................................A Note About NSLog 6

................................................How to Use the Included Source Code 7

......................................................................................Patterns of Use 8

.......................................................................Methods and Messaging 9

.................................................................................Types vs. Objects 10

.......................................................Objective-C How To 12

..............................................................................How to Use Strings 12

......................................................................................................Using strings  12 

...............................................................Inserting a string into another string  12 

.......................................................................Inserting a number into a string  12 

......................................Inserting a string and a number into another string  12 

...........................................................................How to Use Numbers 13

....................................................................................................Using integers 

13 

....................................................................................................Using doubles  13 

................................................................................................Doing arithmetic  13 

.................................................................................................Using NSInteger  13 

..............................................................................................Using NSUInteger  13 

..............................................................................Using the NSNumber Class  13 

..................................How to Use Objects, Properties and Methods 14

........................................................................................Using a class method  14 

....................................................................Instantiate an object from a class  14 

...........Send a message to an object to evoke a method (calling a method)  14 

3 The Objective-C Crash Course

Page 4: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 4/33

..............................................Send a message to an object with a parameter  14 

........................................Send a message to an object with two parameters  14 

.............................................Using a value returned from an object function  14 

...............................................Assign a value to a property using dot syntax  14 

................................................Accessing a property value using dot syntax  15 

...........................................................Release an object ̓  s memory allocation  15 

...............................................................................How to Use Arrays 16

............................................................................................Instantiate an array  16 

..................................................................................Add elements to an array  16 

...................................................................Retrieve an element from an array  16 

..................................................................Retrieve the last object in an array  16 

..........................................................Move through each element in an array  16 

......................................................................How to Use Dictionaries 17

......................................................................................Instantiate a dictionary  17 

..................................................Add objects to a dictionary indexed by keys  17 

.............................................Retrieve an object from a dictionary with a key  17 

..........................................................................................Release a dictionary  17 

..........................................................How to Use If-Then Statements 18

........................How to Use Switch Statements or Case Statements 18

................................................................................How to Use Loops 19

..................................................................................................Using for loops  19 

..............................................Working with Classes and Subclasses 21

...................................................How to Add Properties to a Class Definition  22 

..............................................................................How to Add a Class Method  23 

4 The Objective-C Crash Course

Page 5: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 5/33

.......................................................................How to Add an Instance Method  24 

..........................................................How to Add a Method with a Parameter  25 

..............................................................Complete Code for a Class Definition  27 

.................................................................................Interface File (myClass.h)  27 

.....................................................................Implementation File (myClass.m)  28 

...........................................................................Memory Management 29

...........................................................................................Reference Counting  29 

......................................................................How Reference Counting Works  30 

........................................................................................................Autorelease  31

....................................................................................How to Use Autorelease  31

.........................................................................Memory Management Pointers  32 

.............................................................................................Final Word 33

5 The Objective-C Crash Course

Page 6: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 6/33

Introduction

Objective-C is the primary programming language used in iPhone

programming. Objective-C is similar to other programming languages; it

has loops, if-then statements, objects and arrays. However, the syntax is

different than many other languages.

In order to help you get over the disorientation of jumping into working with

the iPhone this crash course will show you the Objective-C approaches to

using common programming methods like looping and if-then logic.

This document will get you up to speed with the tasks that you are used to

as a programmer. However, if you do not have much experience as a

programmer and would like an introduction to programming concepts and a

deeper knowledge of Objective-C then I recommend the book Learn

Objective-C on the Mac .

A Note About NSLog

In the examples here, the NSLog function is used to demonstrate snippets of 

code. For example,

 

NSLog(@”Write this to log”);

This function writes whatever string is presented between the parentheses tothe log window. Click on this button in XCode (this only works when an app

is executing) to see the log window:

6 The Objective-C Crash Course

Page 7: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 7/33

Page 8: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 8/33

Patterns of Use

{, } & ;

Objective-C follows the conventions of C when it comes to using the symbols

above. The symbol “;” is used to terminate a line of code. This means thatyou may write code over multiple spaces in XCode, but it will be viewed as

only one line of code that ends where the “;” is placed.

For example:

NSString *newString =

[NSString stringWithFormat:

  @"I Added This to %@.", myString];

Even though the statement above looks like it spans over three lines, the

system considers in one line of code that ends with the “;” after “myString].

The “{“ and “}” are used to group lines of code together in this family of 

languages. For example,

int x = 5;

if(x == 5){ NSLog(@"True"); NSLog(@"More Stuff");

}

else{ NSLog(@"False");

}

The brackets are used to ensure that both NSLog statements above are

executed when the x == 5 condition is met.

8 The Objective-C Crash Course

Page 9: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 9/33

Methods and Messaging

Like other OO languages, Objective-C uses the idea of a method. A method

is a unit of code that executes a set of instructions. You may be used to

referring to a method by “calling” the method from another part of the

program. However, in Objective-C this is referred to as sending a messageto an object where the method is the message.

Sending a message to an object looks like this in code:

[alert show];

The object here is “alert” and the message is “show”. Notice how the entire

object and method is contained in square brackets and there is a space

between the object and the method. In other programming languages thisstatement might look something like this:

alert.show();

You may also send a message to an object with a parameter. Parameters

require the “:” before the value. Here is an example:

[alert ShowThisParameter:@"I say this!"];

Other programming languages may write the same statement like this:

Alert.ShowThisParameter("I say this!");

When you use a method that requires more than one parameter you must

supply a descriptive prefix,”:” and the parameter itself. For example,

[myObject aMethodWithTwoParameters:@"First Parm" aNumberToDisplay:2];

The descriptive prefix is a unique Objective-C feature that helps you self-

document your code.

9 The Objective-C Crash Course

Page 10: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 10/33

Types vs. Objects

You will encounter two kinds of variables when working with Objective-C.

Objects such as the alert demonstrated above and simple types like integers

and doubles. These things can cause some confusion because they follow

different rules even though they are used in similar ways.

The first notable difference is how we declare a type versus an object. Here

is how an integer would be declared:

int number;

The type and a variable name followed by a semi-colon. Pretty simple and

probably what you would expect. Here is how a NSNumber object would be

declared:

NSNumber *numberObject;

This is the class name and a variable name prefixed by an asterisk. It is

similar to the integer we created above but it must include the asterisk. The

asterisk simply means that this variable is a pointer to a space in memory.

The next significant difference is that while the integer above is ready to

use, our object have memory allocated to it and our object must be createdwith an constructor (see the sections on objects and classes for more

information on this).

The integer is easy.

number = 78;

The NSNumber object requires more work.

numberObject = [[NSNumber alloc] initWithInt:78];

Finally, when you are finished working with an object you need to make sure

to release it.

[numberObject release];

10 The Objective-C Crash Course

Page 11: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 11/33

When you are finished working with the integer you can just forget about it.

Objects also need special care when it comes to memory management (see

the memory management section). They are worth the extra trouble since

objects generally contain a very rich feature set and are used extensively in

the Cocoa-Touch frameworks.

11 The Objective-C Crash Course

Page 12: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 12/33

Page 13: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 13/33

How to Use Numbers

Numbers represent quantities – the easiest way to work with numbers in

Objective-C is to use C types like int and double. Here are some examples.

Using integers

int i = 3;

NSLog(@"i = %i", i);

 Using doubles

double d = 3.4;

NSLog(@"d = %f", d);

Doing arithmetic

double dPlusi = d + i;

NSLog(@"d + i = %f", dPlusi);

Using NSInteger

NSInteger ns_i = 8;NSLog(@"ns_i = %i", ns_i);

Using NSUIntegerNSUInteger nsu_i = 18;

NSLog(@"nsu_i = %i", nsu_i);

Using the NSNumber Class

NSNumber *numbersObject = [[NSNumber alloc] initWithInt:78];

NSLog([numbersObject stringValue]);

[numbersObject release];

13 The Objective-C Crash Course

Page 14: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 14/33

How to Use Objects, Properties and Methods

Classes and objects are used frequently in Objective-C since it is an object-

oriented programming language. Here is how you work with classes that

already exist in code:

Using a class method

//A class method can be used without instantiating the object

[myClass demonstrateAClassMethod];Instantiate an object from a class

myClass *myObject = [[myClass alloc] init];

Send a message to an object to evoke a method (calling a method)[myObject demonstrateAnInstanceMethod];

Send a message to an object with a parameter

[myObject demonstrateAnObjectMethodWithThisParameter:@"I say this!"];

Send a message to an object with two parameters[myObject aMethodWithTwoParameters:@"First Parm" 

aInteger:2];

Using a value returned from an object function

NSLog([myObject aFunctionReturnsThatAString]);

Assign a value to a property using dot syntax

myObject.name = @"My Object's Name";

14 The Objective-C Crash Course

Page 15: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 15/33

Accessing a property value using dot syntax

NSLog(myObject.name);

Release an object

ʼs memory allocation

[myObject release];

15 The Objective-C Crash Course

Page 16: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 16/33

Page 17: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 17/33

How to Use Dictionaries

Like an array, a dictionary is a list of objects. However, dictionaries make it

easier to organize data by providing "keys" that make it a snap to find the

things you put in there. These are sometimes referred to as a hash or a

hash-table.Instantiate a dictionary

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

Add objects to a dictionary indexed by keys

[dictionary setObject:@"A Book about the Letter A" forKey:@"A"];

[dictionary setObject:@"A Book about the Letter B" forKey:@"B"];[dictionary setObject:@"A Book about the Letter C" forKey:@"C"];

Retrieve an object from a dictionary with a key

NSLog([dictionary objectForKey:@"B"]);

Release a dictionary

[dictionary release];

17 The Objective-C Crash Course

Page 18: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 18/33

How to Use If-Then Statements

An If-Then statement is one way to direct the flow of traffic in programming.

These statements are used when the program must evaluate whether a

condition exists or not. Here is how you do code an if-then statement:

int x = 5;

if(x == 5){ NSLog(@"True");

}

else{ NSLog(@"False");

}

How to Use Switch Statements or Case Statements

Switch statements are used when a program must evaluate an option based

on a list of conditions. This is sometimes referred to as a “Case” statement.

Here is how you code a switch statement:switch (x) {

  case 1:

  NSLog(@"i = 1");

  break; case 5: NSLog(@"i = 5"); break; default: NSLog(@"default case"); break;

}

18 The Objective-C Crash Course

Page 19: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 19/33

How to Use Loops

Loops are used when a program must repeat a set of instructions many

times in a row. Objective-C has a few options that may be used when loops

are needed:

Using for loops

for (int y = 0; y < 3; y++) { NSLog(@"y = %i", y);

}

Using do loops

x = 0;

do{

  NSLog(@"x = %i", x);

x++;

}

while(x <= 4);

Using while loops

x = 0;

while (x <= 4 ) { NSLog(@"x = %i", x); x++;

}

19 The Objective-C Crash Course

Page 20: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 20/33

Using for each loops

//Create an array and add elements to it

NSMutableArray *anArray = [[NSMutableArray alloc] init];

[anArray addObject:@"Element 1"];[anArray addObject:@"Element 2"];

[anArray addObject:@"Element 3"];//Use a for each loop to iterate through the array

for (NSString *s in anArray) {

  NSLog(s);

}//Release the array

[anArray release];}

20 The Objective-C Crash Course

Page 21: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 21/33

Working with Classes and Subclasses

Subclassing in Objective-C is usually referred to as inheritance in other

programming languages. It is what you do when you want to create a

custom class that inherits properties and methods from another class.

Usually, the root class, NSObject, is what is used as a base class. This is theline of code that indicates we are using a subclass:

@interface myClass : NSObject {

@interface means that this is definition of the class, myClass is the name of 

our subclass, : means that this class is inheriting and NSObject is the name

of the class that we are inheriting from.

The code below shows a complete subclass that inherits from NSObject andit also happens to be the class used in the previous section, How to Use

Objects, Properties and Methods. See that section for demonstrations on

how to use the properties and methods of this subclass.

Generally, when you create your own subclass you use two files – an

interface file (ends in h) and an implementation file (ends in m). You must

add code to both files when writing code for your subclass.

XCode will create both of these files and fill in the details when you use

XCode to add a new NSObject subclass to your project.

21 The Objective-C Crash Course

Page 22: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 22/33

How to Add Properties to a Class Definition

Here is how you add a property to a subclass:

Interface File (myClass.h)

#import <Foundation/Foundation.h>

@interface myClass : NSObject {

NSString *name;

}

@property (nonatomic, retain) NSString *name;

@end

Implementation File (myClass.m)

#import "myClass.h"

@implementation myClass

@synthesize name;

-(void) dealloc{

[name release]; [super dealloc];

}

@end

22 The Objective-C Crash Course

Page 23: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 23/33

How to Add a Class Method

Class methods may be used even if an object has not been created. You

know a method is a class method when it as a “+” in front of the (void)

instead of a “-“. Here is how you would add a class method to your

subclass:

Interface File (myClass.h)

#import <Foundation/Foundation.h>

@interface myClass : NSObject {

NSString *name;

}

@property (nonatomic, retain) NSString *name;

+(void) demonstrateAClassMethod;

@end

Implementation File (myClass.m)

#import "myClass.h"

@implementation myClass

@synthesize name;

-(void) dealloc{

[name release];

[super dealloc];

}

+(void) demonstrateAClassMethod{

NSLog(@"Class Method");

}

@end

To use a class method, you must send a message to the class and not the

object.

23 The Objective-C Crash Course

Page 24: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 24/33

How to Add an Instance Method

Instance methods require an object to have been instantiated. You can tell

that a method is an instance method when it has a “-“ before (void). Here is

how you would code an instance method:

Interface File (myClass.h)

#import <Foundation/Foundation.h>

@interface myClass : NSObject {

NSString *name;

}

@property (nonatomic, retain) NSString *name;

-(void) demonstrateAnInstanceMethod;

+(void) demonstrateAClassMethod;

@end

Implementation File (myClass.m)

#import "myClass.h"

@implementation myClass

@synthesize name;

-(void) dealloc{

[name release];

[super dealloc];

}

-(void) demonstrateAnInstanceMethod{

NSLog(@"Instance Method");

}

+(void) demonstrateAClassMethod{

NSLog(@"Class Method");

}

@end

24 The Objective-C Crash Course

Page 25: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 25/33

How to Add a Method with a Parameter

Often you will want to be able to pass a parameter to your method. To do

this you follow the same pattern as before but you need to add more code to

the end of the statement, but before the “;”.

Consider this statement as an example:

-(void) demonstrateAnObjectMethodWithThisParameter:(NSString *) aParameter;

-(void) demonstrateAnObjectMethodWithThisParameter means that the

statement refers to the specified instance method. The “:” means that a

parameter will be required. (NSString *) Specifies the type of parameter

and aParameter specifies the local name of the parameter.

25 The Objective-C Crash Course

Page 26: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 26/33

Here is how you would put this into a class definition:

Interface File (myClass.h)

#import <Foundation/Foundation.h>

@interface myClass : NSObject {

NSString *name;

}

@property (nonatomic, retain) NSString *name;

-(void) demonstrateAnInstanceMethod;

+(void) demonstrateAClassMethod;

-(void) demonstrateAnObjectMethodWithThisParameter:(NSString *) aParameter;

@end

Implementation File (myClass.m)

#import "myClass.h"

@implementation myClass

@synthesize name;

-(void) dealloc{

[name release];

[super dealloc];

}

-(void) demonstrateAnInstanceMethod{

NSLog(@"Instance Method");

}

+(void) demonstrateAClassMethod{

NSLog(@"Class Method");}

-(void) demonstrateAnObjectMethodWithThisParameter:(NSString *) aParameter{

NSLog(aParameter);

}

@end

26 The Objective-C Crash Course

Page 27: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 27/33

Class methods may also use parameters and methods may use more than

one parameter.

See the complete code below for examples of methods that use more than

one parameter, a method that references the object it is contained in and afunction. This code is contained in aMethodWithTwoParameters,

aMethodThatReferencesSelf and aFunctionReturnsThatAString respectively.

Complete Code for a Class Definition

Interface File (myClass.h)

#import <Foundation/Foundation.h>

@interface myClass : NSObject { NSString *name;

}

@property (nonatomic, retain) NSString *name;

-(id)initWithNewName;

-(void) demonstrateAnInstanceMethod;

+(void) demonstrateAClassMethod;

-(void) demonstrateAnObjectMethodWithThisParameter:(NSString *) aParameter;

-(void) aMethodWithTwoParameters:(NSString *) firstParameter

aInteger:(int) secondParameter;

-(void) aMethodThatReferencesSelf;

-(NSString *) aFunctionReturnsThatAString;

@end

27 The Objective-C Crash Course

Page 28: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 28/33

Implementation File (myClass.m)

#import "myClass.h"

@implementation myClass

@synthesize name;

-(id)initWithNewName{

if (self = [super init]){

self.name = @"New Name";

}

return self;

}

-(void) dealloc{

[name release];

[super dealloc];

}

-(void) demonstrateAnInstanceMethod{

NSLog(@"Instance Method");

}

+(void) demonstrateAClassMethod{

NSLog(@"Class Method");

}

-(void) demonstrateAnObjectMethodWithThisParameter:(NSString *) aParameter{

NSLog(aParameter);

}

-(void) aMethodWithTwoParameters:(NSString *) firstParameter

aInteger:(int) secondParameter{

NSLog(@"First Parameter:%@, Second Parameter: %i:",

firstParameter, secondParameter);

}

-(void) aMethodThatReferencesSelf{

NSLog(@"Self:");

[self demonstrateAnInstanceMethod];

}

-(NSString *) aFunctionReturnsThatAString{

return @"A Returned String";}

@end

28 The Objective-C Crash Course

Page 29: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 29/33

Memory Management

When you are programming on the iPhone you need to worry about memory

- the iPhone does not use a garbage collection system to automate assigning

and releasing blocks of memory.

Reference Counting

The system used in the iPhone to deal with memory is called reference

counting. A number is assigned to every object that is created that is equal

to the number of times that object has been referenced by another object.

This number is referred to as a reference count or a retain count. When the

reference count is equal to zero, the object is allow to go away and the

memory associated with it is freed.

29 The Objective-C Crash Course

Page 30: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 30/33

How Reference Counting Works

When you create an object you generally use this pattern. First, you declare

an object of a class.

myClass *myObject;

Then you use the alloc method to allocate memory and the init constructor

to return an instance of the class.

myObject = [[myClass alloc] init];

When the alloc method is used the reference count of the myObject class is

incremented from 0 to 1.

As myObject goes through it’s life cycle other objects that require it to stick

around will send the myObject a retain message. This again increments the

retain count so that the object can be sure that myObject will not go out of 

memory while it is still needed. Here is how the retain message is sent.

[myObject retain];

When an object it is retained by you it is your responsibility to then release

the object. Releasing the object decreases the retain count by 1.

[myObject release];

This retain and release pattern corresponds to adding and subtracting from

the retain count. When the object reaches 0 then it disappears and its

memory is reclaimed by the system.

30 The Objective-C Crash Course

Page 31: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 31/33

Autorelease

Normally, we use this alloc, use and release pattern when working with

objects. If we do need to send a retain message we must match it with a

corresponding release message. That way, we know that we always have

the object when we needed but that it will free up memory when we do notneed it.

However, there are times when this system will not work. For example,

many classes have functions that return objects. The function cannot

release the object before it returns the object; whatever is using the function

will not be able to work with the object if it is released.

However, we cannot be sure that the returned object will eventually be

released. This puts us at risk of causing a memory leak. Memory leaks are

caused when an object’s retain count never reaches zero. These objectscontinue to take up memory even though they will no longer be used. This

causes problems in the memory limited environment of the iPhone system.

The solution to this problem is to use autorelease. This is a special system

managed pool of temporary objects that are periodically purged from the

system.

How to Use Autorelease

When you return an object from function you simply send the autoreleasemessage to the object before return it to the system.

-(myObject *) getAnObject{

myClass *myObject;

myObject = [[myClass alloc] init];

[myObject autorelease];

return myObject;

}

When you use autorelease in this way it is best to assume that the object

being returned will only be used temporarily. If the other components in

your system need the returned object for a longer period of time send a

retain message to keep the object around.

31 The Objective-C Crash Course

Page 32: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 32/33

Memory Management Pointers

• When you use alloc and init to create an object you will need to send a

release message when you are finished

• Objects that are returned through functions are usually autoreleased soyou must send a retain message to them to keep them around

• Adding objects to collections like navigation controllers, sub-views, arrays

and dictionaries automatically sends a retain message to the object.

• Releasing collections automatically sends a release message to every

object in the collection.

• When you use properties in your class definitions with the retain keyword

the system is creating code for your (in the background) that automaticallyretains the object. This is why you need to release these objects in the

dealloc method.

• The dealloc method is executed when the retain count of an object reaches

zero.

• One huge problem that occurs when objects attempt to access another

object that has been released from memory is that this causes the app to

crash.

• Another memory problem you will encounter is memory leaking.

• Learn how to use Instruments and NSZombie to diagnose and fix these

memory problems.

• These memory techniques only apply to objects and not C types. When

you are working with things like int, BOOL or double you do not need to

worry about the retain and release pattern.

32 The Objective-C Crash Course

Page 33: Objective-C Crash Course

8/8/2019 Objective-C Crash Course

http://slidepdf.com/reader/full/objective-c-crash-course 33/33

Final Word

At this point, you should be getting familiar enough with the Objective-C

language to fully implement your iPhone app with the help of the main How

to Make an iPhone App book. If you want to learn about the Objective-C

language in greater detail I would recommend this book: Learn Objective-C on the Mac . If this is your first exposure to any programming that I suggest

that you read Learn C on the Mac . as well in order to learn the basics of 

programming in the C language.