Automatic reference counting

29
ARC AUTOMATIC REFERENCE COUNTING BY. MUHAMMAD NABEEL ARIF

description

ARC stands for Automatic Reference Counting. Apple has introduced ARC in IOS 5 to free developers from managing memory manually and focus on business logic of applications.

Transcript of Automatic reference counting

Page 1: Automatic reference counting

ARCAUTOMATIC REFERENCE COUNTING

BY. MUHAMMAD NABEEL ARIF

Page 2: Automatic reference counting

AT A GLANCE

• Objective C provides two methods of memory management• MRR (manual – retain – release)• Implemented through a model known as Reference counting,

that NSObject class provides

• ARC (automatic reference counting)• It uses the same reference counting system as MRR, but it

inserts the appropriate memory management method calls for you at compile-time

Page 3: Automatic reference counting

MANUAL REFERENCE COUNTING

• Just to help you appreciate ARC...• Retain: +1 retain count (claim ownership)• Release: -1 retain count (revoke ownership)• Autorelease: Ownership is transferred to latest

autorelease pool on the current thread• When retain count reaches 0, the object is deleted.

• With ARC you ignore all of this

Page 4: Automatic reference counting

REFERENCE COUNTING

Page 5: Automatic reference counting

WHAT IS ARC?

• Automatic Reference Counting• Never need to call -release or –autorelease• More efficient than garbage collection• No more memory leaks!• Doesn’t handle retain loops

• Memory management a job of Compiler• Includes a weak reference system (Lion/iOS 5.0)• ARC code works with non-ARC code as well• Xcode 4.2+ only

Page 6: Automatic reference counting
Page 7: Automatic reference counting

NEW RULES

• You cannot explicitly invoke dealloc, or implement or invoke retain, release, retainCount, or autorelease.

• The prohibition extends to using @selector(retain), @selector(release), and so on.

• You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC.

• Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.

• You can still use CFRetain, CFRelease, and other related functions with Core Foundation-style objects

Page 8: Automatic reference counting

NEW RULES

• You cannot use NSAllocateObject or NSDeallocateObject.• You create objects using alloc; the runtime takes care of

deallocating objects.

• You cannot use object pointers in C structures.• Rather than using a struct, you can create an Objective-C

class to manage the data instead.

• There is no casual casting between id and void *.• You must use special casts that tell the compiler about

object lifetime. You need to do this to cast between Objective-C objects and Core Foundation types that you pass as function arguments.

Page 9: Automatic reference counting

NEW RULES

• You cannot use NSAutoreleasePool objects.• ARC provides @autoreleasepool blocks instead. These

have an advantage of being more efficient than NSAutoreleasePool.@autoreleasepool {

// Code, such as a loop that creates a large number of temporary objects.

}

• You cannot use memory zones.• There is no need to use NSZone any more—they are

ignored by the modern Objective-C runtime anyway.

Page 10: Automatic reference counting

NEW RULES

To allow interoperation with manual retain-release code, ARC imposes a constraint on method naming:• You cannot give an accessor a name that begins with

new. This in turn means that you can’t, for example, declare a property whose name begins with new unless you specify a different getter:

// Won't work:@property NSString *newTitle; // Works:@property (getter=theNewTitle) NSString *newTitle;

Page 11: Automatic reference counting

NEW LIFETIME QUALIFIERS

• ARC introduces several new lifetime qualifiers for objects, and weak references. A weak reference does not extend the lifetime of the object it points to, and automatically becomes nil when there are no strong references to the object.• You should take advantage of these qualifiers to manage

the object graphs in your program. In particular, ARC does not guard against strong reference cycles (previously known as retain cycles). Judicious use of weak relationships will help to ensure you don’t create cycles.

Page 12: Automatic reference counting

PROPERTY ATTRIBUTES

The keywords weak and strong are introduced as new declared property attributes, as shown in the following examples.

// The following declaration is a synonym for: @property(retain) MyClass *myObject;

@property(strong) MyClass *myObject;

// The following declaration is similar to "@property(assign) MyClass *myObject;”// except that if the MyClass instance is deallocated,// the property value is set to nil instead of remaining as a dangling

pointer.@property(weak) MyClass *myObject;

• Under ARC, strong is the default for object types.

Page 13: Automatic reference counting

• Weak reference doesn’t increment retain count• Weak reference is nilled when the object is

dealloc’d• Adds some overhead due to bookkeeping• Great for delegates• @property(nonatomic, weak) id delegate;

• iOS 5.0+

WEAK REFERENCING

Page 14: Automatic reference counting

VARIABLE QUALIFIERS

• __strong is the default. An object remains “alive” as long as there is a strong pointer to it.

• __weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.

• __unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.

• __autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.

