SlideShare uma empresa Scribd logo
1 de 34
Automatic Reference
Counting
Robert Brown
@robby_brown
What is ARC?
Automatic Reference Counting
  Similar to using smart pointers
Never need to call -release or -autorelease
More efficient than garbage collection
No 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 versa
Xcode 4.2+ only
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
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.
New Rules

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.
New Rules

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.
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.
New Rules

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.
New Rules

Cannot 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 Rules

To allow interoperation with manual retain-release code,
ARC imposes some constraints on method and
variable naming:
  You cannot give a property a name that begins with
  new.
New Rules

Summary:
 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 = [NSArray
arrayWithObjects:@"BYU",        arrayWithObjects:@"BYU",
@"CocoaHeads", nil];            @"CocoaHeads", nil];

NSString * path = [NSString     NSString * path = [NSString
pathWithComponents: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 Conversion

1.Edit > Refactor > Convert to Objective-C ARC
2.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 Referencing
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+
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
                                               Level




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
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
                                      Level




The casts are hard to remember
Use these macros instead:
  CFBridgingRetain(obj) = ARC to C
  CFBridgingRelease(obj) = C to ARC
Disabling ARC                                      Jedi
                                                   Level




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”
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
                                                   Level




Return by reference is fairly common, especially with
NSError.
Example:
-(BOOL)save:(NSError *__autoreleasing*)outError;
Return by Reference                              Jedi
                                                 Level




// What you write
NSError * error = nil; // Implicitly __strong.
if (![self save:&error]) {
     // An error occurred.
 }
Return by Reference                      Jedi
                                         Level




// What ARC writes
NSError * __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 temporary
variable
NSError * __autoreleasing error = nil;
if (![self save:&error]) {
     // An error occurred.
 }
Questions?
Want to Learn More?


WWDC 2011: Session 323
Transitioning to ARC Release Notes

Mais conteúdo relacionado

Mais procurados

Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureSander Mak (@Sander_Mak)
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waitingRoman Elizarov
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptLivingston Samuel
 
Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtimeInferis
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?Roman Elizarov
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 

Mais procurados (20)

Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the future
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
Runtime
RuntimeRuntime
Runtime
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtime
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 

Semelhante a Automatic Reference Counting

Little Known VC++ Debugging Tricks
Little Known VC++ Debugging TricksLittle Known VC++ Debugging Tricks
Little Known VC++ Debugging TricksOfek Shilon
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingGiuseppe Arici
 
Automatic Reference Counting
Automatic Reference Counting Automatic Reference Counting
Automatic Reference Counting pragmamark
 
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the CoreNSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the CoreNoSuchCon
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmSkills Matter
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDKBeMyApp
 
ARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetupARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetupMoqod
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worthIdan Sheinberg
 
Power of linked list
Power of linked listPower of linked list
Power of linked listPeter Hlavaty
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central DispatchRobert Brown
 
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersDefcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersAlexandre Moneger
 
When Good Code Goes Bad: Tools and Techniques for Troubleshooting Plone
When Good Code Goes Bad: Tools and Techniques for Troubleshooting PloneWhen Good Code Goes Bad: Tools and Techniques for Troubleshooting Plone
When Good Code Goes Bad: Tools and Techniques for Troubleshooting PloneDavid Glick
 

Semelhante a Automatic Reference Counting (20)

Little Known VC++ Debugging Tricks
Little Known VC++ Debugging TricksLittle Known VC++ Debugging Tricks
Little Known VC++ Debugging Tricks
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Automatic Reference Counting
Automatic Reference Counting Automatic Reference Counting
Automatic Reference Counting
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the CoreNSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Node.js debugging
Node.js debuggingNode.js debugging
Node.js debugging
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
ARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetupARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetup
 
Should Invoker Rights be used?
Should Invoker Rights be used?Should Invoker Rights be used?
Should Invoker Rights be used?
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
 
Power of linked list
Power of linked listPower of linked list
Power of linked list
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbersDefcon 22 - Stitching numbers - generating rop payloads from in memory numbers
Defcon 22 - Stitching numbers - generating rop payloads from in memory numbers
 
When Good Code Goes Bad: Tools and Techniques for Troubleshooting Plone
When Good Code Goes Bad: Tools and Techniques for Troubleshooting PloneWhen Good Code Goes Bad: Tools and Techniques for Troubleshooting Plone
When Good Code Goes Bad: Tools and Techniques for Troubleshooting Plone
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 

Mais de Robert Brown

Mais de Robert Brown (11)

High level concurrency
High level concurrencyHigh level concurrency
High level concurrency
 
Data Source Combinators
Data Source CombinatorsData Source Combinators
Data Source Combinators
 
Elixir
ElixirElixir
Elixir
 
MVVM
MVVMMVVM
MVVM
 
Reactive Cocoa
Reactive CocoaReactive Cocoa
Reactive Cocoa
 
UIKit Dynamics
UIKit DynamicsUIKit Dynamics
UIKit Dynamics
 
iOS State Preservation and Restoration
iOS State Preservation and RestorationiOS State Preservation and Restoration
iOS State Preservation and Restoration
 
Anti-Patterns
Anti-PatternsAnti-Patterns
Anti-Patterns
 
Pragmatic blocks
Pragmatic blocksPragmatic blocks
Pragmatic blocks
 
Core Data
Core DataCore Data
Core Data
 
Quick Look for iOS
Quick Look for iOSQuick Look for iOS
Quick Look for iOS
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Automatic Reference Counting

  • 2. What is ARC? Automatic Reference Counting Similar to using smart pointers Never need to call -release or -autorelease More efficient than garbage collection No more memory leaks! Doesn’t handle retain loops
  • 3. What is ARC? Includes a weak reference system (Lion/iOS 5.0+) ARC code works with non-ARC code and vice versa Xcode 4.2+ only
  • 4. 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
  • 5. 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.
  • 6. New Rules 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.
  • 7. New Rules 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.
  • 8. 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.
  • 9. New Rules 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.
  • 10. New Rules Cannot 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. New Rules To allow interoperation with manual retain-release code, ARC imposes some constraints on method and variable naming: You cannot give a property a name that begins with new.
  • 12. New Rules Summary: 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. Old way: ARC way: NSAutoreleasePool * pool = @autoreleasepool { // This is cool! [NSAutoreleasePool new]; NSArray * comps = [NSArray NSArray * comps = [NSArray arrayWithObjects:@"BYU", arrayWithObjects:@"BYU", @"CocoaHeads", nil]; @"CocoaHeads", nil]; NSString * path = [NSString NSString * path = [NSString pathWithComponents: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. Automatic Conversion 1.Edit > Refactor > Convert to Objective-C ARC 2.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. Demo
  • 16. Weak Referencing 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+
  • 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
  • 19. Lifetime Qualifiers Jedi Level __strong A retained reference (default) __weak Uses weak reference system
  • 20. Lifetime Qualifiers Jedi Level __unsafe_unretained Unretained reference—like assign property __autoreleasing Autoreleased reference
  • 21. What About C? Jedi Level 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
  • 22. Bridging Jedi Level __bridge Straight bridge cast __bridge_transfer -1 to the retain count __bridge_retained +1 to the retain count
  • 23. Bridging Made Easy Jedi Level The casts are hard to remember Use these macros instead: CFBridgingRetain(obj) = ARC to C CFBridgingRelease(obj) = C to ARC
  • 24. Disabling ARC Jedi Level 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”
  • 25. Demo
  • 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. Blocks Jedi Level // No retain loop __block __unsafe_unretained id unretainedSelf = self; [self setBlock:^{ [unretainedSelf doSomething]; [[unretainedSelf var] doSomethingElse]; }
  • 28. Blocks Jedi Level // Better alternative (iOS 5.0+) __weak id weakSelf = self; [self setBlock:^{ [weakSelf doSomething]; [[weakSelf var] doSomethingElse]; }
  • 29. Return by Reference Jedi Level Return by reference is fairly common, especially with NSError. Example: -(BOOL)save:(NSError *__autoreleasing*)outError;
  • 30. Return by Reference Jedi Level // What you write NSError * error = nil; // Implicitly __strong. if (![self save:&error]) { // An error occurred. }
  • 31. Return by Reference Jedi Level // What ARC writes NSError * __strong error = nil; NSError * __autoreleasing tmp = error; if (![self save:&tmp]) { // An error occurred. }
  • 32. Return by Reference Jedi Level // This isn’t a big deal, but it avoids the temporary variable NSError * __autoreleasing error = nil; if (![self save:&error]) { // An error occurred. }
  • 34. Want to Learn More? WWDC 2011: Session 323 Transitioning to ARC Release Notes

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n