SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Objective-C 2.0
                            Memory management for iPhone applications

               Vadim Zimin
               senior software developer at IT&T Consulting




Saturday, 5 December 2009                                               1
Introduction

                   • iPhone and Objective-C
                   • Language features
                   • Objective-C 2.0: what’s new?


Saturday, 5 December 2009                           2
Why my app crashes?

                   • Bad memory access
                   • Internal exceptions
                   • Run out of memory
                   • Hang and killed by OS
                   • Killed by user

Saturday, 5 December 2009                    3
Main syntax differences
       Call a method:
               object->Method();
               [object message];

       Passing method arguments:
         person->SetNameAndAge(name, age);
         [person setName:name andAge:age];

       Declaration:
         void Person::SetNameAndAge(string name, int age);
         -(void)setName:(NSString*)name andAge:(int)age;

            Access to current object’s method:
             this->DoSomething();
             [self doSomething];

Saturday, 5 December 2009                                    4
Basic rules and
                              principles
                   • Reference counting
                   • Creating and destroying objects
                   • Object ownership
                   • Autorelease pool
                   • Code conventions

Saturday, 5 December 2009                              5
Reference counting

                  • New object created with reference
                            count=1
                  • Send retain/release message to increase/
                            decrease reference count
                  • Object deallocated automatically when
                            reference count becomes 0



Saturday, 5 December 2009                                      6
Creating object:
         Person* person = [[Person alloc] init];
         // ref_count =1 now

         Using object:
         [person setName:@”Alex”];
         [person setAge:15];
         NSLog([person personInfo]); // print to stdout

         Destroying (releasing) object:
         [person release];// person pointer is invalid now
         [person addPet:[Pet anyPet]]; // crash!!!
         person = nil; // на всякий случай)

Saturday, 5 December 2009                                    7
Object ownership
                   • Any object may have one or more owner
                   • Object’s creator becomes its 1st owner
                   • Other owners must retain object
                   • Owner is responsible for releasing object
                   • Owner must never destroy object directly
                   • Object w/o owners deallocated
                            automatically
                   • Weak references used to avoid inf. loops
Saturday, 5 December 2009                                        8
@interface Person : NSObject {
            NSString* name;
            int age;
            NSMutableArray* pets;
        }
        ...
        @implementation Person

        -(id)initWithName:(NSString*)aName andAge:(int)yearsOld {
           self = [super init];
           name = [aName retain]; // got ownership
           age = yearsOld;
           pets = [[NSMutableArray alloc] init]; // created and owned
           return self;
        }

        -(void)dealloc {
           [name dealloc]; //wrong! will crash later
           [name release];
           [pets release];
           [super dealloc]; // very important!
        }

Saturday, 5 December 2009                                               9
Autoreleased objects

                   • What is Autorelease pool?
                   • Use -autorelease method when you don’t
                            want to own the object
                   • autorelease mean “Release later”
                   • Every thread should have it’s own pool

Saturday, 5 December 2009                                     10
NSAutorelease pool = [[NSAutoreleasePool alloc] init];
        ...
            {
              Person* person = [[Person alloc] init]; // retainCount ==1
              ...
              [person autorelease]; // retainCount==1

            } // out of person pointer scope
        ...
        [pool release]; // memory allocated for Person released




Saturday, 5 December 2009                                                  11
@interface Person : NSObject {
            NSString* name;
            int age;
            NSMutableArray* pets;
        }
        ...
        @implementation Person
        ...
        -(NSString*)personInfo {
            NSString* info = [[NSString alloc] initWithFormat:
            @”%@, %d years old, owns %d pets”, name, age, [pets count]];
            return [info autorelease]; // we are not responsible for this object now!
        }

        -(NSArray*)pets { // safe accessor
            return [[pets copy] autorelease]; // return read-only copy
        }

        -(void)setName:(NSString*)newName { // safe setter
             [name autorelease]; // why not just “release”?
             name = [newName retain];
        }

Saturday, 5 December 2009                                                               12
...
        @implementation Person
        ...
        -(void)startPlayWithPets {
             [NSThread detachNewThreadSelector:@selector(playWithPets)
             toTarget:self withObject:nil];
        }

        -(void)playWithPets {
             // without pool every autoreleased object will leak memory
             NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
             NSArray* petsToPlay = [self pets] ; // our safe accessor returned
             autoreleased object, it is implicitly added to our thread’s autorelease pool
             BOOL allPetsAreHappy = NO;
             while(! allPetsAreHappy) {
                  ... // some code, that may create autoreleased objects
             }
             [pool release]; // memory is freed, petsToPlay released as well
        }




