This is an old revision of the document!
autorelease pools and release/retain
autorelease pools
- in general, if you use the [filenames count;
int i;
for(i=0; i<[filenames count]; i++){ NSString *fullPath = [NSString stringWithFormat:@"%@/%@", path, [filenames objectAtIndex:i]]; [fullFilenames addObject:fullPath]; // fullPath is 2, and will be released to 1 after removeAllObjects, // then autoreleased to 0 if not retained elsewhere } [gridView createGridItemViews:fullFilenames]; [fullFilenames removeAllObjects]; [fullFilenames release]; // the following method call releases the "filenames" array, and the "fullPath" objects [aPool release];
… </code>
release/retain and retainCount
- objects have a retainCount, and when it reaches zero the object is deallocated from memory
- to find the retainCount you send the message to the object: (int)[object retainCount]
- to increment the retainCount, you send the message: [object retain]
- to decrement the retainCount, you send the message: [object release]
Tips
- adding an object to a mutable array increases the retain count by 1
- removing an object from a mutable array decreases the retain count by 1
- adding a view to another view (subview/superview) increases the retain count by 1
- removing or replacing a subview with another view decreases the retain count by 1
- if you need to keep an object around, you may need to use [object retain] before some of the methods that decrement the retain count