iPhone Memory Management

5,285 views

Published on

My presentation for IT Jam Ukraine

Published in: Technology, News & Politics
1 Comment
12 Likes
Statistics
Notes
No Downloads
Views
Total views
5,285
On SlideShare
0
From Embeds
0
Number of Embeds
16
Actions
Shares
0
Downloads
265
Comments
1
Likes
12
Embeds 0
No embeds

No notes for slide

iPhone Memory Management

  1. 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. 2. Introduction • iPhone and Objective-C • Language features • Objective-C 2.0: what’s new? Saturday, 5 December 2009 2
  3. 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. 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. 5. Basic rules and principles • Reference counting • Creating and destroying objects • Object ownership • Autorelease pool • Code conventions Saturday, 5 December 2009 5
  6. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 21. Debugging tools • Static code analyzer (Mac OS X 10.6) • Instruments (ObjectAlloc, Leaks) Saturday, 5 December 2009 21
  22. 22. Code analyze: Saturday, 5 December 2009 22
  23. 23. Instruments: Saturday, 5 December 2009 23
  24. 24. The end by Vadim Zimin phone: +38(093)5826658 e-mail: vad@wareous.com Saturday, 5 December 2009 24

×