Saturday, 5 December 2009                                                                   13
Conventions
                   •        Syntax like [[Class alloc] init] and [obj copy] creates
                            objects with ref_count==1, you are responsible for
                            releasing (autoreleasing) it

                   •        You are not responsible for releasing objects created by
                            “convenience constructors” like
                            -[aString stringByAppendingString:otherString] or
                            +[NSNumber numberWithFloat:1.0f]

                   •        You are not responsible for objects obtained by
                            (property) getters and should not delegate such
                            responsibility to others when implementing getters




Saturday, 5 December 2009                                                              14
@interface Pet : NSObject { ... }
        ...
        @implementation Pet
        // this method retuns object with retainCount =1 by convention
        -(id)initWithName:(NSString*)petName {
            self = [super init];
            name = [petName retain];
            return self;
        }
        // convenience constructor, autoreleased object
        +(id)anyPet {
            NSSet* petClasses = [NSSet setWithObjects:[Dog class], [Cat
            class],nil];
            Class aClass = [petClasses anyObject];
            NSSet* petNames = [NSSet setWithObjects:@”Max”,
            @”Sharik”,@”Murka”,nil];
            NSSrting* aName = [petNames anyObject];
            return [[[aClass alloc] initWithName:aName] autorelease];
        }

Saturday, 5 December 2009                                                 15
Objective-C @property
                                  Declaration:
             @propery (writability, setter, atomicity) type name;
             @synthesize name=ivarName;
                                      Usage:
             object.propertyName = newValue;
             value = object.propertyName;


                   • Writability (readonly, readwrite)
                   •        Setter semantic (assign, copy, retain)

                   • Atomicity (atomic, nonatomic)
Saturday, 5 December 2009                                            16
@property (nonatomic, retain) NSString* name;

       // equivalent to pair of methods
       -(NSString*)name {
           return name;
       }

       -(void)setName:(NSString*)aName {
          if (name != aName) {
              [name release];
              name = [aName retain];
          }
       }

Saturday, 5 December 2009                              17
@property (atomic, copy) NSString* name;
       // equivalent to pair of methods
       -(NSString*)name {
           NSString* retVal=nil;
           @synchronized(self) {
               retVal = [[name retain] autorelease];
           }
           return retVal;
       }

       -(void)setName:(NSString*)aName {
           @synchronized(self) {
               if (name != aName) {
                  [name release];
                  name = [aName retain];
               }
           }
       }
Saturday, 5 December 2009                              18
Common mistakes
                   • no retain/release balance
                   • [self release]
                   • missed [super dealloc]
                   • reassign of pointer without old value
                            release
                   • redefined -retain -release methods
Saturday, 5 December 2009                                    19
Optimizations
                   • Use C structures instead of classes
                   • Keep immutable objects
                   • Release now instead of autorelease if
                            possible
                   • Nested Autorelease pools
                   • Use UIKit recommendations
Saturday, 5 December 2009                                    20
Debugging tools



                   • Static code analyzer (Mac OS X 10.6)
                   • Instruments (ObjectAlloc, Leaks)


Saturday, 5 December 2009                                   21
Code analyze:




Saturday, 5 December 2009   22
Instruments:




Saturday, 5 December 2009   23
The end


                                 by Vadim Zimin
                            phone: +38(093)5826658
                            e-mail: vad@wareous.com
Saturday, 5 December 2009                             24

Contenu connexe

Tendances

Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIYnon Perek
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemLeonard Axelsson
 
Moose workshop
Moose workshopMoose workshop
Moose workshopYnon Perek
 
D7 entities fields
D7 entities fieldsD7 entities fields
D7 entities fieldscyberswat
 
Look Again at the ZCA
Look Again at the ZCALook Again at the ZCA
Look Again at the ZCAmikerhodes
 
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
 
2013 gr8 conf_grails_code_from_the_trenches
2013 gr8 conf_grails_code_from_the_trenches2013 gr8 conf_grails_code_from_the_trenches
2013 gr8 conf_grails_code_from_the_trenchesEdwin van Nes
 
Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon VMUG IT
 
