Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

teguh123

macrumors member
Original poster
Mar 22, 2011
62
0
Does that mean that the alloc and release will always be on the same function (with the exception of destructor?)
 
yes. I've never seen the allocator and release in different functions. I always make a separate destructor though.
 
Last edited by a moderator:
No, alloc and release do not always occur in the same function. For example, one object creates another object (and stores a pointer to it) at init time...then at dealloc time, releases it. Very common.
 
Last edited by a moderator:
No, alloc and release do not always occur in the same function. For example, one object creates another object (and stores a pointer to it) at init time...then at dealloc time, releases it. Very common.

To elaborate on this, imagine that you have an object of class Car that needs to access another object of class Wheel for Car's entire life span. You would want to create the Wheel when you create the Car, retain it. And then you release the Wheel when dealloc is called on the Car. Here would be init and dealloc for Class Car.

Code:
@interface Car : NSObject {
    Wheel *wheel_;
}

@end


@implementation Car

- (id)init {
    if((self = [super init])) {
        wheel_ = [[Wheel alloc] init];
    }
    return self;
}

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

@end
 
An additional release that could go along with seepel's example would be in the setter method:

Code:
- (void)setWheel(Wheel *aWheel) {
      if(aWheel != wheel_) {
         [wheel_ release];
         wheel_ = [aWheel retain];
      }
}

This is what the compiler generates for you if you synthesize a retained property.
 
So with the exception of init and dealloc couple, alloc and release are always on the same function.

admanimal sample actually illustrate it. Retain is like alloc in a sense of increasing retain count.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.