I know that the basic rule of memory management in objective-C is that for every object you do an alloc, you need to release it somewhere.
Say I have the following:
@interface NewPollViewController : UIViewController
{
NSMutableArray * myArray;
}
@property (nonatomic, retain) NSMutableArray * myArray;
@implementation NewPollViewController
@synthesize myArray = _myArray;
- (void) viewDidLoad
{
[super viewDidLoad];
self.myArray = [[NSMutableArray alloc] init];
}
Say that this self.myArray is used as a dataSource of a UITableView, so when and where should I release this? In the dealloc? I guess that the release in the dealloc corresponds to the retain that I’ve set in my property, so where do I release
In your example you technically need to release it twice – once in
dealloc, and once immediately after setting the property:The reasoning for this is because you are specifically allocating memory in
viewDidLoad, and then also increasing the retain count when setting the property.A way to avoid this is to use one of the static
NSMutableArrayconstructors or useautoreleasei.e.Alternatively, bypass the property altogether:
This would avoid the extra retain generated by the property (in fact you could get rid of the property statement if it was only used locally).