SlideShare ist ein Scribd-Unternehmen logo
1 von 118
Downloaden Sie, um offline zu lesen
Automatic Reference
                      Counting



Giuseppe Arici - @giuseppearici
Superpartes Innovation Campus

MOBILE DEVELOPER CONFERENCE 24 – 25 MAGGIO 2012
                                         1
Giuseppe ARiCi
       Apple iOS & Mac OS X Addicted Developer
        Superpartes Innovation Campus & H-Farm

       Group Founder & Cocoa Preacher




                                                                       m
        # Pragma Mark ― pragmamark.org




                                                                     co
                                                           pe y ;)
                                                                 ci.
                                                        sep bo
                                                             ari
                                                     giu Fan
       A Social & Lazy Connected Node




                                                    → ot a
        [ tt | in | fb | * ] / giuseppe.arici




                                                 ard n
                                                I'm
       Mail Forwarder & Spammer



                                                vC
        giuseppe.arici@gmail.com



2
ARC
3
Attenzione: è un medicinale, leggere attentamente il foglio illustrativo.
      Consultare il medico se il disturbo si presenta ripetutamente. I medicinali
     vanno assunti con cautela, per un breve periodo di tempo, non superando le
    dosi consigliate e solo per le indicazioni riportate nel foglio illustrativo. In caso
     di dubbio rivolgersi al medico o al farmacista. Tenere il medicinale fuori dalla
             portata e dalla vista dei bambini. Da usare solo in età adulta.



4
OS X & iOS
5
Session Timeline

          • Da dove nasce ?
          • Che cos’è ?
    ARC   • Come funziona ?
          • Quando utilizzarlo ?


6
Memory Management 100
    UIImage <0x12345678>

     @”Hello WhyMCA !”


    NSData <0a1b2c3d4e...>


     UIVIew Backing Store




7
Memory Management 100
    UIImage <0x12345678>




    UIVIew Backing Store




8
malloc / free
    UIImage <0x12345678>




    UIVIew Backing Store




9
Manual Reference Counting
     UIImage <0x12345678>
                            1


     UIVIew Backing Store
                            3



10
Manual Reference Counting
     UIImage <0x12345678>
                            1


     UIVIew Backing Store
                            2



11
Manual Reference Counting
                            0


     UIVIew Backing Store
                            2



12
Garbage Collection 100




13
Garbage Collection 200
     Generation 1   Generation 2   Generation 3




14
Garbage Collection 300




15
Garbage Collection 300




16
Garbage Collection 300




17
Garbage Collection 300




                    Heap Compaction




18
Garbage Collection 400




      High Performance Concurrent
            Garbage Collector
19
Garbage Collection 400




                      X
     read barrier


20
C GC
      vs




21
Puntatori che giocano a
          Nascondino




22
Apple l’ha fatto comunque !




23
Limiti del GC Objective-C




24
Limiti del GC Objective-C

     NSData *data = [obj someData];
     const char *bytes = [data bytes];

     NSUInteger length = [data length];
     for (NSUInteger i = 0; i < length; ++i) {
         printf(“%x”, bytes[i]);
     }



25
Limiti del GC Objective-C




26
Limiti del GC Objective-C




27
iPhone GC
          vs




28
iPhone Android
           vs




