SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von Robert Brown

Mehr von 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
 

Kürzlich hochgeladen

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Kürzlich hochgeladen (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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

Hinweis der Redaktion

  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