R – Should I release this property

memory-managementobjective-c

I'm a objective c newbie, and i'm having a bit of problems with memory management, I've read the apple's memory management policies, however i need a bit of clarification here, this is pretty simple i guess, but i would like to ask you if I'm right:

Given this property:

@interface Test : NSObject {
  NSArray *property1;
}
@property (nonatomic,retain) NSArray* property1;
@end

...

//And its implementation:
@implementation Test
@synthetize property1;
-(id) init {
  if (self=[super init]) {
    self.property1=[[[NSArray alloc] initWithCapacity:5] autorelease];
  }
  return self;
}
-(void) dealloc {
  [super dealloc];
  [property1 release];
}

@end

Is it right to issue an Autorelease message to the allocated object in the init method?, i do this cause in apple's document, says that every allocated object should be released by the developer, then, I think, alloc sets retain count to 1, then the property (nonatomic, retain) adds 1, so retain==2, then autorelease substracts 1, and when the dealloc method is called, property1 is released and retain count==0, am I right?

Best Solution

You have your memory management right, though Apple (and a lot of other people) generally recommend not using accessors in your initialization methods because accessors can have side effects beyond simply setting an instance variable that your class might not be set up to handle yet. And in that case, you wouldn't want to autorelease since you'd want ownership of the object.

Related Question