iphone memory management final version

53
 iPhone OS Memory Management Robert Clair VTM Seattle April 25, 2010 1

Upload: vish172001

Post on 18-Jul-2015

73 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 1/53

 

iPhone OS Memory Management

Robert Clair

VTM Seattle

April 25, 2010

1

Page 2: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 2/53

 

Roadmap

•Demo

•Memory basics

•Objective-C memory management review

•Low memory warnings and responding to them

•Keeping your memory usage low

•Tools for memory management

2

Page 3: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 3/53

 

MemoryHog Demo

3

Page 4: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 4/53

 

MemoryHog Demo

The rest of the talk could be titled “How

not to go Boom.”

The basic problem: the devices don’t have

much memory and if you are piggy withmemory, you are looking for toruble

4

Page 5: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 5/53

 

Memory basics

•We’re interested in RAM, not the flash “disk”

• iPhone OS devices don’t have much:

•Earlier devices: 128 MB

• iPhone 3GS, 3rd generation iPod, iPad: 256 MB

•By comparison latest Mac Book Pro (base model) has4 GB RAM

5

Page 6: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 6/53

 

Virtual Memory and Paging (Swapping)

•The are not the same thing

•Virtual memory

•Each process sees its own address space

•MMU translates between virtual addresses and

physical addresses

•Paging - system swaps pages of memory to and from

secondary storage (the disk)

6

Page 7: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 7/53

Swapping

7

   

Page 8: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 8/53

iPhone OS devices

•Virtual memory - YES !

•Paging - NO ! (except...)

•The OS has paging, but it’s disabled (probably soyou don’t wear out the flash disk).

• Jail-breakers can enable it.

•The “no paging” only applies to writable memorypages. Read only memory (program text, files that

are memory mapped [mmap] read-only) is paged.

8

 

Page 9: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 9/53

Virtual address space of a Unix process

9

 

Page 10: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 10/53

•Data Segment - global variables

•Stack - automatic variables (variables defined in

functions or methods)

•Heap - dynamically allocated memory

10

 

Page 11: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 11/53

Dynamic Memory

•You can ask the system for memory at runtime.

•Dynamic memory comes from the heap

•Request memory with malloc (or cousin):

•As the heap grows your process size increases

•Return memory to the heap with free:

char* someBytes = malloc( numBytesNeeded );

free( someBytes );

11

 

Page 12: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 12/53

The Golden Rule of Dynamic Allocation

When you allocate memory from the heap you must

give it back when you are finished using it !

iPhone Addendum

As soon as you can.

12

 

Page 13: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 13/53

An aside about malloc

• iPhone OS malloc does lazy allocation

• It notes your request, but doesn’t commit pages forthe requested memory until you try and write on it.

•This can get you in trouble if you think the memory is

there, but the system doesn’t actually have the

memory when you go to use it.

13

 

Page 14: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 14/53

Objective-C memory management review

•OC Objects are chunks of memory with an isa 

pointer (points to the class object, tells what the object

is)

•All OC objects are heap-based

•Trying to create one on the stack is an error

•Under the hood the memory comes from malloc(ora cousin like calloc) and is returned by free

14

 

Page 15: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 15/53

•On Mac OS X you can choose between reference

counting and garbage collection (GC)

•No GC on the iPhone (no time? performance issues?)

• iPhone uses reference counting only

15

 

Page 16: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 16/53

Reference Counting

•Also called “retain counting” or “managed memory”.

•Each object keeps a count of how many other objectsare using it. (Usually discussed in terms of

“ownership”.)

•When an object’s reference count becomes zero, the

object is deallocated and its memory is returned to

the heap.

16

 

Page 17: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 17/53

If you create an object, you own it:

Foo* aFoo = [[Foo alloc] init];

You must eventually balance the creation by

relinquishing your ownership with a release 

message:

[foo release];

releasedecrements the object’s reference count. Ifthe new reference count is zero, the object is

deallocated.

17

 

Page 18: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 18/53

If you don’t, you have a leak:

-(void) useAFoo{

Foo* aFoo = [[Foo alloc] init]; // Do something with aFoo

return;}

18 

Page 19: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 19/53

• If you create an object (receive an object from a

method that begins with allocor newor contains

the word copy) you “own” the object.

• If you receive an object from any other method, you

