Objective-C Memory Management by Ahmed Magdy
Introduction <ul><li>Objective-C : </li></ul><ul><li>Is a strict superset of C </li></ul><ul><li>Is an OOP version of C us...
OUTLINE <ul><li>Reference counting </li></ul><ul><li>Object Ownership </li></ul><ul><li>Auto-release pools </li></ul><ul><...
Reference Counting <ul><li>New object created with reference count=1 </li></ul><ul><li>Send retain/release message to incr...
Object ownership <ul><li>Any object may have one or more owner </li></ul><ul><li>Object’s creator becomes its 1st owner </...
Auto-release Pools <ul><li>What is an Autorelease pool? </li></ul><ul><li>Use autorelease method when you don’t want to ow...
Auto-release pool  example @implementation Person -(void)startPlayWithPets { [NSThread detachNewThreadSelector:@selector(p...
Conventions <ul><li>To create an object and be the first owner of it, use a method that has one of these in its name:  - a...
Properties in Objective-C <ul><li>Writability (readonly,  readwrite ) </li></ul><ul><li>Setter semantic ( assign , copy, r...
Properties in Objective-C  example 1 @property (nonatomic, retain) NSString* name; @synthesize name; // is equivalent to a...
Properties in Objective-C  example 2 @property (atomic, copy) NSString* name;  // equivalent to  -(NSString*)name { NSStri...
Rules of Thumb <ul><li>Use autorelease for temporaries </li></ul><ul><li>Retain & release members </li></ul><ul><li>Use pr...
Use autorelease for temporaries - (void) foo { NSString* s = [NSString string]; Or NSString* s = [[[NSString alloc] init] ...
Retain & release members @interface Bar { NSString* _name; } @end - (id) init { if (self = [super init]) { _name = [[NSStr...
Use properties to get correct setters @interface Bar { NSString* _name; } @property(retain) NSString* name; @end @implemen...
Break rule 2 to avoid retain loops @interface Bar { id _delegate; } @property(assign) id delegate; // Note: not retain @en...
Common mistakes <ul><li>Premature delete </li></ul><ul><li>Double-deletion </li></ul><ul><li>No retain/release balance </l...
Premature Deletion - (void)init { if (self = [super init]) { _foo = [NSString string]; } } - (void)foo { NSLog(@”Foo is %@...
Double-deletion - (void) f { Bar* bar = [NSString string]; _foo = bar; } ... [pool release]  or [pool drain]; - (void)deal...
No retain/release balance <ul><li>Causing either: </li></ul><ul><li>A  memory leak , if the retain are greater than the re...
[self release] - (void) someMethod { _name = @”the name”; _message = [[[NSString alloc] initWithFormat: @”my name is: ”, _...
Reassign of pointer without releasing old value - (void) leak { NSString *name = [NSString alloc]  initWithFormat:@”%@”, @...
Overriding retain & release methods <ul><li>Some developers tend to override retain and release methods. </li></ul><ul><li...
Optimizations <ul><li>Use C structures instead of classes </li></ul><ul><li>Keep immutable objects </li></ul><ul><li>Relea...
Summary <ul><li>Reference counting </li></ul><ul><li>Object Ownership </li></ul><ul><li>Auto-release pools </li></ul><ul><...
Thank you
Upcoming SlideShare
Loading in …5
×

Objective C Memory Management

6,511 views

Published on

iOS 3 and iOS 4 Memory Management Tips and Tricks

Published in: Technology
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
6,511
On SlideShare
0
From Embeds
0
Number of Embeds
85
Actions
Shares
0
Downloads
214
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide

Objective C Memory Management

  1. 1. Objective-C Memory Management by Ahmed Magdy
  2. 2. Introduction <ul><li>Objective-C : </li></ul><ul><li>Is a strict superset of C </li></ul><ul><li>Is an OOP version of C using message passing. </li></ul><ul><li>Uses a variation of GCC and GDB </li></ul><ul><li>Has dynamic and static memory allocation </li></ul><ul><li>Uses “Reference Counting” to manage memory in iOS. </li></ul>
  3. 3. OUTLINE <ul><li>Reference counting </li></ul><ul><li>Object Ownership </li></ul><ul><li>Auto-release pools </li></ul><ul><li>Conventions </li></ul><ul><li>Properties in Objective-C </li></ul><ul><li>Rules of Thumb </li></ul><ul><li>Common mistakes </li></ul><ul><li>Optimizations </li></ul>
  4. 4. Reference Counting <ul><li>New object created with reference count=1 </li></ul><ul><li>Send retain/release message to increase/decrease reference count </li></ul><ul><li>Object deallocated automatically when reference count becomes 0 </li></ul>
  5. 5. Object ownership <ul><li>Any object may have one or more owner </li></ul><ul><li>Object’s creator becomes its 1st owner </li></ul><ul><li>Other owners must retain object </li></ul><ul><li>Owner is responsible for releasing object </li></ul><ul><li>Owner must never destroy object directly </li></ul><ul><li>Object without owners are deallocated automatically </li></ul><ul><li>Weak references used to avoid infinite retain loops </li></ul>
  6. 6. Auto-release Pools <ul><li>What is an Autorelease pool? </li></ul><ul><li>Use autorelease method when you don’t want to own the object </li></ul><ul><li>autorelease mean “Release later” </li></ul><ul><li>Every thread should have it’s own pool </li></ul>
  7. 7. Auto-release pool example @implementation Person -(void)startPlayWithPets { [NSThread detachNewThreadSelector:@selector(play) toTarget:self withObject:nil]; } -(void)play { // without pool every autoreleased object will leak memory NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; // safe accessor returns autoreleased object, added to thread’s autorelease pool NSArray* petsToPlay = [self pets] ; BOOL allPetsAreHappy = NO; while(! allPetsAreHappy) { ... // some code, that may create autoreleased objects } [pool release]; // or [pool drain]; memory is freed, petsToPlay released as well } @end
  8. 8. Conventions <ul><li>To create an object and be the first owner of it, use a method that has one of these in its name: - alloc - new - copy - mutableCopy </li></ul><ul><li>If we use properties and convenience constructors we do not take ownership of the object. </li></ul><ul><ul><ul><li>- Convenience Constructors (Factory Pattern) like: stringWithFormat, imageWithData, imageWithContentsOfFile, stringWithContentsOfFile </li></ul></ul></ul>
  9. 9. Properties in Objective-C <ul><li>Writability (readonly, readwrite ) </li></ul><ul><li>Setter semantic ( assign , copy, retain) </li></ul><ul><li>Atomicity ( atomic , nonatomic) </li></ul><ul><li>Declaration: @property (writability, setter, atomicity) type name; @synthesize name=ivarName; </li></ul><ul><li>Usage: </li></ul><ul><li>object.propertyName = newValue; </li></ul><ul><li>value = object.propertyName; </li></ul>
  10. 10. Properties in Objective-C example 1 @property (nonatomic, retain) NSString* name; @synthesize name; // is equivalent to a pair of methods -(NSString*)name { return [[name retain] autorelease]; } -(void)setName:(NSString*)aName { if (name != aName) { [name release]; name = [aName retain]; } }
  11. 11. Properties in Objective-C example 2 @property (atomic, copy) NSString* name; // equivalent to -(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 copy]; } }
  12. 12. Rules of Thumb <ul><li>Use autorelease for temporaries </li></ul><ul><li>Retain & release members </li></ul><ul><li>Use properties to get correct setters </li></ul><ul><li>Break rule 2 to avoid retain loops </li></ul>
  13. 13. Use autorelease for temporaries - (void) foo { NSString* s = [NSString string]; Or NSString* s = [[[NSString alloc] init] autorelease]; }
  14. 14. Retain & release members @interface Bar { NSString* _name; } @end - (id) init { if (self = [super init]) { _name = [[NSString alloc] init]; } return self; } - (void) dealloc { [_name release]; [super dealloc]; }
  15. 15. Use properties to get correct setters @interface Bar { NSString* _name; } @property(retain) NSString* name; @end @implementation @synthesize name = _name; - (void) dealloc { [_name release]; // still important because of _name [super dealloc]; } @end
  16. 16. Break rule 2 to avoid retain loops @interface Bar { id _delegate; } @property(assign) id delegate; // Note: not retain @end @interface Foo { Bar* _bar; } @end In Foo: _bar = [[Bar alloc] init]; _bar.delegate = self;
  17. 17. Common mistakes <ul><li>Premature delete </li></ul><ul><li>Double-deletion </li></ul><ul><li>No retain/release balance </li></ul><ul><li>[self release] </li></ul><ul><li>Reassign of pointer without releasing old value </li></ul><ul><li>Overriding retain & release methods </li></ul>
  18. 18. Premature Deletion - (void)init { if (self = [super init]) { _foo = [NSString string]; } } - (void)foo { NSLog(@”Foo is %@”, _foo); }
  19. 19. Double-deletion - (void) f { Bar* bar = [NSString string]; _foo = bar; } ... [pool release] or [pool drain]; - (void)dealloc { [_foo release]; // retain count -1 [super dealloc]; }
  20. 20. No retain/release balance <ul><li>Causing either: </li></ul><ul><li>A memory leak , if the retain are greater than the releases </li></ul><ul><li> or </li></ul><ul><li>A dangling pointer , if the releases are greater than the retains. (Bad Access Error or accessing an illegal piece of memory) </li></ul>
  21. 21. [self release] - (void) someMethod { _name = @”the name”; _message = [[[NSString alloc] initWithFormat: @”my name is: ”, _name] autorelease]; [self release]; NSLog(_message); // error, if self is deallocated } - (void) dealloc { [_name release]; [_message release]; [super dealloc]; }
  22. 22. Reassign of pointer without releasing old value - (void) leak { NSString *name = [NSString alloc] initWithFormat:@”%@”, @”Ahmed”]; name = @”Ali”; // the value @”Ahmed” is still there so there is a memory leak }
  23. 23. Overriding retain & release methods <ul><li>Some developers tend to override retain and release methods. </li></ul><ul><li>They have to be very careful or else they may cause a memory leak or a dangling pointer. </li></ul>
  24. 24. Optimizations <ul><li>Use C structures instead of classes </li></ul><ul><li>Keep immutable objects </li></ul><ul><li>Release now instead of autorelease if possible </li></ul><ul><li>Nested Autorelease pools </li></ul><ul><li>Use UIKit recommendations </li></ul>
  25. 25. Summary <ul><li>Reference counting </li></ul><ul><li>Object Ownership </li></ul><ul><li>Auto-release pools </li></ul><ul><li>Conventions </li></ul><ul><li>Properties in Objective-C </li></ul><ul><li>Rules of Thumb </li></ul><ul><li>Common mistakes </li></ul><ul><li>Optimizations </li></ul>
  26. 26. Thank you

×