Automatic Reference Counting
Upcoming SlideShare
Loading in...5
×
 

Automatic Reference Counting

on

  • 2,196 views

ARC makes Objective-C development so much easier and enjoyable by eliminating almost all need to manually handle memory management.

ARC makes Objective-C development so much easier and enjoyable by eliminating almost all need to manually handle memory management.

Statistics

Views

Total Views
2,196
Views on SlideShare
2,196
Embed Views
0

Actions

Likes
4
Downloads
68
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Automatic Reference Counting Automatic Reference Counting Presentation Transcript

  • Automatic ReferenceCountingRobert Brown@robby_brown
  • What is ARC?Automatic Reference Counting Similar to using smart pointersNever need to call -release or -autoreleaseMore efficient than garbage collectionNo more memory leaks! Doesn’t handle retain loops
  • What is ARC?Includes a weak reference system (Lion/iOS 5.0+)ARC code works with non-ARC code and vice versaXcode 4.2+ only
  • Manual Reference CountingJust 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
  • New RulesYou cannot explicitly invoke dealloc, or implement orinvoke retain, release, retainCount, or autorelease. The prohibition extends to using @selector(retain), @selector(release), and so on.
  • New RulesYou may implement a dealloc method if you need tomanage resources other than releasing instancevariables. You do not have to (indeed you cannot)release instance variables, but you may need to invoke[systemClassInstance setDelegate:nil] on systemclasses and other code that isn’t compiled using ARC.
  • New RulesCustom dealloc methods in ARC do not require a callto [super dealloc] (it actually results in a compiler error).The chaining to super is automated and enforced bythe compiler.You can still use CFRetain, CFRelease, and otherrelated functions with Core Foundation-style objects.
  • New RulesYou cannot use NSAllocateObject orNSDeallocateObject.You create objects using alloc; the runtime takes careof 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.
  • New RulesThere is no casual casting between id and void *.You must use special casts that tell the compiler aboutobject lifetime. You need to do this to cast betweenObjective-C objects and Core Foundation types thatyou pass as function arguments.
  • New RulesCannot use NSAutoreleasePool objects. ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool.You cannot use memory zones. There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway.
  • New RulesTo allow interoperation with manual retain-release code,ARC imposes some constraints on method andvariable naming: You cannot give a property a name that begins with new.
  • New RulesSummary: ARC does a lot of stuff for you. Just write your code and trust ARC to do the right thing. If you write C code, then you actually have to do some work.
  • Old way: ARC way:NSAutoreleasePool * pool = @autoreleasepool { // This is cool![NSAutoreleasePool new];NSArray * comps = [NSArray NSArray * comps = [NSArrayarrayWithObjects:@"BYU", arrayWithObjects:@"BYU",@"CocoaHeads", nil]; @"CocoaHeads", nil];NSString * path = [NSString NSString * path = [NSStringpathWithComponents:comps]; pathWithComponents:comps];NSURL * url = [[NSURL alloc] NSURL * url = [[NSURL alloc]initWithPath:path]; initWithPath:path];// Do something with the URL. // Do something with the URL.[url release]; // Hey look! No release![pool drain]; } // Automatic drain!
  • Automatic Conversion1.Edit > Refactor > Convert to Objective-C ARC2.Select the files you want to convert (probably all)3.Xcode will let you know if it can’t convert certain parts You may want to continue on errors Xcode > Preferences > General > Continue building after errors
  • Demo
  • Weak ReferencingWeak reference doesn’t increment retain countWeak reference is nilled when the object is dealloc’dAdds some overhead due to bookkeepingGreat for delegates @property(nonatomic, weak) id delegate;iOS 5.0+
  • IBOutlets Weak reference: Strong reference: Used only with non- Must be used for top- top-level IBOutlets level IBOutlets Automatically nils May be used for non- IBOutlet in low top-level IBOutlets memory condition Manually nil IBOutlet in Requires some extra -viewDidUnload overhead
  • Advanced ARC
  • Lifetime Qualifiers Jedi Level __strong A retained reference (default) __weak Uses weak reference system
  • Lifetime Qualifiers Jedi Level __unsafe_unretained Unretained reference—like assign property __autoreleasing Autoreleased reference
  • What About C? Jedi LevelARC does not manage memory for CYou must call free() for every malloc() Core Foundation objects use CFRelease()Toll-free bridging requires an extra keyword
  • Bridging Jedi Level__bridge Straight bridge cast__bridge_transfer -1 to the retain count__bridge_retained +1 to the retain count
  • Bridging Made Easy Jedi LevelThe casts are hard to rememberUse these macros instead: CFBridgingRetain(obj) = ARC to C CFBridgingRelease(obj) = C to ARC
  • Disabling ARC Jedi LevelARC can be disabled on a file-level.Project file > Main target > Build phases > Compilesources > Add compiler flag “-fno-objc-arc”If ARC is not on by default, it can be turned onmanually with “-fobjc-arc”
  • Demo
  • Blocks Jedi Level// WARNING: Retain loop!// The static analyzer will warn you about this.[self setBlock:^{ [self doSomething]; [_ivar doSomethingElse]; // Implicitly self->_ivar}
  • Blocks Jedi Level// No retain loop__block __unsafe_unretained id unretainedSelf = self;[self setBlock:^{ [unretainedSelf doSomething]; [[unretainedSelf var] doSomethingElse];}
  • Blocks Jedi Level// Better alternative (iOS 5.0+)__weak id weakSelf = self;[self setBlock:^{ [weakSelf doSomething]; [[weakSelf var] doSomethingElse];}
  • Return by Reference Jedi LevelReturn by reference is fairly common, especially withNSError.Example:-(BOOL)save:(NSError *__autoreleasing*)outError;
  • Return by Reference Jedi Level// What you writeNSError * error = nil; // Implicitly __strong.if (![self save:&error]) { // An error occurred. }
  • Return by Reference Jedi Level// What ARC writesNSError * __strong error = nil;NSError * __autoreleasing tmp = error;if (![self save:&tmp]) { // An error occurred. }
  • Return by Reference Jedi Level// This isn’t a big deal, but it avoids the temporaryvariableNSError * __autoreleasing error = nil;if (![self save:&error]) { // An error occurred. }
  • Questions?
  • Want to Learn More?WWDC 2011: Session 323Transitioning to ARC Release Notes