Getting Started with Dojo Toolkit
Getting Started with Dojo ToolkitGetting Started with Dojo Toolkit
Getting Started with Dojo ToolkitThomas Koch
 
Moose Design Patterns
Moose Design PatternsMoose Design Patterns
Moose Design PatternsYnon Perek
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective CNeha Gupta
 
Using Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer ArchitectureUsing Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer ArchitectureGarann Means
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
Cassandra data modeling talk
Cassandra data modeling talkCassandra data modeling talk
Cassandra data modeling talkPatrick McFadin
 
dojo is bizarro jQuery
dojo is bizarro jQuerydojo is bizarro jQuery
dojo is bizarro jQueryJohn Hann
 

Tendances (20)

Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
 
iOS Memory Management
iOS Memory ManagementiOS Memory Management
iOS Memory Management
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy Ecosystem
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
 
D7 entities fields
D7 entities fieldsD7 entities fields
D7 entities fields
 
Chapter iii(oop)
Chapter iii(oop)Chapter iii(oop)
Chapter iii(oop)
 
Brubeck: Overview
Brubeck: OverviewBrubeck: Overview
Brubeck: Overview
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
Look Again at the ZCA
Look Again at the ZCALook Again at the ZCA
Look Again at the ZCA
 
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
 
2013 gr8 conf_grails_code_from_the_trenches
2013 gr8 conf_grails_code_from_the_trenches2013 gr8 conf_grails_code_from_the_trenches
2013 gr8 conf_grails_code_from_the_trenches
 
Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon
 
Getting Started with Dojo Toolkit
Getting Started with Dojo ToolkitGetting Started with Dojo Toolkit
Getting Started with Dojo Toolkit
 
Moose Design Patterns
Moose Design PatternsMoose Design Patterns
Moose Design Patterns
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective C
 
Using Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer ArchitectureUsing Templates to Achieve Awesomer Architecture
Using Templates to Achieve Awesomer Architecture
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
Cassandra data modeling talk
Cassandra data modeling talkCassandra data modeling talk
Cassandra data modeling talk
 
dojo is bizarro jQuery
dojo is bizarro jQuerydojo is bizarro jQuery
dojo is bizarro jQuery
 
Active domain
Active domainActive domain
Active domain
 

En vedette

Wag Report 2009 11 De
Wag Report 2009 11 DeWag Report 2009 11 De
Wag Report 2009 11 Dechipwags
 
August 2011 Market Pulse - Attached Homes
August 2011 Market Pulse - Attached HomesAugust 2011 Market Pulse - Attached Homes
August 2011 Market Pulse - Attached Homeschipwags
 
H W 2010 01 At
H W 2010 01 AtH W 2010 01 At
H W 2010 01 Atchipwags
 
H W 2010 Q1 De 12 Mo
H W 2010 Q1 De 12 MoH W 2010 Q1 De 12 Mo
H W 2010 Q1 De 12 Mochipwags
 
H W 2011 10 De
H W 2011 10 DeH W 2011 10 De
H W 2011 10 Dechipwags
 

En vedette (8)

Wag Report 2009 11 De
Wag Report 2009 11 DeWag Report 2009 11 De
Wag Report 2009 11 De
 
August 2011 Market Pulse - Attached Homes
August 2011 Market Pulse - Attached HomesAugust 2011 Market Pulse - Attached Homes
August 2011 Market Pulse - Attached Homes
 
H W 2010 01 At
H W 2010 01 AtH W 2010 01 At
H W 2010 01 At
 
Couch Culture
Couch CultureCouch Culture
Couch Culture
 
Darnesha Y
Darnesha YDarnesha Y
Darnesha Y
 
Lumberjack 20 at CrossFit Enhance
Lumberjack 20 at CrossFit EnhanceLumberjack 20 at CrossFit Enhance
Lumberjack 20 at CrossFit Enhance
 
H W 2010 Q1 De 12 Mo
H W 2010 Q1 De 12 MoH W 2010 Q1 De 12 Mo
H W 2010 Q1 De 12 Mo
 
H W 2011 10 De
H W 2011 10 DeH W 2011 10 De
H W 2011 10 De
 

Similaire à iPhone Memory Management

ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーSatoshi Asano
 
Closer Look - iPhone programming
Closer Look - iPhone programmingCloser Look - iPhone programming
Closer Look - iPhone programmingSujith Krishnan
 