29
30
Automatic Reference
                Counting
     “Automatic Reference Counting (ARC) in Objective-C
     makes memory management the job of the compiler. By
     enabling ARC with the new Apple LLVM compiler, you
     will never need to type retain or release again,
     dramatically simplifying the development process, while
     reducing crashes and memory leaks. The compiler has a
     complete understanding of your objects, and releases
     each object the instant it is no longer used, so apps run
     as fast as ever, with predictable, smooth performance.”
              (Apple, “iOS 5 for developers” – http://developer.apple.com/technologies/ios5)



31
Static Analyzer




32
Analysis + Auto-Fix
         + Goodies




33
Requisiti di Sistema

     •   iOS 5

     •   OS X 10.7

     •   iOS 4 - no runtime !

     •   OS X 10.6 (64-bit) - no runtime !




34
Requisiti di Runtime

     •   Clang (LLVM compiler) 3.0 or later

     •   Obj-C Runtime: objc4 493.9 or later

     •   For iOS4 or OS X 10.6: libarclite_iphoneos.a or
         libarclite_macosx.a is linked to make ARC work




35
Conversione ad ARC




36
Conversione ad ARC




37
Conversione ad ARC
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
         // code here
     [pool release];


     @autoreleasepool {
         // code here
     }


     NSString *s = [(id)CFStringCreateWithX(…) autorelease];


     NSString *s = CFBridgingRelease(CFStringCreateWithX(…));




38
Conversione Automatica




     From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments.



39
Conversione Automatica




40
Nessuno è perfetto !
               Eccezioni
                                  Toll-Free Bridging
 Strani Autorelease Pools
                                       Singleton


     Structs                                  { case }


      Giochetti con i Puntatori          Blocks

41
Conversione Parziale




42
Come Funziona ARC

     ARC è costituito da due componenti principali:
     • ARC front end compiler
     • ARC optimizer.



43
ARC front end compiler

     • Inserisce le release correttamente
     • ivar (strong): inserisce le release nel dealloc
     • Nel dealloc chiama il [super dealloc]
     • Genera errori sui qualificatori inconsistenti


44
ARC optimizer

     • Rimuove le retain e le release superflue
     • Ottimizza le prestazioni, minimizzando le
       sequenza multiple di retain e [auto]release




45
Come Funziona ARC

     Foo *obj = [[Foo alloc] init];
     [foo bar];




46
Come Funziona ARC

     Foo *obj = [[Foo alloc] init];
     [foo bar];
     [foo release];




47
Come Funziona ARC

     Foo *obj = [[Foo alloc] init];
     [foo bar];
     objc_release(foo);




48
Come Funziona ARC
                   retain       retain
       release
              release          release
     retain       retain               retain
                 retain     release
     release                          release
                   retain
        retain                  release
                     release
               retain        release


49
Come Funziona ARC
     Foo *obj = [self foo];
     [foo bar];

     [self setFoo: newFoo];

     [foo baz];




50
Come Funziona ARC
     Foo *obj = objc_retain([self foo]);
     [foo bar];
     [self setFoo: newFoo];
     [foo baz];
     objc_release(foo);




51
Come Funziona ARC

     - (Foo *) foo
     {
       return _foo;
     }




52
Come Funziona ARC

     - (Foo *) foo
     {
       return [[_foo retain] autorelease];
     }




53
Come Funziona ARC

     - (Foo *) foo
     {
       return objc_retainAutoreleaseReturnValue(_foo);
     }




54
Come Funziona ARC

      retain
      autorelease
      retain
      release

55
Come Funziona ARC

      retain
      autorelease
      retain
      release

56
Come Funziona ARC
         objc_retainAutoreleaseReturnValue

                  metodo chiamato

                  Autorelease Pool

                 metodo chiamante
     objc_retainAutorelease dReturnValue

57
Come Funziona ARC

      retain


      release

58
Riferimenti Ciclici




     1                1
59
Riferimenti Ciclici




     0                1
60
zeroing weak references
             Riferimento “debole” non sicuro



     nil
                                     X         release

             Riferimento __weak


                                     X
                           nil
61
Instruments




62
Memory Management Rules

     •   You have ownership of any objects you create.

     •   You can take ownership of an object using retain.

     •   When no longer needed, you must relinquish
         ownership of an object you own.

     •   You must not relinquish ownership of an object
         you don’t own.




63
Memory Management Rules

     Azione su oggetto Objective-C     Metodo Objective-C

     Create and have ownership of it   alloc/new/copy/mutableCopy

     Take ownership of it              retain

     Relinquish it                     release

     Dispose of it                     dealloc




64
Qualificatori di Ownership

     In ARC le variabili id o di tipo oggetto devono avere
     uno di questi 4 qualificatori di ownership:

     •   __strong (default)

     •   __weak

     •   __unsafe_unretained

     •   __autoreleasing




65
__strong
     /* ARC */
                  id obj = [[NSObject alloc] init];
     {
          //id __strong obj = [[NSObject alloc] init];
             id __strong obj = [[NSObject alloc] init];
          id obj = [[NSObject alloc] init];
     }


     /* non-ARC */
     {
          id obj = [[NSObject alloc] init];
          [obj release];
     }



         • Default for ‘id’ and object types !
66
__weak

     {
         id __strong obj0 = [[NSObject alloc] init];
         id __weak obj1 = obj0;
     }


         •   No ownership of the object

         •   When discarded, the variable is assigned to nil

         •   In OS X, not all classes support weak




67
__unsafe_unretained

     id __unsafe_unretained obj = [[NSObject alloc] init];

     warning: assigning retained obj to unsafe_unretained variable;
     obj will be released after assignment [-Warc-unsafe-retained-assign]



          •    UNSAFE

          •    __weak only for iOS5 / OSX Lion (or later).

          •    You must take care of the variables manually




68
__autoreleasing

     @autoreleasepool
     {
             id __strong obj = [NSMutableArray array];
     }


     - (BOOL) performOperationWithError:(NSError **)error;


     - (BOOL) performOperationWithError:(NSError * __autoreleasing *)error;




         •   Pointer to ‘id’ or object types is qualified with
             __autoreleasing as default


69
Initialization

     id __strong obj0;
     id __weak obj1;
     id __autoreleasing obj2;


     id __strong obj0 = nil;
     id __weak obj1 = nil;
     id __autoreleasing obj2 = nil;


      Any variables that are qualified with __strong, __weak,
      and __autoreleasing, are initialized with nil.



70
Coding With ARC Rules

     • Che cosa è vietato fare
     • Che cosa è obbligatorio fare
     • Che cosa si può fare, con attenzione !


71
Rule 1
     1. Forget about using retain, release, retainCount, and
        autorelease



       [obj release];

       error: ARC forbids explicit message send of 'release'
             [obj release];




72
Rule 2
     2. Forget about using NSAllocateObject and
        NSDeallocateObject



      NSAllocateObject (Class c, NSUInteger extraBytes, NSZone *zone)

      error: 'NSAllocateObject' is unavailable:
            not available in automatic reference counting mode




73
Rule 3
     3. Follow the naming rule for methods related to object
        creation


     • if begins { alloc, new, copy, mutableCopy }, the caller has ownership

     • if begins { init }:
                                  - (id) init ...
       • instance method
       • return ‘id’ or types of [super|sub]class
       • not registered in autoreleasepool: the caller has ownership
       • special case: “initialize”


74
Rule 3 (Positive False)

     -(NSString*) copyRightString;


     -(NSString*) copyRightString NS_RETURNS_NON_RETAINED;




 •   NS_RETURNS_NON_RETAINED

 •   NS_RETURNS_RETAINED




75
Rule 4
     4. Forget about calling super dealloc explicitly



       - (void) dealloc {
            free(buffer);
            [super dealloc];
       }


       error: ARC forbids explicit message send of 'dealloc'
       [super dealloc];
             not available in automatic reference counting mode




76
Rule 5
     5. Use @autoreleasepool Instead of NSAutoreleasePool



      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
      ...
      [pool drain];


      error: 'NSAutoreleasePool' is unavailable:
            not available in automatic reference counting mode
            NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
            ^




77
Rule 6
     6. Forget About Using Zone (NSZone)




     •   If __OBJC2__ is defined, the runtime just ignores zones




78
Rule 7
     7. Object Type Variables Cannot Be Members of struct or
        union in C


       struct Data { NSMutableArray *array; };


       error: ARC forbids Objective-C objs in structs or unions
            NSMutableArray *array;




79
Rule 8
     8. 'id' and 'void *' Have to Be Cast Explicitly

       id obj = [[NSObject alloc] init];
       void *p = obj;


       error: implicit conversion of a non-Objective-C pointer type 'void *' to 'id' is disallowed with ARC

        Special kind of casts:

        •    (__bridge cast)

        •    (__bridge_retained cast)

        •    (__bridge_transfer cast)



80
Rule 8 (__bridge cast)


     id obj = [[NSObject alloc] init];
     void *p = (__bridge void *)obj;
     id o = (__bridge id)p;




81
Rule 8 (__bridge_retained cast)


     /* ARC */
     id obj = [[NSObject alloc] init];
     void *p = (__bridge_retained void *)obj;


     /* non-ARC */
     id obj = [[NSObject alloc] init];
     void *p = obj;
     [(id)p retain];




82
Rule 8 (__bridge_transfer cast)


     /* ARC */
     id obj = (__bridge_transfer id)p;



     /* non-ARC */
     id obj = (id)p;
     [obj retain];
     [(id)p release];




83
Rule 8 (Toll-Free Bridging)


     CFTypeRef CFBridgingRetain(id X)
     {
             return (__bridge_retained CFTypeRef)X;
     }


     id CFBridgingRelease(CFTypeRef X)
     {
             return (__bridge_transfer id)X;
     }




         •   Convert an object between Obj-C and Core Foundation.

84
Rule 8 (Toll-Free Bridging)

     (__bridge cast)
              passaggio diretto del blocco puntato
              nessun trasferimento di ownership

     CFBridgingRetain()
              trasferimento di ownership
              da ARC a Core Foundation

     CFBridgingRelease()
              trasferimento di ownership
              da Core Foundation ad ARC




85
Rule 9
     9. Switch cases must be wrapped in scope with { }


       switch (someInt) {
           case 0:
           {
               NSLog(@"Case 0");
           }
           break;
       }




86
Rule 10
     10.Exceptions use must be exceptional




     •   For performance purpose, ARC code leaks on exceptions
     •   In Obj-C ARC is not exception-safe for normal releases by default
     •   -fobjc-arc-exceptions / -fno-objc-arc-exceptions: enable / disable
     •   In Obj-C++ -fobjc-arc-exceptions is enabled by default




87
Rule 11
     11.IBOutlet must be declared as weak




     • Outlets should be defined as declared properties
     • Outlets should generally be weak
     • Top-level objects (or, in iOS, a storyboard scene) should be strong




                       Resource Programming Guide
88
Rule 12
     12.Singletons should be redefined with dispatch_async

       static MyClass *sharedManager = nil;                          - (id)retain

       + (MyClass*)sharedManager                                     {

       {                                                                 return self;

           @synchronized(self) {                                     }

               if (sharedManager == nil) {                           - (NSUInteger)retainCount

                   sharedManager =                                   {

                          [[super allocWithZone:NULL] init];             return NSUIntegerMax;   //cannot be released

               }                                                     }

           }                                                         - (oneway void)release

           return sharedManager;                                     {

       }                                                                 //do nothing

       + (id)allocWithZone:(NSZone *)zone                            }

       {                                                             - (id)autorelease

           return [[self sharedManager] retain];                     {

       }                                                                 return self;

       - (id)copyWithZone:(NSZone *)zone                             }

       {

           return self;

       }




                                             Resource Programming Guide
89
Rule 12 (new singleton)
     + (id)sharedInstance {
           static dispatch_once_t predicate;
           dispatch_once(&predicate, ^{
                 sharedInstance = [[MyClass alloc] init];
           });
           return sharedInstance;
     }


     Single threaded results                          Multi threaded results
     -----------------------                          -----------------------
         @synchronized: 3.3829 seconds                @synchronized: 33.5171 seconds
         dispatch_once: 0.9891 seconds                dispatch_once: 1.6648 seconds


               http://bjhomer.blogspot.it/2011/09/synchronized-vs-dispatchonce.html


90
Rule 13
     13.Be careful with performSelector



       #pragma clang diagnostic push
       #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
           [self performSelector:self.mySel];
       #pragma clang diagnostic pop




91
Constructs With ARC

     • Property
     • Array
     • Block


92
Property

     Property modifier    Ownership qualifier
     assign              __unsafe_unretained
     copy                __strong (note: new copied object is assigned)
     retain              __strong
     strong              __strong
     unsafe_unretained   __unsafe_unretained
     weak                __weak



93
Property


     •   Same ownership rules as variables

     •   copy: copies the object by using copyWithZone

     •   manually declared ivar has to have the same
         ownership qualifier as the property




94
Property

     @property (nonatomic, readonly) MyObj* obj;
     @synthesize obj;


     error: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or
     storage attribute



       •    ARC forbids synthesizing a readonly property without
            specifying an ownership qualifier




95
Array

     id objs0[10];
     id __weak objs1[20];


     NSMutableArray *objs2 = [NSMutableArray alloc] init];




      •   'C' static arrays qualified with {__strong, __weak,
          __autoreleasing} are initialized with nil

      •   For dynamic arrays, should be used containers in the
          Foundation Framework