do not own the object. If you want to keep the object(store it in an instance variable) you must take

ownership of the object by sending it a retain 

message, which increments the object’s reference

count:

The rules:

[aFoo retain];

19 

Page 20: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 20/53

Rules, continued

•You may also take ownership by copying the object (if

it is capable of being copied, the object’s class must

implement -copyWithZone:).

• In all cases, if you own an object, either because you

created it or you retained it, you must eventually

relinquish your ownership by sending the object areleasemessage

20  

Page 21: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 21/53

• If a releasemessage causes an object’s retain count

to drop to zero, the releasemethod invokes the

object’s deallocmethod.

• If the object has stored other objects in its instancevariables, it must release them in the dealloc 

method.

•The deallocmethod must invoke [superdealloc] as the last statement. It is NSObject’s

deallocmethod that actually returns the object’s

 b tes to the hea .

dealloc

21 

Page 22: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 22/53

dealloc

22 

Page 23: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 23/53

A problem (convenience constructors andsuch):

+ (Foo*) foo{Foo* aFoo = [[Foo alloc] init];

return aFoo;}

The solution:

autorelease

23  

Page 24: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 24/53

•Sending an object an autoreleasemessage

registers the object to receive a releasemessage

sometime in the future. It places the object in an

autorelease pool.•When the pool is drained the object receives a

releasemessage (one for each time it received an 

autoreleasemessage)

•An autoreleaseis a release , just one that is

scheduled for the future. It counts as a releasefor

 bookkeeping purposes.

autorelease

24 

Page 25: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 25/53

One last thought

Use properties and synthesize your accessors

whenever you can:

@property (nonatomic, retain) Foo* aFoo;

@synthesize aFoo;

It will automate much of your memory management.

25   

Page 26: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 26/53

Low Memory Warnings

• When the number of unused pages in memory drops

 below a threshold, the system will evict read-onlypages. If that does not free up enough memory it sends

all running apps a low memory warning. Each app is

expected to respond by releasing any memory that it is

not currently using.

• What do you mean “all running apps”?

• You can’t multi-task, but Apple can.

• Safari, Mail, etc, may be running in the background.

• If the low memory condition persists, the system will

eventually terminate your app.26

 

Page 27: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 27/53

How much memory can an app safelyuse?

•Unknowable - depends on what else is going on

•Apple DTS engineer: "You will get memory warnings.

They are a fact of life, and are generally unavoidable.

That does not mean that you are doing anything

wrong.”

•Demo

27 

Page 28: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 28/53

Handling Low Memory Warnings

In your application delegate implement:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)

application

For other objects (except UIViewControllers) , register

for low memory notification:

UIApplicationDidReceiveMemoryWarningNotification

28 

Page 29: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 29/53

[ [NSNotificationCenter defaultCenter]addObserver: selfselector: @selector(lowMemory:)name: UIApplicationDidReceiverMemoryWarningNotification

object: nil ];

...

- (void) lowMemory:(NSNotification *)notification

