Professional Documents
Culture Documents
Iphone Memory Management Final Version
Iphone Memory Management Final Version
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
MemoryHog Demo
MemoryHog Demo The rest of the talk could be titled How not to go Boom. The basic problem: the devices dont have much memory and if you are piggy with memory, you are looking for toruble
Memory basics
Were interested in RAM, not the ash disk iPhone OS devices dont have much: Earlier devices: 128 MB iPhone 3GS, 3rd generation iPod, iPad: 256 MB By comparison latest Mac Book Pro (base model) has
4 GB RAM
Swapping
iPhone OS devices
Virtual memory - YES ! Paging - NO ! (except...) The OS has paging, but its disabled (probably so
you dont wear out the ash disk).
Jail-breakers can enable it. The no paging only applies to writable memory
pages. Read only memory (program text, les that are memory mapped [mmap] read-only) is paged.
10
Dynamic Memory
You can ask the system for memory at runtime. Dynamic memory comes from the heap Request memory with malloc (or cousin):
char* someBytes = malloc( numBytesNeeded );
As the heap grows your process size increases Return memory to the heap with free:
free( someBytes );
11
iPhone Addendum
As soon as you can.
12
13
All OC objects are heap-based Trying to create one on the stack is an error Under the hood the memory comes from malloc (or
a cousin like calloc) and is returned by free
14
No GC on the iPhone (no time? performance issues?) iPhone uses reference counting only
15
Reference Counting
Also called retain counting or managed memory. Each object keeps a count of how many other objects
are using it. (Usually discussed in terms of ownership.)
16
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]; release decrements the objects reference count. If the new reference count is zero, the object is deallocated.
17
-(void) useAFoo { Foo* aFoo = [[Foo alloc] init]; // Do something with aFoo return; }
18
The rules:
If you create an object (receive an object from a
method that begins with alloc or new or contains the word copy) you own the object. 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 objects reference count: [aFoo retain];
19
Rules, continued
You may also take ownership by copying the object (if
it is capable of being copied, the objects class must implement -copyWithZone:).
20
dealloc
If a release message causes an objects retain count
to drop to zero, the release method invokes the objects dealloc method. variables, it must release them in the dealloc method.
dealloc] as the last statement. It is NSObjects dealloc method that actually returns the objects bytes to the heap.
21
dealloc
22
23
autorelease
Sending an object an autorelease message
registers the object to receive a release message sometime in the future. It places the object in an autorelease pool. release message (one for each time it received an autorelease message) scheduled for the future. It counts as a release for bookkeeping purposes.
24
25
What do you mean all running apps? You cant 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
Demo
27
For other objects (except UIViewControllers) , register for low memory notication:
UIApplicationDidReceiveMemoryWarningNotification
28
29
UIViewController
- (void)didReceiveMemoryWarning
- (void)viewDidUnload
30
- [UIViewController viewDidUnload]
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]
31
32
33
Images
Size of compressed image le isnt relevant. In
memory, the image is roughly width * height * 4
34
+[UIImage imageNamed:]
Reads the le, uncompresses it, caches result Cached copy of data is kept even if the UIImage is
deallocated
Low memory condition causes cache to be purged. No direct control over when cache is purged. Use for small frequently drawn images.
35
+[UIImage imageWithContentsOfFile:]
Just reads enough of le to determine if it can open
the le.
UIImageView or as the contents of a CALayer also causes it to read and uncompress the le. The UIImageView or CALayer keep the expanded version.
36
37
38
Memory Usage (in MB) 8.6 MB image used with UIView subclass (stored in instance variable and drawn with drawinRect: )
imageNamed Initial Load UIImage Assign to UIView Remove from UIView 2.73 11.38 11.81 11.84 imageWithContentsofFile 2.73 2.78 3.20 3.04
39
40
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 oating point work
41
42
Bottom Line
Understand what you are doing Pay attention Use common sense
43
Object Allocation
44
NSZombie
First dealloc changes objects isa pointer so the object
becomes an instance of NSZombie
Zombies log messages You can set break point on messages to zombies:
[_NSZombie release]
45
checks for memory problems not perfect - some false negatives, more false
positives
47
48
Leaks
49
50
VM Tracker
part of the Object Allocation template Requires iPhone OS 3.1 and Mac OS 10.6
51
52
53