96
Block
     void (^block)(void) = ^{
         [self doSomethingImportant];
     };
     ivar = block; // ARC inserts [block copy]




97
Block
     return ^{
         [self doSomethingGreat];
     };




98
Block
     [array addObject: ^{ … }];

     - (id)method
     {
         return ^{ … };
     }




99
Block
      [[[[[[[[[[block copy] copy]
          copy] copy] copy] copy]
          copy] copy] copy] copy]




100
Block
      __block variable
      in MRC: mutable & “debole”
      in ARC: mutable & strong !



      __weak variable




101
Block & Riferimenti Ciclici i
      MyObj
      {
          id ivar;
          void (^block)(void);
      }


                         ^{
                              [self something];
                              [ivar something];
                         };


102
Block & Riferimenti Ciclici
      __weak MyClass *weakSelf = self;
      ^{
          [weakSelf something];
      };




103
Block & Riferimenti Ciclici
      __weak MyClass *weakSelf = self;
      ^{
          if (weakSelf)
          {
              [weakSelf->ivar something];
          }
      };




104
Block & Riferimenti Ciclici
      __weak MyClass *weakSelf = self;
      ^{
          if (weakSelf)
          { nil !?
              [weakSelf->ivar something];
          }
      };




105
Block & Riferimenti Ciclici
      __weak MyClass *weakSelf = self;
      ^{
          MyClass *localSelf = weakSelf;
          if (localSelf)
          {
              [localSelf->ivar something];
          }
      };


