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?
That is correct, the retain count for
self.array =ends up as 2.First, you
alloc inita newNSArrayobject. That’s a retain count of 1. Second, your setter sends the object aretainmessage when assigning it to your instance var. That bumps the retain count up to 2.Besides directly setting the ivar
array =as in your question, here are some ways to do this with yourself.arrayproperty without leaking:Autorelease:
Use the
arrayWithObjects:class method. Simpler, and also produces an autoreleased object:Make a temporary variable to hold the new pointer, then release it after setting the property (which will have had it retained by then):