SlideShare une entreprise Scribd logo
1  sur  39
iOS &
Memory Management
            Basics
    Cameron Barrie - @whalec
iOS &
Memory Management
   Memory Management Programming Guide:
   https://developer.apple.com/iphone/library/
documentation/Cocoa/Conceptual/MemoryMgmt/
               MemoryMgmt.html
iOS Memory Management


   alloc/copy/retain/release/autorelease

  Program received signal: "EXC_BAD_ACCESS".
iOS Memory Management
iOS Memory Management
 ObjectiveC objects contain a ‘count’ of how many
  other objects are currently holding onto them.

 You increment that count with the retain message.
You decrement that count with the release message.

             When that count hits 0.
      The object is deallocated from memory
iOS Memory Management
Memory Management Rules:
iOS Memory Management
Memory Management Rules:
  1. You only release objects you own:
iOS Memory Management
Memory Management Rules:
  1. You only release objects you own:
  [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil]
iOS Memory Management
 Memory Management Rules:
     1. You only release objects you own:
     [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil]

NSArray *topLevelObjects = [[NSBundle mainBundle]
                             loadNibNamed:@"UPLeaderboardViewCell"
                             owner:nil options:nil];
NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];
iOS Memory Management
 Memory Management Rules:
     1. You only release objects you own:
     [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil]

NSArray *topLevelObjects = [[NSBundle mainBundle]
                             loadNibNamed:@"UPLeaderboardViewCell"
                             owner:nil options:nil];
NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];



     2. Or objects you take ownership of:
iOS Memory Management
 Memory Management Rules:
     1. You only release objects you own:
     [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil]

NSArray *topLevelObjects = [[NSBundle mainBundle]
                             loadNibNamed:@"UPLeaderboardViewCell"
                             owner:nil options:nil];
NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];



     2. Or objects you take ownership of:

                 [[UIFont fontWithName:@"HoboStd" size:25] retain]
iOS Memory Management
 Memory Management Rules:
     1. You only release objects you own:
     [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil]

NSArray *topLevelObjects = [[NSBundle mainBundle]
                             loadNibNamed:@"UPLeaderboardViewCell"
                             owner:nil options:nil];
NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];



     2. Or objects you take ownership of:

                 [[UIFont fontWithName:@"HoboStd" size:25] retain]




          Retaining an object simply increments an objects retainCount by 1.
iOS Memory Management
Releasing an object
  Release an object by sending it the release message
iOS Memory Management
 Releasing an object
     Release an object by sending it the release message

NSArray *topLevelObjects = [[NSBundle mainBundle]
                             loadNibNamed:@"UPLeaderboardViewCell"
                             owner:nil options:nil];
NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];

[mutableTopLevelObjects release];
iOS Memory Management
 Releasing an object
     Release an object by sending it the release message

NSArray *topLevelObjects = [[NSBundle mainBundle]
                             loadNibNamed:@"UPLeaderboardViewCell"
                             owner:nil options:nil];
NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];

[mutableTopLevelObjects release];




                Releasing an object doesn’t remove it from memory.
                It simply decrements the objects retainCount by 1.
                When an objects retainCount is equal to 0.
                The object is deallocated by the runtime automatically.
iOS Memory Management
 Releasing an object
     Release an object by sending it the release message

NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];
[topLevelObjects retainCount]; // => 1
[topLevelObjects retain];
[topLevelObjects retainCount]; // => 2
[mutableTopLevelObjects release];
[topLevelObjects retainCount]; // => 1

[topLevelObjects release];
[topLevelObjects retainCount]; // => 0




                Releasing an object doesn’t remove it from memory.
                It simply decrements the objects retainCount by 1.
                When an objects retainCount is equal to 0.
                The object is deallocated by the runtime automatically.
iOS Memory Management
So what about the other objects?
iOS Memory Management
So what about the other objects?
    They’re what’s known as autorelease objects.
iOS Memory Management
 So what about the other objects?
        They’re what’s known as autorelease objects.

// This object will be automatically released at some point
// in the future when the autorelease pool is drained
NSString *aString = [NSString stringWithFormat:@"a string with an int %i", 1];
iOS Memory Management
 So what about the other objects?
        They’re what’s known as autorelease objects.