106
ARC MACRO
      // define some LLVM3 macros if the code is compiled with a
      different compiler (ie LLVMGCC42)
      #ifndef __has_feature
      #define __has_feature(x) 0
      #endif
      #ifndef __has_extension
      #define __has_extension __has_feature // Compatibility with
      pre-3.0 compilers.
      #endif


      #if __has_feature(objc_arc) && __clang_major__ >= 3
      #define ARC_ENABLED 1
      #endif // __has_feature(objc_arc)


                 Check @ compile-time if ARC is enabled

107
Conclusioni

      •   La Garbage collection é una gran bella idea !

      •   L'Objective-C è un gran bel linguaggio !



                          MA
      •   L'Objective-C + La Garbage Collection non sono
          una gran bella accoppiata !


108
Conclusioni



      ARC non è la Garbage Collection

                     … anche se ci arriva vicino ;)



109
Conclusioni

      •   Le zeroing weak references sono indispensabili !

      •   Utilizziamo __weak per evitare i riferimenti ciclici !

      •   Utilizziamo __unsafe_unretained se e solo se non
          possiamo usare __weak !

      •   Utilizziamo Instruments Leaks per individuare i
          riferimenti ciclici !




110
Conclusioni

      •   ARC sa gestire soltanto gli oggetti Objective-C !

      •   Utilizziamo sempre __bridge, CFBridgingRetain,
          CFBridgingRelease per interagire con Core
          Foundation !




111
Conclusioni

      •   ARC è una figata !

      •   Iniziamo subito ad usarlo !

      •   Convertiamo il nostro codice !

      •   Risparmiamo tempo !

      •   Risparmiamo denaro !

      •   Viviamo meglio !



112
ARC Reference: documentation and articles
        Clang: Automatic Reference Counting documentation
       • Apple: Transitioning to ARC Release Notes
       • Apple: Xcode New Features User Guide: Automatic Reference Counting
       • Mike Ash: Friday Q&A about Automatic Reference Counting
       • StackOverflow: How does automatic reference counting work?
       • StackOverflow: What are the advantages and disadvantages of using ARC?
       • StackOverflow: What is the difference between ARC and garbage collection?
       • informIT: Automatic Reference Counting in Objective-C, Part 1
       • informIT: Automatic Reference Counting in Objective-C, Part 2 The Details
       • Mike Ash: Zeroing weak references without ARC
       • Github: Support for zeroing weak references on iOS 4 / OS X 10.6
       • Assembler - A look under ARC’s hood
       • MKBlog - Migrating your code to Objective-C ARC
       • Ray Wenderlich - Beginning ARC in iOS 5 Tutorial



113
ARC Reference: videos



      • WWDC 2011 – Session 322 – Introduction to Automatic Reference Counting
      • WWDC 2011 – Session 322 – Objective-C Advancements in depth
      • WWDC 2011 – Session 308 – Blocks and Grand Central Dispatch in Practice


      • NSScreenCasts Episode 9 - Automatic Reference Counting




114
ARC Reference: books




      • Pro Multithreading and Memory Management for iOS and OS X with ARC,
        Grand Central Dispatch, and Blocks – By Kazuki Sakamoto, Apress
      • Programming iOS 5: Fundamentals of iPhone, iPad, and iPod touch Development
        Second Edition – By Matt Neuburg, O’Reilly




115
Sorry !?


      Automatic Reference Counting Specifications

116
Questions ?


       giuseppe.arici@gmail.com

117
Thanks !


      giuseppearici.com   pragmamark.org

118

Weitere ähnliche Inhalte

Was ist angesagt?

Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
rahulrevo
 

Was ist angesagt? (15)

Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Do we need Unsafe in Java?
Do we need Unsafe in Java?Do we need Unsafe in Java?
Do we need Unsafe in Java?
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
Message in a bottle
Message in a bottleMessage in a bottle
Message in a bottle
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
 
Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole
 
Home Automation with Android Things and the Google Assistant
Home Automation with Android Things and the Google AssistantHome Automation with Android Things and the Google Assistant
Home Automation with Android Things and the Google Assistant
 
