SlideShare a Scribd company logo
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

More Related Content

What's hot

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
Matteo Battaglio
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan 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 future
Sander Mak (@Sander_Mak)
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
Roman Elizarov
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
Ben Evans
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
Allan Huang
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
Kyle Oba
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
Runtime
RuntimeRuntime
Runtime
Jorge Ortiz
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
Lhouceine OUHAMZA
 
Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtime
Inferis
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
Mujtaba Haider
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
Apaichon Punopas
 
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 Practice
Alina Dolgikh
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
ygv2000
 

What's hot (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
 

Similar to Automatic Reference Counting

Little Known VC++ Debugging Tricks
Little Known VC++ Debugging TricksLittle Known VC++ Debugging Tricks
Little Known VC++ Debugging Tricks
Ofek Shilon
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
Roman Atachiants
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
Janie Clayton
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
Giuseppe Arici
 
Automatic Reference Counting
Automatic Reference Counting Automatic Reference Counting
Automatic Reference Counting
pragmamark
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
Janie Clayton
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
BlackRabbitCoder
 
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
NoSuchCon
 
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
Skills Matter
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
stable|kernel
 
Node.js debugging
Node.js debuggingNode.js debugging
Node.js debugging
Nicholas McClay
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
BeMyApp
 
ARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetupARC - Moqod mobile talks meetup
ARC - Moqod mobile talks meetup
Moqod
 
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
Idan Sheinberg
 
Power of linked list
Power of linked listPower of linked list
Power of linked list
Peter Hlavaty
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
Robert 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 numbers
Alexandre 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 Plone
David Glick
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
pythonandchips
 

Similar to 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
 

More from Robert Brown

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

More from 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
 

Recently uploaded

JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 

Recently uploaded (20)

JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 

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

Editor's Notes

  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