SlideShare a Scribd company logo
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

More Related Content

PDF
Automatic Reference Counting @ Pragma Night
ZIP
iOS Memory Management Basics
PDF
Future-proofing Your JavaScript Apps (Compact edition)
PPT
Objective C Memory Management
PDF
Automatic Reference Counting
PDF
iPhone dev intro
PPTX
Awesomeness of JavaScript…almost
PDF
JavaScript 1.8.5: New Features Explored
Automatic Reference Counting @ Pragma Night
iOS Memory Management Basics
Future-proofing Your JavaScript Apps (Compact edition)
Objective C Memory Management
Automatic Reference Counting
iPhone dev intro
Awesomeness of JavaScript…almost
JavaScript 1.8.5: New Features Explored

What's hot (20)

PDF
Writing Reusable Web Components with jQuery and jQuery UI
PPTX
iOS Memory Management
PDF
A Tour Through the Groovy Ecosystem
PDF
Moose workshop
KEY
D7 entities fields
PPTX
Chapter iii(oop)
PDF
Brubeck: Overview
PDF
Lecture 04
PDF
Look Again at the ZCA
PDF
My Favourite 10 Things about Xcode/ObjectiveC
PDF
2013 gr8 conf_grails_code_from_the_trenches
PPTX
Luc Dekens - Italian vmug usercon
PDF
Getting Started with Dojo Toolkit
PDF
Moose Design Patterns
PPT
Memory management in Objective C
PDF
Using Templates to Achieve Awesomer Architecture
KEY
Dojo for programmers (TXJS 2010)
PDF
Cassandra data modeling talk
PDF
dojo is bizarro jQuery
PDF
Active domain
Writing Reusable Web Components with jQuery and jQuery UI
iOS Memory Management
A Tour Through the Groovy Ecosystem
Moose workshop
D7 entities fields
Chapter iii(oop)
Brubeck: Overview
Lecture 04
Look Again at the ZCA
My Favourite 10 Things about Xcode/ObjectiveC
2013 gr8 conf_grails_code_from_the_trenches
Luc Dekens - Italian vmug usercon
Getting Started with Dojo Toolkit
Moose Design Patterns
Memory management in Objective C
Using Templates to Achieve Awesomer Architecture
Dojo for programmers (TXJS 2010)
Cassandra data modeling talk
dojo is bizarro jQuery
Active domain
Ad

Viewers also liked (8)

PDF
Wag Report 2009 11 De
PDF
August 2011 Market Pulse - Attached Homes
PDF
H W 2010 01 At
PPT
Couch Culture
PPT
Darnesha Y
PPTX
Lumberjack 20 at CrossFit Enhance
PDF
H W 2010 Q1 De 12 Mo
PDF
H W 2011 10 De
Wag Report 2009 11 De
August 2011 Market Pulse - Attached Homes
H W 2010 01 At
Couch Culture
Darnesha Y
Lumberjack 20 at CrossFit Enhance
H W 2010 Q1 De 12 Mo
H W 2011 10 De
Ad

Similar to iPhone Memory Management (20)

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

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Empathic Computing: Creating Shared Understanding
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
Teaching material agriculture food technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
KodekX | Application Modernization Development
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
A Presentation on Artificial Intelligence
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cuic standard and advanced reporting.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Empathic Computing: Creating Shared Understanding
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Dropbox Q2 2025 Financial Results & Investor Presentation
Teaching material agriculture food technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KodekX | Application Modernization Development
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Per capita expenditure prediction using model stacking based on satellite ima...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
NewMind AI Weekly Chronicles - August'25 Week I
Spectral efficient network and resource selection model in 5G networks
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
A Presentation on Artificial Intelligence
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

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