Memory management in iOS.

Post on 10-Feb-2017

335 views 0 download

transcript

Study group Memory management

2014/12/16 JoeHsieh

Outline

• Item 29 : Understand Reference Counting

• Item 30 : Use ARC to Make Reference Counting Easier.

Manual Retain Release (MRR)

Manual Retain Release(1/2)

• Tracks how many owners the object has.When it reaches zero, the OS allowed to destroy it.

Manual Retain Release(2/2)• increment

• alloc : Creates an object and claims ownership of it.

• retain : Claims ownership of an existing object

• copy : Copy an object and claims ownership of it

• decrement

• release : Relinquishes ownership of an object and destroy it immediately

• autorelease : Relinquishes ownership of an object but defer its destruction

In case of retain/release is not balanced

• Forgets to release, retain cycle, etc… : memory leak

• Releases too many times, etc… : dangling pointer(zombie)

ExampleMemory Management in Property Accessors

CarStore

Crash?

Dangling pointer and memory leak.

setter will not retain inventory

superstore forget to release

Fixes it, but it’s still memory leak?

Finally…

Automatic Reference Counting (ARC)

In order to solve the verbose problem of MMR, savior is coming!

@property (strong, nonatomic) NSMutableArray *inventory;

For property accessor

ARC• Complier will add retain, release and autorelease

for you automatically.You cannot add these by yourself.

• Memory leak and dangling pointer exist still.

• ARC is only for Objective-C.That means memory management of CoreFundation and C is still MRR.(malloc, free, CFRetain, CFRelease)

Retain Cycle

How to prevent leak ?• Pointer to any parent must not be retained.

Retain Cycle Example

• strong delegate

• retain variables in block

How to solve leak ?• Breaks retain relationship explicitly.

Retain Cycle Example

• Timer

• NSURLConnectionDelegate

Retain Cycle Demo

PrinterVC

Printer

References

• http://rypress.com/tutorials/objective-c/memory-management

• http://www.cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html

• https://www.mikeash.com/pyblog/friday-qa-2010-04-30-dealing-with-retain-cycles.html