2
votes

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

3

3 Answers

3
votes

In your example you technically need to release it twice - once in dealloc, and once immediately after setting the property:

NSMutableArray *a = [[NSMutableArray alloc] init];
self.myArray = a;
[a release];

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 NSMutableArray constructors or use autorelease i.e.

self.myArray = [[[NSMutableArray alloc] init] autorelease];

Alternatively, bypass the property altogether:

myArray = [[NSMutableArray alloc] init];

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).

1
votes

If I want to expose a NSMutableArray I would do this:

@interface NewPollViewController : UIViewController 
{
   NSMutableArray * myArray;
}

@property (nonatomic, readonly) NSMutableArray * myArray;

@implementation NewPollViewController
@synthesize myArray;

- (void) viewDidLoad
{
  [super viewDidLoad];
  self.myArray = [[NSMutableArray alloc] init];
}

- (void) dealloc
{
   [myArray release],myArray = nil;
}

Changed the property to readonly because its mutable array you don't want other classes to change this array and you are properly alloc and releasing it.

0
votes

In your case I would often release it in the viewDidUnload, and also in dealloc.

I like to maintain a mirror with respect to where the memory is allocated. When its done in viewWillAppear, I release in viewWillDisappear.

Now since you are saying this is used thru-out the class, I would allocate in an init method, or the awakeFromNib, and then just release it once in dealloc.