Objective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersObjective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersBen Scheirman
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Countingpragmamark
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement SauvageCocoaHeads France
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 
Objective-C Survives
Objective-C SurvivesObjective-C Survives
Objective-C SurvivesS Akai
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
Thinking Outside The [Sand]Box
Thinking Outside The [Sand]BoxThinking Outside The [Sand]Box
Thinking Outside The [Sand]BoxMichael Genkin
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CDataArt
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl ObjectsLambert Lum
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone developmentVonbo
 
Introduction to Ruby & Ruby on Rails
Introduction to Ruby & Ruby on RailsIntroduction to Ruby & Ruby on Rails
Introduction to Ruby & Ruby on RailsMarcelo Pinheiro
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritancepedro.carvalho
 

Similaire à iPhone Memory Management (20)

ARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマーARCでめちゃモテiOSプログラマー
ARCでめちゃモテiOSプログラマー
 
Closer Look - iPhone programming
Closer Look - iPhone programmingCloser Look - iPhone programming
Closer Look - iPhone programming
 
Objective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersObjective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET Developers
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Objective-C Survives
Objective-C SurvivesObjective-C Survives
Objective-C Survives
 
Ios development
Ios developmentIos development
Ios development
 
Thinking Outside The [Sand]Box
Thinking Outside The [Sand]BoxThinking Outside The [Sand]Box
Thinking Outside The [Sand]Box
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-C
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone development
 
Introduction to Ruby & Ruby on Rails
Introduction to Ruby & Ruby on RailsIntroduction to Ruby & Ruby on Rails
Introduction to Ruby & Ruby on Rails
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
Moose
MooseMoose
Moose
 
The messy lecture
The messy lectureThe messy lecture
The messy lecture
 

Dernier

OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 

Dernier (20)

OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 