Introduction to Debuggers
Introduction to DebuggersIntroduction to Debuggers
Introduction to Debuggers
 
오브젝트C(pdf)
오브젝트C(pdf)오브젝트C(pdf)
오브젝트C(pdf)
 
JavaScript on the GPU
JavaScript on the GPUJavaScript on the GPU
JavaScript on the GPU
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXL
 

Andere mochten auch

Property and MM with ARC in Objective-C
Property and MM with ARC in Objective-CProperty and MM with ARC in Objective-C
Property and MM with ARC in Objective-C
Yo Yo Chen
 
Memory Management In Swift
Memory Management In SwiftMemory Management In Swift
Memory Management In Swift
Hossam Ghareeb
 

Andere mochten auch (16)

A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Property and MM with ARC in Objective-C
Property and MM with ARC in Objective-CProperty and MM with ARC in Objective-C
Property and MM with ARC in Objective-C
 
Memory Management In Swift
Memory Management In SwiftMemory Management In Swift
Memory Management In Swift
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
GDB Mobile
GDB MobileGDB Mobile
GDB Mobile
 
Digital Universitas
Digital UniversitasDigital Universitas
Digital Universitas
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Objective-C @ ITIS
Objective-C @ ITISObjective-C @ ITIS
Objective-C @ ITIS
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
 
Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013Auto Layout Under Control @ Pragma conference 2013
Auto Layout Under Control @ Pragma conference 2013
 
iOS Memory Management
iOS Memory ManagementiOS Memory Management
iOS Memory Management
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Objective-C
Objective-CObjective-C
Objective-C
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Ähnlich wie Automatic Reference Counting

exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
tutorialsruby
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
tutorialsruby
 
Objective-C: a gentle introduction
Objective-C: a gentle introductionObjective-C: a gentle introduction
Objective-C: a gentle introduction
Gabriele Petronella
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
Mohammad Shaker
 
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
 

Ähnlich wie Automatic Reference Counting (20)

2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
 
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java Applications
 
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one
 
What Can Reverse Engineering Do For You?
What Can Reverse Engineering Do For You?What Can Reverse Engineering Do For You?
What Can Reverse Engineering Do For You?
 
iPhone dev intro
iPhone dev introiPhone dev intro
iPhone dev intro
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone development
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic library
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
 
Objective-C: a gentle introduction
Objective-C: a gentle introductionObjective-C: a gentle introduction
Objective-C: a gentle introduction
 
iOS 5 & Xcode 4: ARC, Stroryboards
iOS 5 & Xcode 4: ARC, StroryboardsiOS 5 & Xcode 4: ARC, Stroryboards
iOS 5 & Xcode 4: ARC, Stroryboards
 
