E-Madd
E-Madd

Reputation: 4582

Why is dealloc for my class not being called?

I have a view controller. The view controller has a retained object called streamController, which is an NSObject subclass that handles all of the data I/O with my server. All is well, except I'm trying to figure out why some things are leaking on said streamController. I drop an NSLog in there and I never see it firing. I'm completely puzzled as to why, because I'm releasing the controller in my dealloc method for my view controller.

from view controller interface...

StreamController *streamController;
@property (nonatomic, retain) StreamController *streamController;

from view controller implementation...

@synthesize streamController;

- (id)init {
    [super init];
    self.streamController = [[StreamController alloc] init];
}

- (void)dealloc {
    NSLog(@"dealloc view controller");
    [streamController release];
    [super dealloc];
}

from StreamController implementation...

- (void)dealloc {
    NSLog(@"dealloc stream controller");
    [super dealloc];
}

this last dealloc NEVER gets called. Why?

Upvotes: 1

Views: 865

Answers (1)

nacho4d
nacho4d

Reputation: 45138

I believe you are just leaking memory, if your property has retain attribute then you should take a look at the following examples:

//A
self.streamController = [[StreamController alloc] init];

//B
StreamController * st = [[StreamController alloc] init];
self.streamController = st;
[st release];

//C
streamController = [[StreamController alloc] init];

if you check retain counts you will see that in A approach your streamController object will have a retainCount of 2, while in B it will be only 1.

Reason:

In A by doing [[StreamController alloc] init]; your object has already a retainCount of 1 before passing it to your property. Then, since you declared it as retain, it will be retained, hence it's retainCount becomes 2.

In B is basically the same but you are releasing the object just after you pass it to your property. Hence, it ends with it's retainCount in 1. (This is what we want)

In C you are not using the property, you are setting the value directly. Hence it will be retained only once. This is fine in this case because is the initialization.

I will suggest to use B or maybe C if you are sure that streamController is nil (like the initialization of your object)

Hope this helps

Upvotes: 3

Related Questions