Should I let go of this property?

I'm a novice newbie and I'm having problems with memory management, I've read Apple's memory management rules, but I need to clarify a bit here, it's pretty simple I guess, but I would like to ask you if I am correct:

Considering 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 correct to issue an Autorelease message to the allocated object in the init method ?, I do it in the Apple doc says that every allocated object should be released by the developer, then I think alloc sets count count count to 1, then property (non-atomic, persistence) adds 1, so keep == 2, then autocompost subtracts 1, and when the dealloc method is called, property1 is freed and stores count == 0, am I right?

+2


source to share


3 answers


You have the right to manage memory, although Apple (and many other people) generally discourage the use of accessors in your initialization methods, because accessories can have side effects beyond just setting an instance variable that your class might not have set to handle yet. And in this case, you don't want auto-updates, since you need ownership of the object.



+6


source


one-way note: in dealloc

you need to free the property before calling [super dealloc]

because it [super dealloc]

ultimately frees the memory of the object, including the memory containing the variable property1

, so it is wrong to refer to that variable after the call [super dealloc]

. It should be:



-(void) dealloc {
 [property1 release];
 [super dealloc];
}

      

+2


source


One of the nice things about using properties is that you can encapsulate all of your "deallocating" behavior regardless of whether your property is set to save, copy, assign, etc:

self.property1 = nil;

      

Personally, I'm used to setting all properties to nil (using self.property, not just accessing the member variable directly) in dealloc, so even if I change the way I manage memory for the member variable, it works correctly.

0


source







All Articles