SlideShare uma empresa Scribd logo
1 de 29
ARC
AUTOMATIC REFERENCE COUNTING
    BY. MUHAMMAD NABEEL ARIF
AT A GLANCE

• Objective C provides two methods of memory
  management
 • MRR (manual – retain – release)
   • Implemented through a model known as Reference counting,
     that NSObject class provides
 • ARC (automatic reference counting)
   • It uses the same reference counting system as MRR, but it inserts
     the appropriate memory management method calls for you at
     compile-time
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
REFERENCE COUNTING
WHAT IS ARC?

•   Automatic Reference Counting
•   Never need to call -release or –autorelease
•   More efficient than garbage collection
•   No more memory leaks!
    • Doesn’t handle retain loops
•   Memory management a job of Compiler
•   Includes a weak reference system (Lion/iOS 5.0)
•   ARC code works with non-ARC code as well
•   Xcode 4.2+ only
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.
• 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.
• 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.
• 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

• You cannot use NSAutoreleasePool objects.
 • ARC provides @autoreleasepool blocks instead. These have
   an advantage of being more efficient than
   NSAutoreleasePool.
   @autoreleasepool {
       // Code, such as a loop that creates a large number of temporary
       objects.
   }
• 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 a constraint on method naming:
 • You cannot give an accessor a name that begins with new.
   This in turn means that you can‘t, for example, declare a
   property whose name begins with new unless you specify a
   different getter:

   // Won't work:
   @property NSString *newTitle;
   // Works:
   @property (getter=theNewTitle) NSString *newTitle;
NEW LIFETIME QUALIFIERS

• ARC introduces several new lifetime qualifiers for
  objects, and weak references. A weak reference
  does not extend the lifetime of the object it points
  to, and automatically becomes nil when there are
  no strong references to the object.
  • You should take advantage of these qualifiers to manage
    the object graphs in your program. In particular, ARC does
    not guard against strong reference cycles (previously
    known as retain cycles). Judicious use of weak relationships
    will help to ensure you don‘t create cycles.
PROPERTY ATTRIBUTES


The keywords weak and strong are introduced as
new declared property attributes, as shown in the
following examples.
  // The following declaration is a synonym for: @property(retain) MyClass *myObject;

  @property(strong) MyClass *myObject;

  // The following declaration is similar to "@property(assign) MyClass *myObject;‖
  // except that if the MyClass instance is deallocated,
  // the property value is set to nil instead of remaining as a dangling

  pointer.@property(weak) MyClass *myObject;

• Under ARC, strong is the default for object types.
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+
VARIABLE QUALIFIERS

• __strong is the default. An object remains ―alive‖ as long
  as there is a strong pointer to it.
• __weak specifies a reference that does not keep the
  referenced object alive. A weak reference is set to nil
  when there are no strong references to the object.
• __unsafe_unretained specifies a reference that does not
  keep the referenced object alive and is not set to nil
  when there are no strong references to the object. If the
  object it references is deallocated, the pointer is left
  dangling.
• __autoreleasing is used to denote arguments that are
  passed by reference (id *) and are autoreleased on
  return.
USING QUALIFIERS

• You should decorate variables correctly. When
  using qualifiers in an object variable declaration,
  the correct format is:

  ClassName * qualifier variableName;

  for example:
  MyClass * __weak myWeakReference;
  MyClass * __unsafe_unretained myUnsafeReference;
IBOUTLETS

• Weak reference:
 • Used only with non-top-level IBOutlets
 • Automatically nils IBOutlet in low memory condition
 • Requires some extra overhead
• Strong reference:
 • Must be used for top-level IBOutlets
 • May be used for non-top-level IBOutlets
 • Manually nil IBOutlet in -viewDidUnload
AVOID STRONG REFERENCE CYCLES

You can use lifetime qualifiers to avoid strong reference cycles. For
example, typically if you have a graph of objects arranged in a parent-
child hierarchy and parents need to refer to their children and vice
versa, then you make the parent-to-child relationship strong and the
child-to-parent relationship weak.
BRIDGING

• __bridge transfers a pointer between Objective-C and
  Core Foundation with no transfer of ownership.
• __bridge_retained or CFBridgingRetain casts an
  Objective-C pointer to a Core Foundation pointer and
  also transfers ownership to you.
• You are responsible for calling CFRelease or a related
  function to relinquish ownership of the object.
• __bridge_transfer or CFBridgingRelease moves a non-
  Objective-C pointer to Objective-C and also transfers
  ownership to ARC.
• ARC is responsible for relinquishing ownership of the
  object.
ARC VS GC

• ARC != garbage collection. There is no run time
  penalty, it is done at compile time.
• GC require a separate thread to collect garbage
  and utilize RAM and CPU resources.
• ARC is similar to GC in that you don't have to
  manually retain or release objects.
• ARC does not handles ‗ReferenceCycles‘ where as
  GC handles it.
• ARC is predictable about releasing objects where
  as GC is not as much.