{ // Release anything you can}

Registering for Low Memory Notifications

29 

Page 30: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 30/53

UIViewController

•Default implementation checks to see if view can be

released (has no superview) and releases it if possible.• If it releases the view, it calls

•3.0+, no need to override (use viewDidUnload) , but if you

override it, remember to call super

- (void)didReceiveMemoryWarning

- (void)viewDidUnload

30 

Page 31: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 31/53

•Release anything that can be easily recovered.

•Release nib objects held in outlets

•Objects are stored in outlets using accessors if they exist

•Accessor must retain any top level nib object

• If there is no accessor the object is sent a retain message

when the nib is loaded

• Invoke [ super viewDidUnload] (?? - not clear in docs)

- [UIViewController viewDidUnload]

31 

Page 32: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 32/53

Don’t block the main thread (run loop)

•Low memory warnings are delivered on the main thread

• If you are doing something time consuming on the main

thread, you may never receive the low memory warningand your app may be terminated.

• If your app uses a lot of memory on a secondary thread

you must find a way to pass on the warning.

32 

Page 33: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 33/53

Keeping Memory Footprint Small

•Don’t leak (follow the rules).

•Don’t pseudo-leak.

•Load resources lazily if you can.

•Be careful with images.

33   

Page 34: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 34/53

Images

•Size of compressed image file isn’t relevant. In

memory, the image is roughly width * height * 4

•Drawing a big image in a small space doesn’t make it

smaller. Size your images to their final size.

•Different UIImagemethods (imageNamed ,

imageWithContentsOfFile:) do different things

34 

Page 35: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 35/53

+[UIImage imageNamed:]

•Reads the file, uncompresses it, caches result

•Cached copy of data is kept even if the UIImageisdeallocated

•Low memory condition causes cache to be purged.

•No direct control over when cache is purged.

•Use for small frequently drawn images.

35 

Page 36: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 36/53

+[UIImageimageWithContentsOfFile:]

• Just reads enough of file to determine if it can open

the file.

•Reads and uncompresses the file each time it draws.

Uses uncompressed size worth of memory only

temporarily.

•Assigning a UIImagecreated this way toa

UIImageView or as the contents of a CALayeralsocauses it to read and uncompress the file. The

UIImageViewor CALayerkeep the expanded

version.

36 

Page 37: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 37/53

Demo image app

37 

Page 38: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 38/53

Memory Usage (in MB)8.6 MB image used with UIImageView

imageNamed imageWithContentsofFile

Initial 2.46 2.46

Load UIImage 11.12 2.51

 Assign to

UIImageView 11.09 11.09

Remove from

UIImageView11.12 2.51

38 

( )

Page 39: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 39/53

Memory Usage (in MB)8.6 MB image used with UIViewsubclass (stored

in instance variable and drawn with

drawinRect: 

imageNamed imageWithContentsofFile

Initial 2.73 2.73

Load UIImage 11.38 2.78

 Assign to

UIView11.81 3.20

Remove from

UIView11.84 3.04

39 

Page 40: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 40/53

Other ways to uncompress and cache aUIImage

•Assign it to a UIImageViewthat isn’t in the viewhierarchy.

•Draw it with CoreGraphics to get a CGImageRef ,

then Use the CGImageRef to create a new UIImage

40  

Page 41: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 41/53

Other strategies:

•Create your own caches for other large resources

(sounds, etc.)

•Consider memory mapping (mmap)•Use thumb instructions (Xcode default) if you are not

doing floating point work 

•Avoid autorelease if possible. (Opinions differ,probably only in case of large objects.)

41 

Page 42: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 42/53

42 

Page 43: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 43/53

Bottom Line

•Understand what you are doing

•Pay attention

•Use common sense

43 

Page 44: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 44/53

Tools for debugging memory problems

•NSZombie

•Clang Static Analyzer

• Instruments

•Leaks template

•VM Tracker (In Object Allocation template)

•Object Allocation

44 

Page 45: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 45/53

NSZombie

•First dealloc changes object’s isa pointer so the object becomes an instance of NSZombie

•Zombies log messages

•You can set break point on messages to zombies:

[_NSZombie release]

•Turn on zombies by setting NSZombieEnabled 

environment variable to YES

45 

Page 46: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 46/53

Can set NSZombieEnabled in Xcode (project or

target info) or in ~/.dbxinit:

define enable-zombiesset env NSDebugEnabled=YESset env NSZombieEnabled=YESset env NSDeallocateZombies=NOset env NSHangOnUncaughtException=YES

set env NSAutoreleaseFreedObjectCheckEnabled=YESfb -[_NSZombie retain]fb -[_NSZombie release]fb -[_NSZombie methodSignatureForSelector:]fb -[_NSZombie respondsToSelector:]fb -[_NSZombie class]fb -[_NSZombie forward::]

fb -[NSException raise]endenable-zombies

The environment variables are defined in NSDebug.h

46 

Cl S A l

Page 47: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 47/53

Clang Static Analyzer

•checks for memory problems•not perfect - some false negatives, more false

positives

47 

Page 48: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 48/53

48 

Page 49: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 49/53

Leaks

49 

Page 50: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 50/53

50 

VM T k

Page 51: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 51/53

VM Tracker

•part of the Object Allocation template

•Requires iPhone OS 3.1 and Mac OS 10.6

51 

Page 52: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 52/53

52 

Page 53: iPhone Memory Management Final Version

5/16/2018 iPhone Memory Management Final Version - slidepdf.com

http://slidepdf.com/reader/full/iphone-memory-management-final-version 53/53