Page 15: Automatic reference counting

USING QUALIFIERS

• You should decorate variables correctly. When using qualifiers in an object variable declaration, the correct format is:

ClassName * qualifier variableName;

for example:MyClass * __weak myWeakReference;MyClass * __unsafe_unretained myUnsafeReference;

Page 16: Automatic reference counting

IBOUTLETS

• Weak reference:• Used only with non-top-level IBOutlets• Automatically nils IBOutlet in low memory condition• Requires some extra overhead

• Strong reference:• Must be used for top-level IBOutlets• May be used for non-top-level IBOutlets• Manually nil IBOutlet in -viewDidUnload

Page 17: Automatic reference counting

AVOID STRONG REFERENCE CYCLES

You can use lifetime qualifiers to avoid strong reference cycles. For example, typically if you have a graph of objects arranged in a parent-child hierarchy and parents need to refer to their children and vice versa, then you make the parent-to-child relationship strong and the child-to-parent relationship weak.

Page 18: Automatic reference counting

BRIDGING

• __bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.

• __bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you.

• You are responsible for calling CFRelease or a related function to relinquish ownership of the object.

• __bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.

• ARC is responsible for relinquishing ownership of the object.

Page 19: Automatic reference counting

ARC VS GC

• ARC != garbage collection. There is no run time penalty, it is done at compile time. • GC require a separate thread to collect garbage

and utilize RAM and CPU resources.• ARC is similar to GC in that you don't have to

manually retain or release objects.• ARC does not handles ‘ReferenceCycles’ where as

GC handles it.• ARC is predictable about releasing objects where

as GC is not as much.

Page 20: Automatic reference counting

ADVANTAGES OF ARC

• It is faster than your old code. It is safer than your old code. It is easier than your old code.

• It is not garbage collection. It has no GC runtime cost. • The compiler inserts retains and releases in all the places

you should have anyway. But it's smarter than you and can optimize out the ones that aren't actually needed

• Apple is suggestin ARC due to ease and performance, so in future projects ARC projects will dominate.

• The benefit is a significant degree of protection from common memory management mistakes.

• ARC is to minimize the amount of routine memory mgmt code we have to write, letting us focus the business logic of an app.

Page 21: Automatic reference counting

ADVANTAGES OF ARC

• To conclude: ARC is NOT a free pass to be mindless about memory; it is a tool to help humans avoid repetitive tasks, that cause stress and are prone to error, therefore better delegated to a machine (the compiler, in this case).

Page 22: Automatic reference counting

DOWNSIDE OF ARC

• If you're a long-time ObjC developer, you will twitch for about a week when you see ARC code.• There is some (very) small complications in

bridging to Core Foundation code.• ARC will not work at all on iPhoneOS 3 or Mac OS

X 10.5 or e• __weak pointers do not work correctly on iOS 4 or

Mac OS X 10.6, but fairly easy to work around. __weak pointers are great, but they're not the #1 selling point of ARC.

Page 23: Automatic reference counting

DISABLING ARC

• ARC can be disabled on a file-level. • Project file > Main target > Build phases >

Compile sources > Add compiler flag “-fno-objc-arc”• If ARC is not on by default, it can be turned on

manually with “-fobjc-arc”

Page 24: Automatic reference counting

WHAT ABOUT C?

• ARC does not manage memory for C• You must call free() for every malloc()• Core Foundation objects use CFRelease()

• Toll-free bridging requires an extra keyword

Page 25: Automatic reference counting

CONVERSION TO ARC

We are going to convert the Artists app to ARC. Basically this means we’ll just get rid of all the calls to retain, release, and autorelease, but we’ll also run into a few situations that require special attention.• There are three things you can do to make your app ARC-

compatible:• Xcode has an automatic conversion tool that can migrate

your source files.• You can convert the files by hand.• You can disable ARC for source files that you do not want to

convert. This is useful for third-party libraries that you don’t feel like messing with.

Page 26: Automatic reference counting

AUTOMATIC CONVERSION

• From Xcode’s menu, choose Edit\Refactor\Convert to Objective-C ARC.

Page 27: Automatic reference counting

DEMO

Page 28: Automatic reference counting

QUESTIONS?

Page 29: Automatic reference counting

WANT TO LEARN MORE?

• About Memory Management • http://bit.ly/YQBPFC

• Memory Management Programming Guide for Core Foundation

• http://bit.ly/VkfcGz

• Transitioning to ARC Release Notes • http://bit.ly/I5sJeJ

• Beginning ARC in iOS 5 Tutorial Part 1 • http://bit.ly/var1R6

• Why ARC over GC • http://bit.ly/WVJ5Qd

• Friday Q&A 2011-09-30: Automatic Reference Counting

• http://bit.ly/ouh41L