// This object will be automatically released at some point
// in the future when the autorelease pool is drained
NSString *aString = [NSString stringWithFormat:@"a string with an int %i", 1];




        You can mark your own objects as autorelease objects
iOS Memory Management
 So what about the other objects?
        They’re what’s known as autorelease objects.

// This object will be automatically released at some point
// in the future when the autorelease pool is drained
NSString *aString = [NSString stringWithFormat:@"a string with an int %i", 1];




        You can mark your own objects as autorelease objects
[topLevelObjects retainCount]; // => 1
[topLevelObjects autorelease];
[topLevelObjects retainCount]; // => 1 since it will be released later
iOS Memory Management
NSAutoreleasePool
    “Cocoa always expects there to be an autorelease pool available”
      - Memory Management Programming Guide: Autorelease Pools

    // main.m
    // The main entry point into the app sets up
    // an autorelease pool for us automatically
    int main(int argc, char *argv[])
    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        int retVal = UIApplicationMain(argc, argv, nil, nil);
        [pool release];
        return retVal;
    }
iOS Memory Management
Common mistakes
iOS Memory Management
Common mistakes
    // You need to mark zero for autorelease or release it
    - (void)reset {
        NSNumber *zero = [[NSNumber alloc] initWithInteger:0];
        [self setCount:zero];
    }
iOS Memory Management
Common mistakes
    // You need to mark zero for autorelease or release it
    - (void)reset {
        NSNumber *zero = [[NSNumber alloc] initWithInteger:0];
        [self setCount:zero];
    }



    // zero is an autorelease object already.
    // you haven't used alloc/copy anywhere
    // you are over releasing the zero object
    - (void)reset {
        NSNumber *zero = [NSNumber numberWithInteger:0];
        [self setCount:zero];
        [zero release];
    }
iOS Memory Management
Common confusion
   // Adding an object to a collection retains the object
   // It transfers ownership to the parent collection
   // Since alloc/copy was never called you don’t need
   // to release convenienceNumber
   NSMutableArray *array = [[NSMutableArray alloc] init];
   NSUInteger i = 0;
   for (i; i < 10; i++) {
       NSNumber *convenienceNumber = [NSNumber numberWithInteger:i];
       [array addObject:convenienceNumber];
   }
iOS Memory Management
Common confusion
   // Adding an object to a collection retains the object
   // It transfers ownership to the parent collection
   // You need to release allocedNumber here since you alloced it.
   NSMutableArray *array = [[NSMutableArray alloc] init];
   NSUInteger i = 0;
   for (i; i < 10; i++) {
       NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger: i];
       [array addObject:allocedNumber];
       [allocedNumber release];
   }
iOS Memory Management
Returning Objects from Methods
iOS Memory Management
Returning Objects from Methods
 // Correct - You don't own the string object so you should return it as such.
 - (NSString *)fullName {
     NSString *string = [NSString stringWithFormat:@"%@ %@",
                          self.firstName, self.lastName];
     return string;
 }
iOS Memory Management
Returning Objects from Methods
 // Correct - You don't own the string object so you should return it as such.
 - (NSString *)fullName {
     NSString *string = [NSString stringWithFormat:@"%@ %@",
                          self.firstName, self.lastName];
     return string;
 }

 // Incorrect - You're returning an object that has already been released.
 - (NSString *)fullName {
     NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@",
                                           self.firstName, self.lastName]
                                           release];
     return string;
 }
iOS Memory Management
Returning Objects from Methods
 // Correct - You don't own the string object so you should return it as such.
 - (NSString *)fullName {
     NSString *string = [NSString stringWithFormat:@"%@ %@",
                          self.firstName, self.lastName];
     return string;
 }

 // Incorrect - You're returning an object that has already been released.
 - (NSString *)fullName {
     NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@",
                                           self.firstName, self.lastName]
                                           release];
     return string;
 }

 // Correct - You've created an autorelease object.
 - (NSString *)fullName {
     NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@",
                                           self.firstName, self.lastName]
                                           autorelease];
     return string;
 }
iOS Memory Management
Accessor Method - @property/@synthesize
iOS Memory Management
Accessor Method - @property/@synthesize
 // MyClass.h
 @property(nonatomic, readwrite, retain) NSString *myString
