I have a UIView
subclass that manipulates a number of layers. Because the view's layer's sublayers
retains the layers strongly, my thought was to make my own references to them weak:
@interface AnchorCell : UICollectionReusableView
@property (weak, nonatomic) CAShapeLayer *link;
@property (weak, nonatomic) CATextLayer *offset;
@end
I can do a certain amount of setup at init time. But I end up writing code like this:
- (void) initLink {
CAShapeLayer *shape = _link = [CAShapeLayer layer]; // have to put it in local variable to make it last long enough to get to the sublayer
_link.strokeColor = [[UIColor orangeColor] colorWithAlphaComponent: 1].CGColor;
_link.fillColor = nil;
_link.lineWidth = 3;
_link.masksToBounds = NO;
....
[self.layer addSublayer: _link];
}
I'm curious if there's a better idiomatic way to do this. What I like about the above, is that it highlights as much as possible, that I'm setting up the link
variable, instead of some local shape
variable, which I then set to link
at the end. What I don't like about it is that you have to add a local variable for no apparent reason that Xcode warns about.
I could move the addSublayer:
to the top of the method:
- (void) initLink {
CAShapeLayer *shape = [CAShapeLayer layer];
[self.layer addSublayer: shape];
_link = shape;
_link.strokeColor = [[UIColor orangeColor] colorWithAlphaComponent: 1].CGColor;
_link.fillColor = nil;
_link.lineWidth = 3;
_link.masksToBounds = NO;
}
But this hides things (to me) as well. It doesn't make it clear that link
has been added as a sublayer. Also, sometimes, there are patterns where you have to do a certain amount of setup to the object before you register it elsewhere.
Is there a more elegant way of doing this? Or at least a more idiomatic way given the restrictions of ARC managed ObjectiveC?