Power of linked list
Power of linked listPower of linked list
Power of linked list
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Bee Smalltalk RunTime: anchor's aweigh
Bee Smalltalk RunTime: anchor's aweighBee Smalltalk RunTime: anchor's aweigh
Bee Smalltalk RunTime: anchor's aweigh
 
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
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Automatic Reference Counting

  • 1. Automatic Reference Counting Giuseppe Arici - @giuseppearici Superpartes Innovation Campus MOBILE DEVELOPER CONFERENCE 24 – 25 MAGGIO 2012 1
  • 2. Giuseppe ARiCi  Apple iOS & Mac OS X Addicted Developer Superpartes Innovation Campus & H-Farm  Group Founder & Cocoa Preacher m # Pragma Mark ― pragmamark.org co pe y ;) ci. sep bo ari giu Fan  A Social & Lazy Connected Node → ot a [ tt | in | fb | * ] / giuseppe.arici ard n I'm  Mail Forwarder & Spammer vC giuseppe.arici@gmail.com 2
  • 4. Attenzione: è un medicinale, leggere attentamente il foglio illustrativo. Consultare il medico se il disturbo si presenta ripetutamente. I medicinali vanno assunti con cautela, per un breve periodo di tempo, non superando le dosi consigliate e solo per le indicazioni riportate nel foglio illustrativo. In caso di dubbio rivolgersi al medico o al farmacista. Tenere il medicinale fuori dalla portata e dalla vista dei bambini. Da usare solo in età adulta. 4
  • 5. OS X & iOS 5
  • 6. Session Timeline • Da dove nasce ? • Che cos’è ? ARC • Come funziona ? • Quando utilizzarlo ? 6
  • 7. Memory Management 100 UIImage <0x12345678> @”Hello WhyMCA !” NSData <0a1b2c3d4e...> UIVIew Backing Store 7
  • 8. Memory Management 100 UIImage <0x12345678> UIVIew Backing Store 8
  • 9. malloc / free UIImage <0x12345678> UIVIew Backing Store 9
  • 10. Manual Reference Counting UIImage <0x12345678> 1 UIVIew Backing Store 3 10
  • 11. Manual Reference Counting UIImage <0x12345678> 1 UIVIew Backing Store 2 11
  • 12. Manual Reference Counting 0 UIVIew Backing Store 2 12
  • 14. Garbage Collection 200 Generation 1 Generation 2 Generation 3 14
  • 18. Garbage Collection 300 Heap Compaction 18
  • 19. Garbage Collection 400 High Performance Concurrent Garbage Collector 19
  • 20. Garbage Collection 400 X read barrier 20
  • 21. C GC vs 21
  • 22. Puntatori che giocano a Nascondino 22
  • 23. Apple l’ha fatto comunque ! 23
  • 24. Limiti del GC Objective-C 24
  • 25. Limiti del GC Objective-C NSData *data = [obj someData]; const char *bytes = [data bytes]; NSUInteger length = [data length]; for (NSUInteger i = 0; i < length; ++i) { printf(“%x”, bytes[i]); } 25
  • 26. Limiti del GC Objective-C 26
  • 27. Limiti del GC Objective-C 27
  • 28. iPhone GC vs 28
  • 29. iPhone Android vs 29
  • 30. 30
  • 31. Automatic Reference Counting “Automatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler. By enabling ARC with the new Apple LLVM compiler, you will never need to type retain or release again, dramatically simplifying the development process, while reducing crashes and memory leaks. The compiler has a complete understanding of your objects, and releases each object the instant it is no longer used, so apps run as fast as ever, with predictable, smooth performance.” (Apple, “iOS 5 for developers” – http://developer.apple.com/technologies/ios5) 31
  • 33. Analysis + Auto-Fix + Goodies 33
  • 34. Requisiti di Sistema • iOS 5 • OS X 10.7 • iOS 4 - no runtime ! • OS X 10.6 (64-bit) - no runtime ! 34
  • 35. Requisiti di Runtime • Clang (LLVM compiler) 3.0 or later • Obj-C Runtime: objc4 493.9 or later • For iOS4 or OS X 10.6: libarclite_iphoneos.a or libarclite_macosx.a is linked to make ARC work 35
  • 38. Conversione ad ARC NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // code here [pool release]; @autoreleasepool { // code here } NSString *s = [(id)CFStringCreateWithX(…) autorelease]; NSString *s = CFBridgingRelease(CFStringCreateWithX(…)); 38
  • 39. Conversione Automatica From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments. 39
  • 41. Nessuno è perfetto ! Eccezioni Toll-Free Bridging Strani Autorelease Pools Singleton Structs { case } Giochetti con i Puntatori Blocks 41
  • 43. Come Funziona ARC ARC è costituito da due componenti principali: • ARC front end compiler • ARC optimizer. 43
  • 44. ARC front end compiler • Inserisce le release correttamente • ivar (strong): inserisce le release nel dealloc • Nel dealloc chiama il [super dealloc] • Genera errori sui qualificatori inconsistenti 44
  • 45. ARC optimizer • Rimuove le retain e le release superflue • Ottimizza le prestazioni, minimizzando le sequenza multiple di retain e [auto]release 45
  • 46. Come Funziona ARC Foo *obj = [[Foo alloc] init]; [foo bar]; 46
  • 47. Come Funziona ARC Foo *obj = [[Foo alloc] init]; [foo bar]; [foo release]; 47
  • 48. Come Funziona ARC Foo *obj = [[Foo alloc] init]; [foo bar]; objc_release(foo); 48
  • 49. Come Funziona ARC retain retain release release release retain retain retain retain release release release retain retain release release retain release 49
  • 50. Come Funziona ARC Foo *obj = [self foo]; [foo bar]; [self setFoo: newFoo]; [foo baz]; 50
  • 51. Come Funziona ARC Foo *obj = objc_retain([self foo]); [foo bar]; [self setFoo: newFoo]; [foo baz]; objc_release(foo); 51
  • 52. Come Funziona ARC - (Foo *) foo { return _foo; } 52
  • 53. Come Funziona ARC - (Foo *) foo { return [[_foo retain] autorelease]; } 53
  • 54. Come Funziona ARC - (Foo *) foo { return objc_retainAutoreleaseReturnValue(_foo); } 54
  • 55. Come Funziona ARC retain autorelease retain release 55
  • 56. Come Funziona ARC retain autorelease retain release 56
  • 57. Come Funziona ARC objc_retainAutoreleaseReturnValue metodo chiamato Autorelease Pool metodo chiamante objc_retainAutorelease dReturnValue 57
  • 58. Come Funziona ARC retain release 58
  • 61. zeroing weak references Riferimento “debole” non sicuro nil X release Riferimento __weak X nil 61
  • 63. Memory Management Rules • You have ownership of any objects you create. • You can take ownership of an object using retain. • When no longer needed, you must relinquish ownership of an object you own. • You must not relinquish ownership of an object you don’t own. 63
  • 64. Memory Management Rules Azione su oggetto Objective-C Metodo Objective-C Create and have ownership of it alloc/new/copy/mutableCopy Take ownership of it retain Relinquish it release Dispose of it dealloc 64
  • 65. Qualificatori di Ownership In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership: • __strong (default) • __weak • __unsafe_unretained • __autoreleasing 65
  • 66. __strong /* ARC */ id obj = [[NSObject alloc] init]; { //id __strong obj = [[NSObject alloc] init]; id __strong obj = [[NSObject alloc] init]; id obj = [[NSObject alloc] init]; } /* non-ARC */ { id obj = [[NSObject alloc] init]; [obj release]; } • Default for ‘id’ and object types ! 66
  • 67. __weak { id __strong obj0 = [[NSObject alloc] init]; id __weak obj1 = obj0; } • No ownership of the object • When discarded, the variable is assigned to nil • In OS X, not all classes support weak 67
  • 68. __unsafe_unretained id __unsafe_unretained obj = [[NSObject alloc] init]; warning: assigning retained obj to unsafe_unretained variable; obj will be released after assignment [-Warc-unsafe-retained-assign] • UNSAFE • __weak only for iOS5 / OSX Lion (or later). • You must take care of the variables manually 68
  • 69. __autoreleasing @autoreleasepool { id __strong obj = [NSMutableArray array]; } - (BOOL) performOperationWithError:(NSError **)error; - (BOOL) performOperationWithError:(NSError * __autoreleasing *)error; • Pointer to ‘id’ or object types is qualified with __autoreleasing as default 69
  • 70. Initialization id __strong obj0; id __weak obj1; id __autoreleasing obj2; id __strong obj0 = nil; id __weak obj1 = nil; id __autoreleasing obj2 = nil; Any variables that are qualified with __strong, __weak, and __autoreleasing, are initialized with nil. 70
  • 71. Coding With ARC Rules • Che cosa è vietato fare • Che cosa è obbligatorio fare • Che cosa si può fare, con attenzione ! 71
  • 72. Rule 1 1. Forget about using retain, release, retainCount, and autorelease [obj release]; error: ARC forbids explicit message send of 'release' [obj release]; 72
  • 73. Rule 2 2. Forget about using NSAllocateObject and NSDeallocateObject NSAllocateObject (Class c, NSUInteger extraBytes, NSZone *zone) error: 'NSAllocateObject' is unavailable: not available in automatic reference counting mode 73
  • 74. Rule 3 3. Follow the naming rule for methods related to object creation • if begins { alloc, new, copy, mutableCopy }, the caller has ownership • if begins { init }: - (id) init ... • instance method • return ‘id’ or types of [super|sub]class • not registered in autoreleasepool: the caller has ownership • special case: “initialize” 74
  • 75. Rule 3 (Positive False) -(NSString*) copyRightString; -(NSString*) copyRightString NS_RETURNS_NON_RETAINED; • NS_RETURNS_NON_RETAINED • NS_RETURNS_RETAINED 75
  • 76. Rule 4 4. Forget about calling super dealloc explicitly - (void) dealloc { free(buffer); [super dealloc]; } error: ARC forbids explicit message send of 'dealloc' [super dealloc]; not available in automatic reference counting mode 76
  • 77. Rule 5 5. Use @autoreleasepool Instead of NSAutoreleasePool NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; ... [pool drain]; error: 'NSAutoreleasePool' is unavailable: not available in automatic reference counting mode NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; ^ 77
  • 78. Rule 6 6. Forget About Using Zone (NSZone) • If __OBJC2__ is defined, the runtime just ignores zones 78
  • 79. Rule 7 7. Object Type Variables Cannot Be Members of struct or union in C struct Data { NSMutableArray *array; }; error: ARC forbids Objective-C objs in structs or unions NSMutableArray *array; 79
  • 80. Rule 8 8. 'id' and 'void *' Have to Be Cast Explicitly id obj = [[NSObject alloc] init]; void *p = obj; error: implicit conversion of a non-Objective-C pointer type 'void *' to 'id' is disallowed with ARC Special kind of casts: • (__bridge cast) • (__bridge_retained cast) • (__bridge_transfer cast) 80
  • 81. Rule 8 (__bridge cast) id obj = [[NSObject alloc] init]; void *p = (__bridge void *)obj; id o = (__bridge id)p; 81
  • 82. Rule 8 (__bridge_retained cast) /* ARC */ id obj = [[NSObject alloc] init]; void *p = (__bridge_retained void *)obj; /* non-ARC */ id obj = [[NSObject alloc] init]; void *p = obj; [(id)p retain]; 82
  • 83. Rule 8 (__bridge_transfer cast) /* ARC */ id obj = (__bridge_transfer id)p; /* non-ARC */ id obj = (id)p; [obj retain]; [(id)p release]; 83
  • 84. Rule 8 (Toll-Free Bridging) CFTypeRef CFBridgingRetain(id X) { return (__bridge_retained CFTypeRef)X; } id CFBridgingRelease(CFTypeRef X) { return (__bridge_transfer id)X; } • Convert an object between Obj-C and Core Foundation. 84
  • 85. Rule 8 (Toll-Free Bridging) (__bridge cast) passaggio diretto del blocco puntato nessun trasferimento di ownership CFBridgingRetain() trasferimento di ownership da ARC a Core Foundation CFBridgingRelease() trasferimento di ownership da Core Foundation ad ARC 85
  • 86. Rule 9 9. Switch cases must be wrapped in scope with { } switch (someInt) { case 0: { NSLog(@"Case 0"); } break; } 86
  • 87. Rule 10 10.Exceptions use must be exceptional • For performance purpose, ARC code leaks on exceptions • In Obj-C ARC is not exception-safe for normal releases by default • -fobjc-arc-exceptions / -fno-objc-arc-exceptions: enable / disable • In Obj-C++ -fobjc-arc-exceptions is enabled by default 87
  • 88. Rule 11 11.IBOutlet must be declared as weak • Outlets should be defined as declared properties • Outlets should generally be weak • Top-level objects (or, in iOS, a storyboard scene) should be strong Resource Programming Guide 88
  • 89. Rule 12 12.Singletons should be redefined with dispatch_async static MyClass *sharedManager = nil; - (id)retain + (MyClass*)sharedManager { { return self; @synchronized(self) { } if (sharedManager == nil) { - (NSUInteger)retainCount sharedManager = { [[super allocWithZone:NULL] init]; return NSUIntegerMax; //cannot be released } } } - (oneway void)release return sharedManager; { } //do nothing + (id)allocWithZone:(NSZone *)zone } { - (id)autorelease return [[self sharedManager] retain]; { } return self; - (id)copyWithZone:(NSZone *)zone } { return self; } Resource Programming Guide 89
  • 90. Rule 12 (new singleton) + (id)sharedInstance { static dispatch_once_t predicate; dispatch_once(&predicate, ^{ sharedInstance = [[MyClass alloc] init]; }); return sharedInstance; } Single threaded results Multi threaded results ----------------------- ----------------------- @synchronized: 3.3829 seconds @synchronized: 33.5171 seconds dispatch_once: 0.9891 seconds dispatch_once: 1.6648 seconds http://bjhomer.blogspot.it/2011/09/synchronized-vs-dispatchonce.html 90
  • 91. Rule 13 13.Be careful with performSelector #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self performSelector:self.mySel]; #pragma clang diagnostic pop 91
  • 92. Constructs With ARC • Property • Array • Block 92
  • 93. Property Property modifier Ownership qualifier assign __unsafe_unretained copy __strong (note: new copied object is assigned) retain __strong strong __strong unsafe_unretained __unsafe_unretained weak __weak 93
  • 94. Property • Same ownership rules as variables • copy: copies the object by using copyWithZone • manually declared ivar has to have the same ownership qualifier as the property 94
  • 95. Property @property (nonatomic, readonly) MyObj* obj; @synthesize obj; error: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute • ARC forbids synthesizing a readonly property without specifying an ownership qualifier 95
  • 96. Array id objs0[10]; id __weak objs1[20]; NSMutableArray *objs2 = [NSMutableArray alloc] init]; • 'C' static arrays qualified with {__strong, __weak, __autoreleasing} are initialized with nil • For dynamic arrays, should be used containers in the Foundation Framework 96
  • 97. Block void (^block)(void) = ^{ [self doSomethingImportant]; }; ivar = block; // ARC inserts [block copy] 97
  • 98. Block return ^{ [self doSomethingGreat]; }; 98
  • 99. Block [array addObject: ^{ … }]; - (id)method { return ^{ … }; } 99
  • 100. Block [[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy] 100
  • 101. Block __block variable in MRC: mutable & “debole” in ARC: mutable & strong ! __weak variable 101
  • 102. Block & Riferimenti Ciclici i MyObj { id ivar; void (^block)(void); } ^{ [self something]; [ivar something]; }; 102
  • 103. Block & Riferimenti Ciclici __weak MyClass *weakSelf = self; ^{ [weakSelf something]; }; 103
  • 104. Block & Riferimenti Ciclici __weak MyClass *weakSelf = self; ^{ if (weakSelf) { [weakSelf->ivar something]; } }; 104
  • 105. Block & Riferimenti Ciclici __weak MyClass *weakSelf = self; ^{ if (weakSelf) { nil !? [weakSelf->ivar something]; } }; 105
  • 106. Block & Riferimenti Ciclici __weak MyClass *weakSelf = self; ^{ MyClass *localSelf = weakSelf; if (localSelf) { [localSelf->ivar something]; } }; 106
  • 107. ARC MACRO // define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42) #ifndef __has_feature #define __has_feature(x) 0 #endif #ifndef __has_extension #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif #if __has_feature(objc_arc) && __clang_major__ >= 3 #define ARC_ENABLED 1 #endif // __has_feature(objc_arc) Check @ compile-time if ARC is enabled 107
  • 108. Conclusioni • La Garbage collection é una gran bella idea ! • L'Objective-C è un gran bel linguaggio ! MA • L'Objective-C + La Garbage Collection non sono una gran bella accoppiata ! 108
  • 109. Conclusioni ARC non è la Garbage Collection … anche se ci arriva vicino ;) 109
  • 110. Conclusioni • Le zeroing weak references sono indispensabili ! • Utilizziamo __weak per evitare i riferimenti ciclici ! • Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak ! • Utilizziamo Instruments Leaks per individuare i riferimenti ciclici ! 110
  • 111. Conclusioni • ARC sa gestire soltanto gli oggetti Objective-C ! • Utilizziamo sempre __bridge, CFBridgingRetain, CFBridgingRelease per interagire con Core Foundation ! 111
  • 112. Conclusioni • ARC è una figata ! • Iniziamo subito ad usarlo ! • Convertiamo il nostro codice ! • Risparmiamo tempo ! • Risparmiamo denaro ! • Viviamo meglio ! 112
  • 113. ARC Reference: documentation and articles Clang: Automatic Reference Counting documentation • Apple: Transitioning to ARC Release Notes • Apple: Xcode New Features User Guide: Automatic Reference Counting • Mike Ash: Friday Q&A about Automatic Reference Counting • StackOverflow: How does automatic reference counting work? • StackOverflow: What are the advantages and disadvantages of using ARC? • StackOverflow: What is the difference between ARC and garbage collection? • informIT: Automatic Reference Counting in Objective-C, Part 1 • informIT: Automatic Reference Counting in Objective-C, Part 2 The Details • Mike Ash: Zeroing weak references without ARC • Github: Support for zeroing weak references on iOS 4 / OS X 10.6 • Assembler - A look under ARC’s hood • MKBlog - Migrating your code to Objective-C ARC • Ray Wenderlich - Beginning ARC in iOS 5 Tutorial 113
  • 114. ARC Reference: videos • WWDC 2011 – Session 322 – Introduction to Automatic Reference Counting • WWDC 2011 – Session 322 – Objective-C Advancements in depth • WWDC 2011 – Session 308 – Blocks and Grand Central Dispatch in Practice • NSScreenCasts Episode 9 - Automatic Reference Counting 114
  • 115. ARC Reference: books • Pro Multithreading and Memory Management for iOS and OS X with ARC, Grand Central Dispatch, and Blocks – By Kazuki Sakamoto, Apress • Programming iOS 5: Fundamentals of iPhone, iPad, and iPod touch Development Second Edition – By Matt Neuburg, O’Reilly 115
  • 116. Sorry !? Automatic Reference Counting Specifications 116
  • 117. Questions ? giuseppe.arici@gmail.com 117
  • 118. Thanks ! giuseppearici.com pragmamark.org 118