iOS Memory Management
Accessor Method - @property/@synthesize
 // MyClass.h
 @property(nonatomic, readwrite, retain) NSString *myString


 // MyClass.m
 @synthesize myString = _myString;
 -(id)init
 {
     if ((self = [super init]))
     {
         self.myString = @"A string to be retained";
     }
     return self;
 }

 -(void)dealloc
 {
     [_myString release], _myString = nil;

     [super dealloc];
 }
iOS Memory Management
Accessor Method - @property/@synthesize

 // MyClass.h
 // Will retain the variable sent to it.
 @property(nonatomic, readwrite, retain) NSString *myString;

 // Will not retain the variable sent to it.
 @property(nonatomic, readwrite, assign) NSString *myWeakString;
iOS Memory Management
Accessor Method - @property/@synthesize
 // MyClass.m
 // Will retain the variable sent to it.
 @synthesize myString = _myString;

 // The @synthesize produces a setter/getter combo(readwrite)
 -(NSString *)myString
 {
     return _myString;
 }

 -(void)setMyString:(NSString *)myString
 {
     if (myString != _myString)
      {
         [_myString release];
         _myString = [myString retain];
     }
 }
iOS Memory Management
Accessor Method - @property/@synthesize

 // MyClass.m
 // Will not retain the variable sent to it.
 @synthesize myWeakString = _myWeakString;

 // The @synthesize produces a setter/getter combo(readwrite)
 -(NSString *)myWeakString
 {
   return _myWeakString;
 }

 -(void)setMyWeakString:(NSString *)myWeakString
 {
   _myWeakString = myWeakString;
 }
iOS Memory Management
Accessor Methods - @property/@synthesize
 // MyClass.m
 // By synthesizing in this way you are protecting your iVar so it can
 // only be accessed through the setter.
 // It also means you can pass the argument myString to methods.
 @synthesize myString = _myString;

 -(id)initWithMyString:(NSString *)myString
 {
     if ((self = [super init]))
     {
         self.myString = myString;
     }
     return self;
 }

 +(id)myClassWithMyString:(NSString *)myString
 {
     return [[self initWithMyString:myString] autorelease];
 }
iOS Memory Management
Accessor Methods - @property/@synthesize
 // MyClass.m
 // By synthesizing in this way you are protecting your iVar so it can
 // only be accessed through the setter.
 // It also means you can pass the argument myString to methods.
 @synthesize myString;

 -(id)initWithMyString:(NSString *)cantBeCalledMyStringNow
 {
     if ((self = [super init]))
     {
         // Woops I assigned straight to the iVar. So it’s not retained now
         myString = cantBeCalledMyStringNow;
     }
     return self;
 }

 +(id)myClassWithMyString:(NSString *)cantBeCalledMyStringNow
 {
     return [[self initWithMyString: cantBeCalledMyStringNow] autorelease];
 }

Contenu connexe

Tendances

Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOSMake School
 
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
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろうUnity Technologies Japan K.K.
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement SauvageCocoaHeads France
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Nida Ismail Shah
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSMin Ming Lo
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsIgnacio Martín
 
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップUnite2017Tokyo
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityRyan Weaver
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative versionWO Community
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applicationslmrei
 

Tendances (20)

Lecture 3-ARC
Lecture 3-ARCLecture 3-ARC
Lecture 3-ARC
 
iOS5 NewStuff
iOS5 NewStuffiOS5 NewStuff
iOS5 NewStuff
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
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]
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 
Data perisistence in iOS
Data perisistence in iOSData perisistence in iOS
Data perisistence in iOS
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
ERGroupware
ERGroupwareERGroupware
ERGroupware
 
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 

En vedette

Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchasAlec Tucker
 
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
 
Apple iOS Introduction
Apple iOS IntroductionApple iOS Introduction
Apple iOS IntroductionPratik Vyas
 
Memory Management in RubyMotion
Memory Management in RubyMotionMemory Management in RubyMotion
Memory Management in RubyMotionMichael Denomy
 
My ppt @ bec doms on process management
My ppt @ bec doms on process managementMy ppt @ bec doms on process management
My ppt @ bec doms on process managementBabasab Patil
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touchmobiledeveloperpl
 
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーSatoshi Asano
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in AndroidKeyhan Asghari
 
