Automatic ReferenceCountingRobert Brown@robby_brown
What is ARC?Automatic Reference Counting  Similar to using smart pointersNever need to call -release or -autoreleaseMore e...
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...
New RulesYou cannot explicitly invoke dealloc, or implement orinvoke retain, release, retainCount, or autorelease.  The pr...
New RulesYou may implement a dealloc method if you need tomanage resources other than releasing instancevariables. You do ...
New RulesCustom dealloc methods in ARC do not require a callto [super dealloc] (it actually results in a compiler error).T...
New RulesYou cannot use NSAllocateObject orNSDeallocateObject.You create objects using alloc; the runtime takes careof dea...
New RulesThere is no casual casting between id and void *.You must use special casts that tell the compiler aboutobject li...
New RulesCannot use NSAutoreleasePool objects.  ARC provides @autoreleasepool blocks instead.  These have an advantage of ...
New RulesTo allow interoperation with manual retain-release code,ARC imposes some constraints on method andvariable naming...
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 ...
Old way:                        ARC way:NSAutoreleasePool * pool =      @autoreleasepool {    // This is cool![NSAutorelea...
Automatic Conversion1.Edit > Refactor > Convert to Objective-C ARC2.Select the files you want to convert (probably all)3.Xc...
Demo
Weak ReferencingWeak reference doesn’t increment retain countWeak reference is nilled when the object is dealloc’dAdds som...
IBOutlets Weak reference:         Strong reference:   Used only with non-     Must be used for top-   top-level IBOutlets ...
Advanced ARC
Lifetime Qualifiers                  Jedi                                    Level __strong   A retained reference (default...
Lifetime Qualifiers                             Jedi                                               Level __unsafe_unretaine...
What About C?                                  Jedi                                               LevelARC does not manage...
Bridging                   Jedi                           Level__bridge  Straight bridge cast__bridge_transfer  -1 to the ...
Bridging Made Easy                    Jedi                                      LevelThe casts are hard to rememberUse the...
Disabling ARC                                      Jedi                                                   LevelARC can be ...
Demo
Blocks                                                   Jedi                                                         Leve...
Blocks                                            Jedi                                                  Level// No retain ...
Blocks                                  Jedi                                        Level// Better alternative (iOS 5.0+)_...
Return by Reference                                Jedi                                                   LevelReturn by r...
Return by Reference                              Jedi                                                 Level// What you wri...
Return by Reference                      Jedi                                         Level// What ARC writesNSError * __s...
Return by Reference                                     Jedi                                                        Level/...
Questions?
Want to Learn More?WWDC 2011: Session 323Transitioning to ARC Release Notes
Upcoming SlideShare
Loading in …5
×

Automatic Reference Counting

2,630 views

Published on

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

1 Comment
3 Likes
Statistics
Notes
  • ARC is not more efficient than garbage collection. It inserts atomic retain/release operations everywhere in the code, causing spread-out but in total higher CPU overhead than garbage collection. ARC can also not be trusted to prevent memory leaks if you make heavy use of Objective-C blocks (first-class functions). Preventing cycles can require some horrible boilerplate on heavy use of blocks. I think Apple had to stick to reference counting because it's too deeply tied in all of their legacy code (CoreFoundation and all). GC stop-the-world pauses are no reason for UI stutter either, so long as animations are on their own thread like in iOS (not the case in Android).
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
2,630
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
79
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide
  • \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

    1. 1. Automatic ReferenceCountingRobert Brown@robby_brown
    2. 2. 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
    3. 3. 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
    4. 4. 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
    5. 5. 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.
    6. 6. 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.
    7. 7. 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.
    8. 8. 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.
    9. 9. 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.
    10. 10. 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.
    11. 11. 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.
    12. 12. 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.
    13. 13. 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!
    14. 14. 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
    15. 15. Demo
    16. 16. 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+
    17. 17. 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
    18. 18. Advanced ARC
    19. 19. Lifetime Qualifiers Jedi Level __strong A retained reference (default) __weak Uses weak reference system
    20. 20. Lifetime Qualifiers Jedi Level __unsafe_unretained Unretained reference—like assign property __autoreleasing Autoreleased reference
    21. 21. 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
    22. 22. Bridging Jedi Level__bridge Straight bridge cast__bridge_transfer -1 to the retain count__bridge_retained +1 to the retain count
    23. 23. Bridging Made Easy Jedi LevelThe casts are hard to rememberUse these macros instead: CFBridgingRetain(obj) = ARC to C CFBridgingRelease(obj) = C to ARC
    24. 24. 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”
    25. 25. Demo
    26. 26. Blocks Jedi Level// WARNING: Retain loop!// The static analyzer will warn you about this.[self setBlock:^{ [self doSomething]; [_ivar doSomethingElse]; // Implicitly self->_ivar}
    27. 27. Blocks Jedi Level// No retain loop__block __unsafe_unretained id unretainedSelf = self;[self setBlock:^{ [unretainedSelf doSomething]; [[unretainedSelf var] doSomethingElse];}
    28. 28. Blocks Jedi Level// Better alternative (iOS 5.0+)__weak id weakSelf = self;[self setBlock:^{ [weakSelf doSomething]; [[weakSelf var] doSomethingElse];}
    29. 29. Return by Reference Jedi LevelReturn by reference is fairly common, especially withNSError.Example:-(BOOL)save:(NSError *__autoreleasing*)outError;
    30. 30. Return by Reference Jedi Level// What you writeNSError * error = nil; // Implicitly __strong.if (![self save:&error]) { // An error occurred. }
    31. 31. Return by Reference Jedi Level// What ARC writesNSError * __strong error = nil;NSError * __autoreleasing tmp = error;if (![self save:&tmp]) { // An error occurred. }
    32. 32. 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. }
    33. 33. Questions?
    34. 34. Want to Learn More?WWDC 2011: Session 323Transitioning to ARC Release Notes

    ×