SlideShare a Scribd company logo
1 of 39
Download to read offline
CocoaHeads Rennes #9
                                                Thomas Dupont
    12 avril 2012




               Gestion Mémoire
                       du débutant à l’expert
Sommaire




• Gestion mémoire
• Compteur de références
• Properties
• Blocks
• ARC
•Gestion mémoire




 7
 6
 5
 4                 sp   co   if (b) {
 3                               int y = 3;
 2                           }
 1
 0

          stack
•Gestion mémoire




 7
 6     adresse de retour : 4   sp
 5          variable y
 4                                  co   if (b) {
 3                                           int y = 3;
 2                                       }
 1
 0

             stack
•Gestion mémoire




                   malloc


                    free



           heap
Compteur de références



          NSObject


                         retain

                         release


          2
          1
          0
Compteur de références

      ‣ Vous êtes responsable des objets que vous créez
      ‣ Vous pouvez devenir responsable d’un objet avec retain
      ‣ Vous devez relâcher un objet dont vous êtes responsable
                                                                  C

métaphore du chien
                                        2
                                        1
                                        0
                                        3

                                            chien

                      A                                           B
Compteur de références

                        + (MyObject*)fetchMyObject;

 MyObject* obj = [MyObject fetchMyObject];




+ (id)alloc
- (id)init
+ (id)new                                Conventions de nommage
- (id)copy
- (id)mutableCopy
Compteur de références


                          autorelease



run loop                                 autoreleasepool
                           1
                           0
                                        obj
                               obj
Properties



@property (attributes) NSObject* myObj;
@synthesize myObj;


                   getter=
                   setter=                assign
                   nonatomic              retain
                   readonly               copy
                   readwrite
Blocks




  dispatch_block_t myBlock = ^{ myView.alpha = 0; } ;

  [UIView animateWithDuration:0.5 animations: myBlock ];
Blocks




         __block int a = 3;

         void (^incrementA)(void) = ^{ a++; };

         incrementA();
Blocks




         __block NSObject* myObj;

         void (^foo)(void) = ^{ [myObj foo]; };

         foo();
Blocks



MyClass.h
 MyObject* myObj;
 int myIvar;



MyClass.m

 void (^foo)(void) = ^{
    myIvar++;
    [myObj foo];
 };
  foo();
Blocks

                                                      myObj
MyClass.h
 MyObject* myObj;
 int myIvar;

                                               self           block

MyClass.m


  myObj = [[MyObject alloc] initWithBlock:^{
      NSLog(@"%i", myIvar);
  }];
Blocks

                                                      myObj
MyClass.h
 MyObject* myObj;
 int myIvar;

                                               self           block

MyClass.m
  __block MyClass* weakSelf = self;
  myObj = [[MyObject alloc] initWithBlock:^{
      NSLog(@"%i", weakSelf-> myIvar);
  }];
Blocks




dispatch_block_t block;    int* pInt;

if ( ... ) {               if ( ... ) {
                                 int a = 1;
      block = ^{ ... } ;
                                 pInt = &a;
} else {                   } else {
                                  int b = 1;
      block = ^{ ... } ;          pInt = &b;
}                          }

block();                   // utilisation de pInt
Blocks




dispatch_block_t block;

if ( ... ) {
      block = [ [^{ ... } copy]   autorelease] ;
} else {

      block = [ [^{ ... } copy]   autorelease] ;
}