Process and Threads in Linux - PPT
Process and Threads in Linux - PPTProcess and Threads in Linux - PPT
Process and Threads in Linux - PPTQUONTRASOLUTIONS
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in AndroidOpersys inc.
 
basic structure of computers
basic structure of computersbasic structure of computers
basic structure of computersHimanshu Chawla
 
File system in iOS
File system in iOSFile system in iOS
File system in iOSPurvik Rana
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in AndoidMonkop Inc
 
Memory Management
Memory ManagementMemory Management
Memory ManagementVisakh V
 
Windows OS Architecture in Summery
Windows OS Architecture in SummeryWindows OS Architecture in Summery
Windows OS Architecture in SummeryAsanka Dilruk
 

En vedette (19)

Android & IOS
Android & IOSAndroid & IOS
Android & IOS
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
 
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
 
Apple iOS Introduction
Apple iOS IntroductionApple iOS Introduction
Apple iOS Introduction
 
Ios operating system
Ios operating systemIos operating system
Ios operating system
 
Memory Management in RubyMotion
Memory Management in RubyMotionMemory Management in RubyMotion
Memory Management in RubyMotion
 
My ppt @ bec doms on process management
My ppt @ bec doms on process managementMy ppt @ bec doms on process management
My ppt @ bec doms on process management
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touch
 
ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマー
 
12 deadlock concept
12 deadlock concept12 deadlock concept
12 deadlock concept
 
iOS Ecosystem
iOS EcosystemiOS Ecosystem
iOS Ecosystem
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in Android
 
Process and Threads in Linux - PPT
Process and Threads in Linux - PPTProcess and Threads in Linux - PPT
Process and Threads in Linux - PPT
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in Android
 
basic structure of computers
basic structure of computersbasic structure of computers
basic structure of computers
 
File system in iOS
File system in iOSFile system in iOS
File system in iOS
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Windows OS Architecture in Summery
Windows OS Architecture in SummeryWindows OS Architecture in Summery
Windows OS Architecture in Summery
 

Similaire à iOS Memory Management Basics

iPhone Memory Management
iPhone Memory ManagementiPhone Memory Management
iPhone Memory ManagementVadim Zimin
 
Closer Look - iPhone programming
Closer Look - iPhone programmingCloser Look - iPhone programming
Closer Look - iPhone programmingSujith Krishnan
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
iPhone dev intro
iPhone dev introiPhone dev intro
iPhone dev introVonbo
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone developmentVonbo
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
Objective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersObjective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersBen Scheirman
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swiftYusuke Kita
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCJohnKennedy
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataChris Mar
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...smn-automate
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotionStefan Haflidason
 

Similaire à iOS Memory Management Basics (20)

iPhone Memory Management
iPhone Memory ManagementiPhone Memory Management
iPhone Memory Management
 
Closer Look - iPhone programming
Closer Look - iPhone programmingCloser Look - iPhone programming
Closer Look - iPhone programming
 
Ios development
Ios developmentIos development
Ios development
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
03 objective-c session 3
03  objective-c session 303  objective-c session 3
03 objective-c session 3
 
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
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
Objective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersObjective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET Developers
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveC
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Realm database
Realm databaseRealm database
Realm database
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 

