1

Imagine I have a member variable

@property(nonatomic,retain)NSArray *array;

Now in my viewDidLoad I set up a simple array

array = [[NSArray alloc]initWithObjects:@"A",@"B","C",nil];

My retain count for array is going to be 1 right?

Now if I were to set up the array using the accessor method

self.array = [[NSArray alloc]initWithObjects:@"A",@"B","C",nil];

Is my retain count 2 because my accessor method bumps the retain count up by 1?

What's the convention for initializing member variables?

aaronium112
  • 2,992
  • 4
  • 35
  • 50

1 Answers1

3

That is correct, the retain count for self.array = ends up as 2.

First, you alloc init a new NSArray object. That's a retain count of 1. Second, your setter sends the object a retain message when assigning it to your instance var. That bumps the retain count up to 2.

What's the convention for initializing member variables?

Besides directly setting the ivar array = as in your question, here are some ways to do this with your self.array property without leaking:

  1. Autorelease:

    self.array = [[[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil] autorelease];
    
  2. Use the arrayWithObjects: class method. Simpler, and also produces an autoreleased object:

    self.array = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
    
  3. Make a temporary variable to hold the new pointer, then release it after setting the property (which will have had it retained by then):

    NSArray *tmpArray = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil];
    self.array = tmpArray;
    [tmpArray release];
    
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • What about using the first option array = [[NSArray alloc]initWithObjects:....]; It seems the simplest why don't you suggest that one? – aaronium112 Feb 13 '11 at 16:12