ADVANTAGES OF ARC

• It is faster than your old code. It is safer than your old
  code. It is easier than your old code.
• It is not garbage collection. It has no GC runtime cost.
• The compiler inserts retains and releases in all the places
  you should have anyway. But it's smarter than you and
  can optimize out the ones that aren't actually needed
• Apple is suggestin ARC due to ease and performance,
  so in future projects ARC projects will dominate.
• The benefit is a significant degree of protection from
  common memory management mistakes.
• ARC is to minimize the amount of routine memory mgmt
  code we have to write, letting us focus the business logic
  of an app.
ADVANTAGES OF ARC

• To conclude: ARC is NOT a free pass to be mindless
  about memory; it is a tool to help humans avoid
  repetitive tasks, that cause stress and are prone to
  error, therefore better delegated to a machine (the
  compiler, in this case).
DOWNSIDE OF ARC

• If you're a long-time ObjC developer, you will twitch
  for about a week when you see ARC code.
• There is some (very) small complications in bridging
  to Core Foundation code.
• ARC will not work at all on iPhoneOS 3 or Mac OS X
  10.5 or e
• __weak pointers do not work correctly on iOS 4 or
  Mac OS X 10.6, but fairly easy to work around.
  __weak pointers are great, but they're not the #1
  selling point of ARC.
DISABLING ARC

• 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”
WHAT ABOUT C?

• 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
CONVERSION TO ARC

We are going to convert the Artists app to ARC.
Basically this means we‘ll just get rid of all the calls to
retain, release, and autorelease, but we‘ll also run
into a few situations that require special attention.
  • There are three things you can do to make your app ARC-
    compatible:
    • Xcode has an automatic conversion tool that can migrate your
      source files.
    • You can convert the files by hand.
    • You can disable ARC for source files that you do not want to
      convert. This is useful for third-party libraries that you don‘t feel
      like messing with.
AUTOMATIC CONVERSION

• From Xcode‘s menu, choose EditRefactorConvert
  to Objective-C ARC.
DEMO
QUESTIONS?
WANT TO LEARN MORE?

• About Memory Management
    • http://bit.ly/YQBPFC
• Memory Management Programming Guide for Core
  Foundation
    • http://bit.ly/VkfcGz
• Transitioning to ARC Release Notes
    • http://bit.ly/I5sJeJ
• Beginning ARC in iOS 5 Tutorial Part 1
    • http://bit.ly/var1R6
• Why ARC over GC
    • http://bit.ly/WVJ5Qd
• Friday Q&A 2011-09-30: Automatic Reference Counting
    • http://bit.ly/ouh41L

Mais conteúdo relacionado

Destaque

iOS Memory Management Basics
iOS Memory Management BasicsiOS Memory Management Basics
iOS Memory Management BasicsBilue
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]Kuba Břečka
 
Apple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating systemApple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating systemDhruv Patel
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 

Destaque (7)

iOS Memory Management Basics
iOS Memory Management BasicsiOS Memory Management Basics
iOS Memory Management Basics
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]
 
Apple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating systemApple iOS - A modern way to mobile operating system
Apple iOS - A modern way to mobile operating system
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Apple iOS
Apple iOSApple iOS
Apple iOS
 
iOS platform
iOS platformiOS platform
iOS platform
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 