Dernier

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Dernier (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

iOS Memory Management Basics

  • 1. iOS & Memory Management Basics Cameron Barrie - @whalec
  • 2. iOS & Memory Management Memory Management Programming Guide: https://developer.apple.com/iphone/library/ documentation/Cocoa/Conceptual/MemoryMgmt/ MemoryMgmt.html
  • 3. iOS Memory Management alloc/copy/retain/release/autorelease Program received signal: "EXC_BAD_ACCESS".
  • 5. iOS Memory Management ObjectiveC objects contain a ‘count’ of how many other objects are currently holding onto them. You increment that count with the retain message. You decrement that count with the release message. When that count hits 0. The object is deallocated from memory
  • 6. iOS Memory Management Memory Management Rules:
  • 7. iOS Memory Management Memory Management Rules: 1. You only release objects you own:
  • 8. iOS Memory Management Memory Management Rules: 1. You only release objects you own: [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil]
  • 9. iOS Memory Management Memory Management Rules: 1. You only release objects you own: [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil] NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"UPLeaderboardViewCell" owner:nil options:nil]; NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy];
  • 10. iOS Memory Management Memory Management Rules: 1. You only release objects you own: [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil] NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"UPLeaderboardViewCell" owner:nil options:nil]; NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy]; 2. Or objects you take ownership of:
  • 11. iOS Memory Management Memory Management Rules: 1. You only release objects you own: [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil] NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"UPLeaderboardViewCell" owner:nil options:nil]; NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy]; 2. Or objects you take ownership of: [[UIFont fontWithName:@"HoboStd" size:25] retain]
  • 12. iOS Memory Management Memory Management Rules: 1. You only release objects you own: [[UPGameViewController alloc] initWithNibName:@"UPGameView" bundle:nil] NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"UPLeaderboardViewCell" owner:nil options:nil]; NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy]; 2. Or objects you take ownership of: [[UIFont fontWithName:@"HoboStd" size:25] retain] Retaining an object simply increments an objects retainCount by 1.
  • 13. iOS Memory Management Releasing an object Release an object by sending it the release message
  • 14. iOS Memory Management Releasing an object Release an object by sending it the release message NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"UPLeaderboardViewCell" owner:nil options:nil]; NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy]; [mutableTopLevelObjects release];
  • 15. iOS Memory Management Releasing an object Release an object by sending it the release message NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"UPLeaderboardViewCell" owner:nil options:nil]; NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy]; [mutableTopLevelObjects release]; Releasing an object doesn’t remove it from memory. It simply decrements the objects retainCount by 1. When an objects retainCount is equal to 0. The object is deallocated by the runtime automatically.
  • 16. iOS Memory Management Releasing an object Release an object by sending it the release message NSMutableArray *mutableTopLevelObjects = [topLevelObjects mutableCopy]; [topLevelObjects retainCount]; // => 1 [topLevelObjects retain]; [topLevelObjects retainCount]; // => 2 [mutableTopLevelObjects release]; [topLevelObjects retainCount]; // => 1 [topLevelObjects release]; [topLevelObjects retainCount]; // => 0 Releasing an object doesn’t remove it from memory. It simply decrements the objects retainCount by 1. When an objects retainCount is equal to 0. The object is deallocated by the runtime automatically.
  • 17. iOS Memory Management So what about the other objects?
  • 18. iOS Memory Management So what about the other objects? They’re what’s known as autorelease objects.
  • 19. iOS Memory Management So what about the other objects? They’re what’s known as autorelease objects. // This object will be automatically released at some point // in the future when the autorelease pool is drained NSString *aString = [NSString stringWithFormat:@"a string with an int %i", 1];
  • 20. iOS Memory Management So what about the other objects? They’re what’s known as autorelease objects. // This object will be automatically released at some point // in the future when the autorelease pool is drained NSString *aString = [NSString stringWithFormat:@"a string with an int %i", 1]; You can mark your own objects as autorelease objects
  • 21. iOS Memory Management So what about the other objects? They’re what’s known as autorelease objects. // This object will be automatically released at some point // in the future when the autorelease pool is drained NSString *aString = [NSString stringWithFormat:@"a string with an int %i", 1]; You can mark your own objects as autorelease objects [topLevelObjects retainCount]; // => 1 [topLevelObjects autorelease]; [topLevelObjects retainCount]; // => 1 since it will be released later
  • 22. iOS Memory Management NSAutoreleasePool “Cocoa always expects there to be an autorelease pool available” - Memory Management Programming Guide: Autorelease Pools // main.m // The main entry point into the app sets up // an autorelease pool for us automatically int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }
  • 24. iOS Memory Management Common mistakes // You need to mark zero for autorelease or release it - (void)reset { NSNumber *zero = [[NSNumber alloc] initWithInteger:0]; [self setCount:zero]; }
  • 25. iOS Memory Management Common mistakes // You need to mark zero for autorelease or release it - (void)reset { NSNumber *zero = [[NSNumber alloc] initWithInteger:0]; [self setCount:zero]; } // zero is an autorelease object already. // you haven't used alloc/copy anywhere // you are over releasing the zero object - (void)reset { NSNumber *zero = [NSNumber numberWithInteger:0]; [self setCount:zero]; [zero release]; }
  • 26. iOS Memory Management Common confusion // Adding an object to a collection retains the object // It transfers ownership to the parent collection // Since alloc/copy was never called you don’t need // to release convenienceNumber NSMutableArray *array = [[NSMutableArray alloc] init]; NSUInteger i = 0; for (i; i < 10; i++) { NSNumber *convenienceNumber = [NSNumber numberWithInteger:i]; [array addObject:convenienceNumber]; }
  • 27. iOS Memory Management Common confusion // Adding an object to a collection retains the object // It transfers ownership to the parent collection // You need to release allocedNumber here since you alloced it. NSMutableArray *array = [[NSMutableArray alloc] init]; NSUInteger i = 0; for (i; i < 10; i++) { NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger: i]; [array addObject:allocedNumber]; [allocedNumber release]; }
  • 28. iOS Memory Management Returning Objects from Methods
  • 29. iOS Memory Management Returning Objects from Methods // Correct - You don't own the string object so you should return it as such. - (NSString *)fullName { NSString *string = [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName]; return string; }
  • 30. iOS Memory Management Returning Objects from Methods // Correct - You don't own the string object so you should return it as such. - (NSString *)fullName { NSString *string = [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName]; return string; } // Incorrect - You're returning an object that has already been released. - (NSString *)fullName { NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.lastName] release]; return string; }
  • 31. iOS Memory Management Returning Objects from Methods // Correct - You don't own the string object so you should return it as such. - (NSString *)fullName { NSString *string = [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName]; return string; } // Incorrect - You're returning an object that has already been released. - (NSString *)fullName { NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.lastName] release]; return string; } // Correct - You've created an autorelease object. - (NSString *)fullName { NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.lastName] autorelease]; return string; }
  • 32. iOS Memory Management Accessor Method - @property/@synthesize
  • 33. iOS Memory Management Accessor Method - @property/@synthesize // MyClass.h @property(nonatomic, readwrite, retain) NSString *myString
  • 34. iOS Memory Management Accessor Method - @property/@synthesize // MyClass.h @property(nonatomic, readwrite, retain) NSString *myString // MyClass.m @synthesize myString = _myString; -(id)init { if ((self = [super init])) { self.myString = @"A string to be retained"; } return self; } -(void)dealloc { [_myString release], _myString = nil; [super dealloc]; }
  • 35. iOS Memory Management Accessor Method - @property/@synthesize // MyClass.h // Will retain the variable sent to it. @property(nonatomic, readwrite, retain) NSString *myString; // Will not retain the variable sent to it. @property(nonatomic, readwrite, assign) NSString *myWeakString;
  • 36. iOS Memory Management Accessor Method - @property/@synthesize // MyClass.m // Will retain the variable sent to it. @synthesize myString = _myString; // The @synthesize produces a setter/getter combo(readwrite) -(NSString *)myString { return _myString; } -(void)setMyString:(NSString *)myString { if (myString != _myString) { [_myString release]; _myString = [myString retain]; } }
  • 37. iOS Memory Management Accessor Method - @property/@synthesize // MyClass.m // Will not retain the variable sent to it. @synthesize myWeakString = _myWeakString; // The @synthesize produces a setter/getter combo(readwrite) -(NSString *)myWeakString { return _myWeakString; } -(void)setMyWeakString:(NSString *)myWeakString { _myWeakString = myWeakString; }
  • 38. iOS Memory Management Accessor Methods - @property/@synthesize // MyClass.m // By synthesizing in this way you are protecting your iVar so it can // only be accessed through the setter. // It also means you can pass the argument myString to methods. @synthesize myString = _myString; -(id)initWithMyString:(NSString *)myString { if ((self = [super init])) { self.myString = myString; } return self; } +(id)myClassWithMyString:(NSString *)myString { return [[self initWithMyString:myString] autorelease]; }
  • 39. iOS Memory Management Accessor Methods - @property/@synthesize // MyClass.m // By synthesizing in this way you are protecting your iVar so it can // only be accessed through the setter. // It also means you can pass the argument myString to methods. @synthesize myString; -(id)initWithMyString:(NSString *)cantBeCalledMyStringNow { if ((self = [super init])) { // Woops I assigned straight to the iVar. So it’s not retained now myString = cantBeCalledMyStringNow; } return self; } +(id)myClassWithMyString:(NSString *)cantBeCalledMyStringNow { return [[self initWithMyString: cantBeCalledMyStringNow] autorelease]; }

Notes de l'éditeur