block();
ARC
@implementation Stack { NSMutableArray *array; }
- (id) init {
   if (self = [super init])
      array = [NSMutableArray array] ;
   return self;
}
- (void) push: (id) x {
   [array addObject: x];
}
- (id) pop {
   id x = [array lastObject] ;
            [
   [array removeLastObject];
   return [ ;
}
@end
ARC
@implementation Stack { NSMutableArray *array; }
- (id) init {
   if (self = [super init])
      array = [ [NSMutableArray array] retain] ;
   return self;
}
- (void) push: (id) x {
   [array addObject: x];
}
- (id) pop {
   id x = [ [array lastObject] retain] ;
   [array removeLastObject];
   return [ x autorelease] ;
}
- (void) dealloc { [array release]; [super dealloc]; }
@end
ARC



                          It just works !



      Insertion automatique de retain, release et autorelease



              Oublier la notion de retain et release
                   Penser au graphe d’objets
ARC

                                          __strong

                       valeur par défaut

                                                 devient responsable


- (id) pop {
   __strong id result = objc_retain ( [array lastObject] ) ;
   [array removeLastObject] ;
   return objc_autorelease ( result )
                ;
}
ARC

                              __unsafe_unretained

           ne devient pas responsable


                                        utilisé pour éviter les deadlocks


- (void) dealloc {
   [myTableView setDelegate:nil];
   [myTableView setDataSource:nil];
}
ARC

                                    __weak

                                             ne devient pas responsable

  utilisé pour éviter les deadlocks

                                    remis à nil dès que l’objet est détruit
- (void) testWeak {
   id newObject = [NSObject new];
   __weak id value = newObject;
   newObject = nil;
   assert(value == nil);
}                             !      disponible que depuis iOS 5.0 et OS X 10.7
ARC




@property (strong) id x;              // __strong ,              a.k.a retain

@property (unsafe_unretained) id y;   // __unsafe_unretained ,   a.k.a assign

@property (weak) id z;                // __weak
ARC




      blocks
ARC




dispatch_block_t block;

if ( ... ) {
      block = ^{ ... } ;
} else {
      block = ^{ ... } ;
}

block();
ARC



MyClass.h
 MyObject* myObj;
 int myIvar;



MyClass.m
  __block __unsafe_unretained MyClass* weakSelf = self;
  myObj = [[MyObject alloc] initWithBlock:^{
      NSLog(@"%i", weakSelf->myIvar);
  }];
ARC



MyClass.h
 MyObject* myObj;
 int myIvar;



MyClass.m
  __weak MyClass* weakSelf = self;
  myObj = [[MyObject alloc] initWithBlock:^{
      MyObject* strongSelf = weakSelf
      if (strongSelf)
          NSLog(@"%i", strongSelf-> myIvar);
  }];
ARC




      Core Foundation
ARC




NSString* myNSString = ( __bridge NSString*) myCFString;


NSDictionary* dict = ( __bridge_transfer NSDictionary*) CFDictionaryCreate(...);


CFArrayRef aray = ( __bridge_retained CFArrayRef) [[NSArray alloc] init];
ARC




      Project configuration
ARC
ARC




      -fobjc-arc   -fno-objc-arc
ARC



- (NSString*) copyRightLicense {
    return license;                              Non-ARC compiled
}




- (void) checkLicense {
     NSString* l = [license copyRightLicense];     ARC compiled
     ...
     objc_release ( l );
}
ARC



+ (License*) createLicense {
    return [[self alloc] init];                                    Non-ARC compiled
}




- (void) checkLicense {
     __strong License* l = objc_retain ( [License createLicense] ) ;   ARC compiled
     ...
     objc_release ( l );
}
ARC




- (NSString*) copyRightLicense   NS_RETURNS_NOT_RETAINED ;



+ (License*) createLicense       NS_RETURNS_RETAINED ;
CocoaHeads Rennes #9           julien@cocoaheads.fr
    12 avril 2012              thomas.dupont@cocoaheads.fr




                       Merci
ARC
pour ou contre ?

More Related Content

What's hot

2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing
MongoDB
 
PHP5 - POO
PHP5 - POOPHP5 - POO
PHP5 - POO
mazenovi
 

What's hot (15)

Jquery - introduction au langage
Jquery - introduction au langageJquery - introduction au langage
Jquery - introduction au langage
 
Procédures CLR pour SQL Server : avantages et inconvénients
Procédures CLR pour SQL Server : avantages et inconvénientsProcédures CLR pour SQL Server : avantages et inconvénients
Procédures CLR pour SQL Server : avantages et inconvénients
 
2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing
 
php2 : formulaire-session-PDO
php2 : formulaire-session-PDOphp2 : formulaire-session-PDO
php2 : formulaire-session-PDO
 
Cappuccino - ou comment créer une application web en 5 minutes
Cappuccino - ou comment créer une application web en 5 minutes Cappuccino - ou comment créer une application web en 5 minutes
Cappuccino - ou comment créer une application web en 5 minutes
 
CocoaHeads Rennes #1 : Grand Central Dispatch
CocoaHeads Rennes #1 : Grand Central DispatchCocoaHeads Rennes #1 : Grand Central Dispatch
CocoaHeads Rennes #1 : Grand Central Dispatch
 
Introduction à React JS
Introduction à React JSIntroduction à React JS
Introduction à React JS
 
2014.12.11 - TECH CONF #3 - Présentation Bootstrap
2014.12.11 - TECH CONF #3 - Présentation Bootstrap2014.12.11 - TECH CONF #3 - Présentation Bootstrap
2014.12.11 - TECH CONF #3 - Présentation Bootstrap
 
Cours JavaScript
Cours JavaScriptCours JavaScript
Cours JavaScript
 
Présentation jQuery pour débutant
Présentation jQuery pour débutantPrésentation jQuery pour débutant
Présentation jQuery pour débutant
 
Javascript : fondamentaux et OOP
Javascript : fondamentaux et OOPJavascript : fondamentaux et OOP
Javascript : fondamentaux et OOP
 
PHP5 - POO
PHP5 - POOPHP5 - POO
PHP5 - POO
 
Cours php & Mysql - 2éme partie
Cours php & Mysql - 2éme partieCours php & Mysql - 2éme partie
Cours php & Mysql - 2éme partie
 
Introduction à React
Introduction à ReactIntroduction à React
Introduction à React
 
Programmation Orientée Objet et les Traits en PHP 5.4
Programmation Orientée Objet et les Traits en PHP 5.4Programmation Orientée Objet et les Traits en PHP 5.4
Programmation Orientée Objet et les Traits en PHP 5.4
 

Viewers also liked

CocoaHeads Rennes #4 : la rotation sur iOS
CocoaHeads Rennes #4 : la rotation sur iOSCocoaHeads Rennes #4 : la rotation sur iOS
CocoaHeads Rennes #4 : la rotation sur iOS
CocoaHeadsRNS
 

Viewers also liked (6)

CocoaHeads Rennes #4 : la rotation sur iOS
CocoaHeads Rennes #4 : la rotation sur iOSCocoaHeads Rennes #4 : la rotation sur iOS
CocoaHeads Rennes #4 : la rotation sur iOS
 
CocoaHeads Rennes #2 : Xcode 4
CocoaHeads Rennes #2 : Xcode 4CocoaHeads Rennes #2 : Xcode 4
CocoaHeads Rennes #2 : Xcode 4
 
CocoaHeads Rennes #10 : Mock Objects
CocoaHeads Rennes #10 : Mock ObjectsCocoaHeads Rennes #10 : Mock Objects
CocoaHeads Rennes #10 : Mock Objects
 
CocoaHeads Rennes #10 : Notifications
CocoaHeads Rennes #10 : NotificationsCocoaHeads Rennes #10 : Notifications
CocoaHeads Rennes #10 : Notifications
 
CocoaHeads Rennes #14: Programmation Responsive par Celedev
CocoaHeads Rennes #14: Programmation Responsive par CeledevCocoaHeads Rennes #14: Programmation Responsive par Celedev
CocoaHeads Rennes #14: Programmation Responsive par Celedev
 
CocoaHeads Rennes #16: OHHTTPStubs
CocoaHeads Rennes #16: OHHTTPStubsCocoaHeads Rennes #16: OHHTTPStubs
CocoaHeads Rennes #16: OHHTTPStubs
 

Similar to CocoaHeads Rennes #9 : Gestion mémoire, du débutant à l'expert

Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++
Amel Morchdi
 
Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++
Amel Morchdi
 
Android Optimisations Greendroid
Android Optimisations GreendroidAndroid Optimisations Greendroid
Android Optimisations Greendroid
GDG Nantes
 
fdocuments.fr_chap-03-poo-en-java-partie1.pptx
fdocuments.fr_chap-03-poo-en-java-partie1.pptxfdocuments.fr_chap-03-poo-en-java-partie1.pptx
fdocuments.fr_chap-03-poo-en-java-partie1.pptx
TarikElMahtouchi1
 

Similar to CocoaHeads Rennes #9 : Gestion mémoire, du débutant à l'expert (16)

CocoaHeads Rennes #3 : Bien débuter sur iOS
CocoaHeads Rennes #3 : Bien débuter sur iOSCocoaHeads Rennes #3 : Bien débuter sur iOS
CocoaHeads Rennes #3 : Bien débuter sur iOS
 
Ce bon vieux propel
Ce bon vieux propelCe bon vieux propel
Ce bon vieux propel
 
Les nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ ModerneLes nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ Moderne
 
Introduction au Jquery
Introduction au JqueryIntroduction au Jquery
Introduction au Jquery
 
Part1
Part1Part1
Part1
 
POO-chapitre3.pptx
POO-chapitre3.pptxPOO-chapitre3.pptx
POO-chapitre3.pptx
 
Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++
 
Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++Chapitre 2 poo classe objet c++
Chapitre 2 poo classe objet c++
 
Introduction à jQuery
Introduction à jQueryIntroduction à jQuery
Introduction à jQuery
 
Android Optimisations Greendroid
Android Optimisations GreendroidAndroid Optimisations Greendroid
Android Optimisations Greendroid
 
Clonage d'objets
Clonage d'objetsClonage d'objets
Clonage d'objets
 
Programmation orientée objet : Object, classe et encapsulation
Programmation orientée objet : Object, classe et encapsulationProgrammation orientée objet : Object, classe et encapsulation
Programmation orientée objet : Object, classe et encapsulation
 
Csharp2 : classes et objets
Csharp2 : classes et objetsCsharp2 : classes et objets
Csharp2 : classes et objets
 
poo.pdf
poo.pdfpoo.pdf
poo.pdf
 
fdocuments.fr_chap-03-poo-en-java-partie1.pptx
fdocuments.fr_chap-03-poo-en-java-partie1.pptxfdocuments.fr_chap-03-poo-en-java-partie1.pptx
fdocuments.fr_chap-03-poo-en-java-partie1.pptx
 
programmation orienté objet c++
programmation orienté objet c++programmation orienté objet c++
programmation orienté objet c++
 

More from CocoaHeadsRNS

More from CocoaHeadsRNS (9)

CocoaHeads Rennes #14: iOS7 Controllers Transitions
 CocoaHeads Rennes #14: iOS7 Controllers Transitions CocoaHeads Rennes #14: iOS7 Controllers Transitions
CocoaHeads Rennes #14: iOS7 Controllers Transitions
 
CocoaHeads Rennes #13 : CocoaPods
CocoaHeads Rennes #13 : CocoaPodsCocoaHeads Rennes #13 : CocoaPods
CocoaHeads Rennes #13 : CocoaPods
 
CocoaHeads Rennes #7 : Intégration continue pour les nuls
CocoaHeads Rennes #7 : Intégration continue pour les nulsCocoaHeads Rennes #7 : Intégration continue pour les nuls
CocoaHeads Rennes #7 : Intégration continue pour les nuls
 
CocoaHeads Rennes #6
CocoaHeads Rennes #6CocoaHeads Rennes #6
CocoaHeads Rennes #6
 
CocoaHeads Rennes #5 : iOS & Android
CocoaHeads Rennes #5 : iOS & AndroidCocoaHeads Rennes #5 : iOS & Android
CocoaHeads Rennes #5 : iOS & Android
 
CocoaHeads Rennes #4 : Tests automatisés sur iOS
CocoaHeads Rennes #4 : Tests automatisés sur iOSCocoaHeads Rennes #4 : Tests automatisés sur iOS
CocoaHeads Rennes #4 : Tests automatisés sur iOS
 
Cocoaheads Rennes #3 : Bien coder sur iOS
Cocoaheads Rennes #3 : Bien coder sur iOSCocoaheads Rennes #3 : Bien coder sur iOS
Cocoaheads Rennes #3 : Bien coder sur iOS
 
CocoaHeads Rennes #2 : Pratiques de développement itératif
CocoaHeads Rennes #2 : Pratiques de développement itératifCocoaHeads Rennes #2 : Pratiques de développement itératif
CocoaHeads Rennes #2 : Pratiques de développement itératif
 
CocoaHeads Rennes #1 : internationalisation
CocoaHeads Rennes #1 : internationalisationCocoaHeads Rennes #1 : internationalisation
CocoaHeads Rennes #1 : internationalisation
 

CocoaHeads Rennes #9 : Gestion mémoire, du débutant à l'expert

  • 1. CocoaHeads Rennes #9 Thomas Dupont 12 avril 2012 Gestion Mémoire du débutant à l’expert
  • 2. Sommaire • Gestion mémoire • Compteur de références • Properties • Blocks • ARC
  • 3. •Gestion mémoire 7 6 5 4 sp co if (b) { 3 int y = 3; 2 } 1 0 stack
  • 4. •Gestion mémoire 7 6 adresse de retour : 4 sp 5 variable y 4 co if (b) { 3 int y = 3; 2 } 1 0 stack
  • 5. •Gestion mémoire malloc free heap
  • 6. Compteur de références NSObject retain release 2 1 0
  • 7. Compteur de références ‣ Vous êtes responsable des objets que vous créez ‣ Vous pouvez devenir responsable d’un objet avec retain ‣ Vous devez relâcher un objet dont vous êtes responsable C métaphore du chien 2 1 0 3 chien A B
  • 8. Compteur de références + (MyObject*)fetchMyObject; MyObject* obj = [MyObject fetchMyObject]; + (id)alloc - (id)init + (id)new Conventions de nommage - (id)copy - (id)mutableCopy
  • 9. Compteur de références autorelease run loop autoreleasepool 1 0 obj obj
  • 10. Properties @property (attributes) NSObject* myObj; @synthesize myObj; getter= setter= assign nonatomic retain readonly copy readwrite
  • 11. Blocks dispatch_block_t myBlock = ^{ myView.alpha = 0; } ; [UIView animateWithDuration:0.5 animations: myBlock ];
  • 12. Blocks __block int a = 3; void (^incrementA)(void) = ^{ a++; }; incrementA();
  • 13. Blocks __block NSObject* myObj; void (^foo)(void) = ^{ [myObj foo]; }; foo();
  • 14. Blocks MyClass.h MyObject* myObj; int myIvar; MyClass.m void (^foo)(void) = ^{ myIvar++; [myObj foo]; }; foo();
  • 15. Blocks myObj MyClass.h MyObject* myObj; int myIvar; self block MyClass.m myObj = [[MyObject alloc] initWithBlock:^{ NSLog(@"%i", myIvar); }];
  • 16. Blocks myObj MyClass.h MyObject* myObj; int myIvar; self block MyClass.m __block MyClass* weakSelf = self; myObj = [[MyObject alloc] initWithBlock:^{ NSLog(@"%i", weakSelf-> myIvar); }];
  • 17. Blocks dispatch_block_t block; int* pInt; if ( ... ) { if ( ... ) { int a = 1; block = ^{ ... } ; pInt = &a; } else { } else { int b = 1; block = ^{ ... } ; pInt = &b; } } block(); // utilisation de pInt
  • 18. Blocks dispatch_block_t block; if ( ... ) { block = [ [^{ ... } copy] autorelease] ; } else { block = [ [^{ ... } copy] autorelease] ; } block();
  • 19. ARC @implementation Stack { NSMutableArray *array; } - (id) init { if (self = [super init]) array = [NSMutableArray array] ; return self; } - (void) push: (id) x { [array addObject: x]; } - (id) pop { id x = [array lastObject] ; [ [array removeLastObject]; return [ ; } @end
  • 20. ARC @implementation Stack { NSMutableArray *array; } - (id) init { if (self = [super init]) array = [ [NSMutableArray array] retain] ; return self; } - (void) push: (id) x { [array addObject: x]; } - (id) pop { id x = [ [array lastObject] retain] ; [array removeLastObject]; return [ x autorelease] ; } - (void) dealloc { [array release]; [super dealloc]; } @end
  • 21. ARC It just works ! Insertion automatique de retain, release et autorelease Oublier la notion de retain et release Penser au graphe d’objets
  • 22. ARC __strong valeur par défaut devient responsable - (id) pop { __strong id result = objc_retain ( [array lastObject] ) ; [array removeLastObject] ; return objc_autorelease ( result ) ; }
  • 23. ARC __unsafe_unretained ne devient pas responsable utilisé pour éviter les deadlocks - (void) dealloc { [myTableView setDelegate:nil]; [myTableView setDataSource:nil]; }
  • 24. ARC __weak ne devient pas responsable utilisé pour éviter les deadlocks remis à nil dès que l’objet est détruit - (void) testWeak { id newObject = [NSObject new]; __weak id value = newObject; newObject = nil; assert(value == nil); } ! disponible que depuis iOS 5.0 et OS X 10.7
  • 25. ARC @property (strong) id x; // __strong , a.k.a retain @property (unsafe_unretained) id y; // __unsafe_unretained , a.k.a assign @property (weak) id z; // __weak
  • 26. ARC blocks
  • 27. ARC dispatch_block_t block; if ( ... ) { block = ^{ ... } ; } else { block = ^{ ... } ; } block();
  • 28. ARC MyClass.h MyObject* myObj; int myIvar; MyClass.m __block __unsafe_unretained MyClass* weakSelf = self; myObj = [[MyObject alloc] initWithBlock:^{ NSLog(@"%i", weakSelf->myIvar); }];
  • 29. ARC MyClass.h MyObject* myObj; int myIvar; MyClass.m __weak MyClass* weakSelf = self; myObj = [[MyObject alloc] initWithBlock:^{ MyObject* strongSelf = weakSelf if (strongSelf) NSLog(@"%i", strongSelf-> myIvar); }];
  • 30. ARC Core Foundation
  • 31. ARC NSString* myNSString = ( __bridge NSString*) myCFString; NSDictionary* dict = ( __bridge_transfer NSDictionary*) CFDictionaryCreate(...); CFArrayRef aray = ( __bridge_retained CFArrayRef) [[NSArray alloc] init];
  • 32. ARC Project configuration
  • 33. ARC
  • 34. ARC -fobjc-arc -fno-objc-arc
  • 35. ARC - (NSString*) copyRightLicense { return license; Non-ARC compiled } - (void) checkLicense { NSString* l = [license copyRightLicense]; ARC compiled ... objc_release ( l ); }
  • 36. ARC + (License*) createLicense { return [[self alloc] init]; Non-ARC compiled } - (void) checkLicense { __strong License* l = objc_retain ( [License createLicense] ) ; ARC compiled ... objc_release ( l ); }
  • 37. ARC - (NSString*) copyRightLicense NS_RETURNS_NOT_RETAINED ; + (License*) createLicense NS_RETURNS_RETAINED ;
  • 38. CocoaHeads Rennes #9 julien@cocoaheads.fr 12 avril 2012 thomas.dupont@cocoaheads.fr Merci