views:

1739

answers:

3

I think that when I add a view as a subview like such:

UIView* view = [[UIView alloc] init];
[self addSubview:view];
[view release];

that it's safe to release the view afterwards...is it the same for a CALayer object? If I create a CALayer using alloc/init, and do:

[self.layer addSublayer:layer];

is it safe to do a release of the layer afterwards?

+3  A: 

Yes. In general if object A needs object B it is object A's responsibility to retain it. So if "self.layer" needs "layer, it will bump the retainCount during addSublayer: , and release layer when it is no longer needed. While there are some exceptions to this, those exceptions tend to be very well documented.

Louis Gerbarg
This seems to be the case. We have our own custom layers so we're doing alloc/init rather than layer, but adjusting our releases seem to have fixed our problems. :)
Jonas
A: 

I agree with Louis. And although it's not really necessary in this case, note that you can always use the retainCount: method to double-check these things in the future. For example:

NSLog(@"Retain count before: %d", [layer retainCount]);
[self.layer addSublayer:layer];
NSLog(@"Retain count after: %d", [layer retainCount]);
Clint Harris
A: 

First of all, you make a new CALayer object using the layer class method rather than alloc/init. Like so:-

CALayer *l = [CALayer layer];
l.frame = CGRectMake(...);
l.position = CGPointMake(...);
l.anchorpoint = CGPointMake(0,0);
l.contents = (id)someCGImageRef;
[self.layer addSublayer:l];

Secondly, this is where you can come unstuck because if you release the CALayer after adding it as a sublayer to your view's main layer, you'll get a crash. Or at least I did and I think it's because the layer class method adds the layer to the autorelease pool, so if you release it yourself you get a double-release and so it gets deallocated even thought he view's main layer is still using it.

U62