PDA

View Full Version : You own it, you release it




teguh123
Apr 7, 2011, 10:13 AM
Does that mean that the alloc and release will always be on the same function (with the exception of destructor?)



Small White Car
Apr 7, 2011, 10:33 AM
I don't see how anyone could think otherwise!

drummr
Apr 7, 2011, 10:53 AM
Yes!....wait....No!.....wait......what?:confused:

vincenz
Apr 7, 2011, 10:53 AM
Yes!....wait....No!.....wait......what?:confused:

I'm just as confused by you by this post :confused:

blevins321
Apr 7, 2011, 10:55 AM
yes. I've never seen the allocator and release in different functions. I always make a separate destructor though.

huskerchad
Apr 7, 2011, 11:14 AM
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.

Savage
Apr 7, 2011, 12:08 PM
I'm just as confused by you by this post :confused:Actually, your post is the most confusing post in this thread...

seepel
Apr 7, 2011, 01:05 PM
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.



@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

admanimal
Apr 7, 2011, 01:37 PM
An additional release that could go along with seepel's example would be in the setter method:


- (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.

teguh123
Apr 10, 2011, 02:28 AM
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.