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.
9.
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. 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.
13. Use autorelease for temporaries - (void) foo { NSString* s = [NSString string]; Or NSString* s = [[[NSString alloc] init] autorelease]; }
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. 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;
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 }