Upload
vadim-zimin
View
6.105
Download
3
Embed Size (px)
DESCRIPTION
My presentation for IT Jam Ukraine
Citation preview
Objective-C 2.0Memory management for iPhone applications
Vadim Ziminsenior software developer at IT&T Consulting
1Saturday, 5 December 2009
Introduction
• iPhone and Objective-C
• Language features
• Objective-C 2.0: what’s new?
2Saturday, 5 December 2009
Why my app crashes?
• Bad memory access
• Internal exceptions
• Run out of memory
• Hang and killed by OS
• Killed by user
3Saturday, 5 December 2009
Main syntax differencesCall 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];
4Saturday, 5 December 2009
Basic rules and principles
• Reference counting
• Creating and destroying objects
• Object ownership
• Autorelease pool
• Code conventions
5Saturday, 5 December 2009
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
6Saturday, 5 December 2009
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; // на всякий случай)
7Saturday, 5 December 2009
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
8Saturday, 5 December 2009
@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 ownershipage = yearsOld;pets = [[NSMutableArray alloc] init]; // created and ownedreturn self;
}
-(void)dealloc {[name dealloc]; //wrong! will crash later[name release];[pets release]; [super dealloc]; // very important!
}
9Saturday, 5 December 2009
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
10Saturday, 5 December 2009
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
11Saturday, 5 December 2009
@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 accessorreturn [[pets copy] autorelease]; // return read-only copy
}
-(void)setName:(NSString*)newName { // safe setter[name autorelease]; // why not just “release”?name = [newName retain];
}
12Saturday, 5 December 2009
...@implementation Person...-(void)startPlayWithPets {
[NSThread detachNewThreadSelector:@selector(playWithPets) toTarget:self withObject:nil];
}
-(void)playWithPets {// without pool every autoreleased object will leak memoryNSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];NSArray* petsToPlay = [self pets] ; // our safe accessor returned autoreleased object, it is implicitly added to our thread’s autorelease poolBOOL allPetsAreHappy = NO;while(! allPetsAreHappy) {
... // some code, that may create autoreleased objects}[pool release]; // memory is freed, petsToPlay released as well
}
13Saturday, 5 December 2009
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
14Saturday, 5 December 2009
@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];
}
15Saturday, 5 December 2009
Objective-C @property
• Writability (readonly, readwrite)
• Setter semantic (assign, copy, retain)
• Atomicity (atomic, nonatomic)
Declaration:@propery (writability, setter, atomicity) type name;@synthesize name=ivarName;
Usage:object.propertyName = newValue;value = object.propertyName;
16Saturday, 5 December 2009
@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];
}}
17Saturday, 5 December 2009
@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];
}}
}18Saturday, 5 December 2009
Common mistakes
• no retain/release balance
• [self release]
• missed [super dealloc]
• reassign of pointer without old value release
• redefined -retain -release methods
19Saturday, 5 December 2009
Optimizations
• Use C structures instead of classes
• Keep immutable objects
• Release now instead of autorelease if possible
• Nested Autorelease pools
• Use UIKit recommendations
20Saturday, 5 December 2009
Debugging tools
• Static code analyzer (Mac OS X 10.6)
• Instruments (ObjectAlloc, Leaks)
21Saturday, 5 December 2009
Code analyze:
22Saturday, 5 December 2009
Instruments:
23Saturday, 5 December 2009