marlu
marlu

Reputation: 1

confusion about retain and release issues

i'm wondering about the behaviour of the CALayer class and its reference counter. Please see the following two code snippets:

First:

CALayer *layer = [[CALayer alloc] init];
NSLog(@"retain count: %d",  [layer retainCount]); // log: retain count: 1
[layer release]; // no problem so far

[layer release]; // this leads to a crash as expected

Second:

CALayer *layer = [[CALayer alloc] init];

NSLog(@"retain count: %d",  [layer retainCount]); // log: retain count: 1
layer.opaque = YES; //increases the retain count, WHY?!?
NSLog(@"retain count: %d",  [layer retainCount]); // log: retain count: 2

[layer release]; // no problem so far

[layer release]; // this leads NOT to a crash as expected

In the first snippet, everything occurs as I expect it, also the crash (zombie ...) at the second release message.

In the second one, unexpected things happen. Calling any message after init (e.g. layer.opaque = YES) increases the retain counter by one, but only the first call of a message. So the retain counter is allways 1 to high. To proof that this is not just a number problem, I used the second release. The layer will only be freed from memory after the second release.

The behaviour of this could also be produced with autorelease.

So, why does a message to the layer increase its retain count? Did I miss some Infromation about retain and release issues?

Thanks in advance

Marco

Upvotes: 0

Views: 336

Answers (2)

bbum
bbum

Reputation: 162722

retainCount is useless. Don't call it.

So, why does a message to the layer increase its retain count? Did I miss some Infromation about retain and release issues?

Because it is an internal implementation detail of the framework.

If you balance your retains and releases, then your objects will be deallocated correctly.

If an object is sticking around for too long (long enough to cause your app to crash), it is because your code isn't cleaning things up correctly. In the case of layers, the most common cause is failure to remove a layer from your layer/view hierarchy when your app is finished with it.

Upvotes: 1

Terry Wilcox
Terry Wilcox

Reputation: 9040

You missed the part about not using retain count for debugging. Don't do it. The object's retain count is none of your business.

Concentrate on your ownership of the object. If you own it (retain, alloc, copy, or new), you have to release it, once.

If an object sticks around after you've done your retain/release cycle properly, that means something else owns it and is responsible for releasing it. If you release it again, you've broken that ownership, which can only end tragically.

So if layer.opaque = YES increases the retain count, let it. Don't worry about it. You've fulfilled your obligation and doing anything else will unbalance the retain/release cycle somewhere else.

Upvotes: 1

Related Questions