iPhone Memory Management

  • 1. Objective-C 2.0 Memory management for iPhone applications Vadim Zimin senior software developer at IT&T Consulting Saturday, 5 December 2009 1
  • 2. Introduction • iPhone and Objective-C • Language features • Objective-C 2.0: what’s new? Saturday, 5 December 2009 2
  • 3. Why my app crashes? • Bad memory access • Internal exceptions • Run out of memory • Hang and killed by OS • Killed by user Saturday, 5 December 2009 3
  • 4. Main syntax differences Call a method: object->Method(); [object message]; Passing method arguments: person->SetNameAndAge(name, age); [person setName:name andAge:age]; Declaration: void Person::SetNameAndAge(string name, int age); -(void)setName:(NSString*)name andAge:(int)age; Access to current object’s method: this->DoSomething(); [self doSomething]; Saturday, 5 December 2009 4
  • 5. Basic rules and principles • Reference counting • Creating and destroying objects • Object ownership • Autorelease pool • Code conventions Saturday, 5 December 2009 5
  • 6. Reference counting • New object created with reference count=1 • Send retain/release message to increase/ decrease reference count • Object deallocated automatically when reference count becomes 0 Saturday, 5 December 2009 6
  • 7. Creating object: Person* person = [[Person alloc] init]; // ref_count =1 now Using object: [person setName:@”Alex”]; [person setAge:15]; NSLog([person personInfo]); // print to stdout Destroying (releasing) object: [person release];// person pointer is invalid now [person addPet:[Pet anyPet]]; // crash!!! person = nil; // на всякий случай) Saturday, 5 December 2009 7
  • 8. Object ownership • Any object may have one or more owner • Object’s creator becomes its 1st owner • Other owners must retain object • Owner is responsible for releasing object • Owner must never destroy object directly • Object w/o owners deallocated automatically • Weak references used to avoid inf. loops Saturday, 5 December 2009 8
  • 9. @interface Person : NSObject { NSString* name; int age; NSMutableArray* pets; } ... @implementation Person -(id)initWithName:(NSString*)aName andAge:(int)yearsOld { self = [super init]; name = [aName retain]; // got ownership age = yearsOld; pets = [[NSMutableArray alloc] init]; // created and owned return self; } -(void)dealloc { [name dealloc]; //wrong! will crash later [name release]; [pets release]; [super dealloc]; // very important! } Saturday, 5 December 2009 9
  • 10. Autoreleased objects • What is Autorelease pool? • Use -autorelease method when you don’t want to own the object • autorelease mean “Release later” • Every thread should have it’s own pool Saturday, 5 December 2009 10
  • 11. NSAutorelease pool = [[NSAutoreleasePool alloc] init]; ... { Person* person = [[Person alloc] init]; // retainCount ==1 ... [person autorelease]; // retainCount==1 } // out of person pointer scope ... [pool release]; // memory allocated for Person released Saturday, 5 December 2009 11
  • 12. @interface Person : NSObject { NSString* name; int age; NSMutableArray* pets; } ... @implementation Person ... -(NSString*)personInfo { NSString* info = [[NSString alloc] initWithFormat: @”%@, %d years old, owns %d pets”, name, age, [pets count]]; return [info autorelease]; // we are not responsible for this object now! } -(NSArray*)pets { // safe accessor return [[pets copy] autorelease]; // return read-only copy } -(void)setName:(NSString*)newName { // safe setter [name autorelease]; // why not just “release”? name = [newName retain]; } Saturday, 5 December 2009 12
  • 13. ... @implementation Person ... -(void)startPlayWithPets { [NSThread detachNewThreadSelector:@selector(playWithPets) toTarget:self withObject:nil]; } -(void)playWithPets { // without pool every autoreleased object will leak memory NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSArray* petsToPlay = [self pets] ; // our safe accessor returned autoreleased object, it is implicitly added to our thread’s autorelease pool BOOL allPetsAreHappy = NO; while(! allPetsAreHappy) { ... // some code, that may create autoreleased objects } [pool release]; // memory is freed, petsToPlay released as well } Saturday, 5 December 2009 13
  • 14. Conventions • Syntax like [[Class alloc] init] and [obj copy] creates objects with ref_count==1, you are responsible for releasing (autoreleasing) it • You are not responsible for releasing objects created by “convenience constructors” like -[aString stringByAppendingString:otherString] or +[NSNumber numberWithFloat:1.0f] • You are not responsible for objects obtained by (property) getters and should not delegate such responsibility to others when implementing getters Saturday, 5 December 2009 14
  • 15. @interface Pet : NSObject { ... } ... @implementation Pet // this method retuns object with retainCount =1 by convention -(id)initWithName:(NSString*)petName { self = [super init]; name = [petName retain]; return self; } // convenience constructor, autoreleased object +(id)anyPet { NSSet* petClasses = [NSSet setWithObjects:[Dog class], [Cat class],nil]; Class aClass = [petClasses anyObject]; NSSet* petNames = [NSSet setWithObjects:@”Max”, @”Sharik”,@”Murka”,nil]; NSSrting* aName = [petNames anyObject]; return [[[aClass alloc] initWithName:aName] autorelease]; } Saturday, 5 December 2009 15
  • 16. Objective-C @property Declaration: @propery (writability, setter, atomicity) type name; @synthesize name=ivarName; Usage: object.propertyName = newValue; value = object.propertyName; • Writability (readonly, readwrite) • Setter semantic (assign, copy, retain) • Atomicity (atomic, nonatomic) Saturday, 5 December 2009 16
  • 17. @property (nonatomic, retain) NSString* name; // equivalent to pair of methods -(NSString*)name { return name; } -(void)setName:(NSString*)aName { if (name != aName) { [name release]; name = [aName retain]; } } Saturday, 5 December 2009 17
  • 18. @property (atomic, copy) NSString* name; // equivalent to pair of methods -(NSString*)name { NSString* retVal=nil; @synchronized(self) { retVal = [[name retain] autorelease]; } return retVal; } -(void)setName:(NSString*)aName { @synchronized(self) { if (name != aName) { [name release]; name = [aName retain]; } } } Saturday, 5 December 2009 18
  • 19. Common mistakes • no retain/release balance • [self release] • missed [super dealloc] • reassign of pointer without old value release • redefined -retain -release methods Saturday, 5 December 2009 19
  • 20. Optimizations • Use C structures instead of classes • Keep immutable objects • Release now instead of autorelease if possible • Nested Autorelease pools • Use UIKit recommendations Saturday, 5 December 2009 20
  • 21. Debugging tools • Static code analyzer (Mac OS X 10.6) • Instruments (ObjectAlloc, Leaks) Saturday, 5 December 2009 21
  • 22. Code analyze: Saturday, 5 December 2009 22
  • 24. The end by Vadim Zimin phone: +38(093)5826658 e-mail: vad@wareous.com Saturday, 5 December 2009 24