Question About Retain Counts & initializing member variables
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 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:
Autorelease:
self.array = [[[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil] autorelease];
Use the
arrayWithObjects:
class method. Simpler, and also produces an autoreleased object:self.array = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
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];
精彩评论