Último

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Último (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Automatic reference counting

  • 1. ARC AUTOMATIC REFERENCE COUNTING BY. MUHAMMAD NABEEL ARIF
  • 2. AT A GLANCE • Objective C provides two methods of memory management • MRR (manual – retain – release) • Implemented through a model known as Reference counting, that NSObject class provides • ARC (automatic reference counting) • It uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for you at compile-time
  • 3. 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. WHAT IS ARC? • Automatic Reference Counting • Never need to call -release or –autorelease • More efficient than garbage collection • No more memory leaks! • Doesn’t handle retain loops • Memory management a job of Compiler • Includes a weak reference system (Lion/iOS 5.0) • ARC code works with non-ARC code as well • Xcode 4.2+ only
  • 6.
  • 7. 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. • 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. • 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. • 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.
  • 9. NEW RULES • You cannot use NSAutoreleasePool objects. • ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool. @autoreleasepool { // Code, such as a loop that creates a large number of temporary objects. } • You cannot use memory zones. • There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway.
  • 10. NEW RULES To allow interoperation with manual retain-release code, ARC imposes a constraint on method naming: • You cannot give an accessor a name that begins with new. This in turn means that you can‘t, for example, declare a property whose name begins with new unless you specify a different getter: // Won't work: @property NSString *newTitle; // Works: @property (getter=theNewTitle) NSString *newTitle;
  • 11. NEW LIFETIME QUALIFIERS • ARC introduces several new lifetime qualifiers for objects, and weak references. A weak reference does not extend the lifetime of the object it points to, and automatically becomes nil when there are no strong references to the object. • You should take advantage of these qualifiers to manage the object graphs in your program. In particular, ARC does not guard against strong reference cycles (previously known as retain cycles). Judicious use of weak relationships will help to ensure you don‘t create cycles.
  • 12. PROPERTY ATTRIBUTES The keywords weak and strong are introduced as new declared property attributes, as shown in the following examples. // The following declaration is a synonym for: @property(retain) MyClass *myObject; @property(strong) MyClass *myObject; // The following declaration is similar to "@property(assign) MyClass *myObject;‖ // except that if the MyClass instance is deallocated, // the property value is set to nil instead of remaining as a dangling pointer.@property(weak) MyClass *myObject; • Under ARC, strong is the default for object types.
  • 13. 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+
  • 14. VARIABLE QUALIFIERS • __strong is the default. An object remains ―alive‖ as long as there is a strong pointer to it. • __weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object. • __unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling. • __autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.
  • 15. USING QUALIFIERS • You should decorate variables correctly. When using qualifiers in an object variable declaration, the correct format is: ClassName * qualifier variableName; for example: MyClass * __weak myWeakReference; MyClass * __unsafe_unretained myUnsafeReference;
  • 16. IBOUTLETS • Weak reference: • Used only with non-top-level IBOutlets • Automatically nils IBOutlet in low memory condition • Requires some extra overhead • Strong reference: • Must be used for top-level IBOutlets • May be used for non-top-level IBOutlets • Manually nil IBOutlet in -viewDidUnload
  • 17. AVOID STRONG REFERENCE CYCLES You can use lifetime qualifiers to avoid strong reference cycles. For example, typically if you have a graph of objects arranged in a parent- child hierarchy and parents need to refer to their children and vice versa, then you make the parent-to-child relationship strong and the child-to-parent relationship weak.
  • 18. BRIDGING • __bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership. • __bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. • You are responsible for calling CFRelease or a related function to relinquish ownership of the object. • __bridge_transfer or CFBridgingRelease moves a non- Objective-C pointer to Objective-C and also transfers ownership to ARC. • ARC is responsible for relinquishing ownership of the object.
  • 19. ARC VS GC • ARC != garbage collection. There is no run time penalty, it is done at compile time. • GC require a separate thread to collect garbage and utilize RAM and CPU resources. • ARC is similar to GC in that you don't have to manually retain or release objects. • ARC does not handles ‗ReferenceCycles‘ where as GC handles it. • ARC is predictable about releasing objects where as GC is not as much.
  • 20. ADVANTAGES OF ARC • It is faster than your old code. It is safer than your old code. It is easier than your old code. • It is not garbage collection. It has no GC runtime cost. • The compiler inserts retains and releases in all the places you should have anyway. But it's smarter than you and can optimize out the ones that aren't actually needed • Apple is suggestin ARC due to ease and performance, so in future projects ARC projects will dominate. • The benefit is a significant degree of protection from common memory management mistakes. • ARC is to minimize the amount of routine memory mgmt code we have to write, letting us focus the business logic of an app.
  • 21. ADVANTAGES OF ARC • To conclude: ARC is NOT a free pass to be mindless about memory; it is a tool to help humans avoid repetitive tasks, that cause stress and are prone to error, therefore better delegated to a machine (the compiler, in this case).
  • 22. DOWNSIDE OF ARC • If you're a long-time ObjC developer, you will twitch for about a week when you see ARC code. • There is some (very) small complications in bridging to Core Foundation code. • ARC will not work at all on iPhoneOS 3 or Mac OS X 10.5 or e • __weak pointers do not work correctly on iOS 4 or Mac OS X 10.6, but fairly easy to work around. __weak pointers are great, but they're not the #1 selling point of ARC.
  • 23. DISABLING ARC • 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”
  • 24. WHAT ABOUT C? • 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
  • 25. CONVERSION TO ARC We are going to convert the Artists app to ARC. Basically this means we‘ll just get rid of all the calls to retain, release, and autorelease, but we‘ll also run into a few situations that require special attention. • There are three things you can do to make your app ARC- compatible: • Xcode has an automatic conversion tool that can migrate your source files. • You can convert the files by hand. • You can disable ARC for source files that you do not want to convert. This is useful for third-party libraries that you don‘t feel like messing with.
  • 26. AUTOMATIC CONVERSION • From Xcode‘s menu, choose EditRefactorConvert to Objective-C ARC.
  • 27. DEMO
  • 29. WANT TO LEARN MORE? • About Memory Management • http://bit.ly/YQBPFC • Memory Management Programming Guide for Core Foundation • http://bit.ly/VkfcGz • Transitioning to ARC Release Notes • http://bit.ly/I5sJeJ • Beginning ARC in iOS 5 Tutorial Part 1 • http://bit.ly/var1R6 • Why ARC over GC • http://bit.ly/WVJ5Qd • Friday Q&A 2011-09-30: Automatic Reference Counting • http://bit.ly/ouh41L