1

Usually when I create an object and assign it to an instance variable I alloc a temp object, call the iVar setter to retain the object and then release the temp object. However I was looking at init this morning and noticed that if I simply assign the iVar directly, its retained by the alloc whilst also being released correctly when either the setter is called or dealloc is executed. I am just curious if I am understand this correctly?

@property(nonatomic, retain) CLLocationManager *locationManager;

.

@synthesize locationManager;

// VERSION 001
- (id)init {
    self = [super init];
    if(self) {
        CLLocationManager *tempManager = [[CLLocationManager alloc] init];
        [self setLocationManager:tempManager];
        [tempManager release];  
    }
    return self;
}

// VERSION 002
- (id)init {
    self = [super init];
    if(self) {
        locationManager = [[CLLocationManager alloc] init]; 
    }
    return self;
}

- (void)dealloc {
    [locationManager release];
    [super dealloc];
}
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

2 Answers2

2

As far as the memory management goes both solutions are fine. But you might want to prefer the direct access in init and dealloc, see this related question.

Community
  • 1
  • 1
zoul
  • 102,279
  • 44
  • 260
  • 354
  • I was aware of not using setters in dealloc from a previous question, its good to know that I should not be using them in init as well. So would I be right in saying that for init & delloc directly assign the iVars like v_002. For other methods its best to go with alloc object, use the setter to assign the iVar & finally release the object. – fuzzygoat Nov 25 '10 at 15:34
1

Version 002 is the Apple approved answer because the pitfalls of using an accessor in init are theoretically worse. Basically, a subclass could choose to override your accessor and then you'd be sending a message to a subclass object that is not yet initialised.

However, everywhere else except init and dealloc, use version 001.

JeremyP
  • 84,577
  • 15
  • 123
  • 161