我有一个 UIView
子类,它可以操作多个图层。因为 View 层的 sublayers
强烈保留层,所以我的想法是让我自己对它们的引用变弱:
@interface AnchorCell : UICollectionReusableView
@property (weak, nonatomic) CAShapeLayer *link;
@property (weak, nonatomic) CATextLayer *offset;
@end
我可以在初始时进行一定数量的设置。但我最终写了这样的代码:
- (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];
}
我很好奇是否有更好的惯用方法来执行此操作。我喜欢关于上面的内容,是它尽可能地突出显示,我正在设置 link
变量,而不是一些本地 shape
变量,然后我在最后将其设置为 link
。我不喜欢的是,您必须无缘无故地添加局部变量,而 Xcode 会发出警告。
我可以将 addSublayer:
移动到方法的顶部:
- (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;
}
但这也(对我)隐藏了一些东西。没有明确说明 link
已添加为子层。此外,有时,在某些模式下,您必须先对对象进行一定数量的设置,然后才能在别处注册它。
有没有更优雅的方式来做到这一点?或者至少考虑到 ARC 管理的 ObjectiveC 的限制,一种更惯用的方式?
最佳答案
我不认为你应该使属性 strong
只是为了避免使用局部变量(如果属性是 weak
,你需要局部变量).
我认为内存语义(例如 weak
vs strong
vs copy
)应该反射(reflect)功能对象所有权图,而不是花招而已避免使用局部变量。我会将属性保留为 weak
,然后执行显而易见的操作:
CAShapeLayer *shape = [CAShapeLayer layer]; // have to put it in local variable to make it last long enough to get to the sublayer
shape.strokeColor = [[UIColor orangeColor] colorWithAlphaComponent: 1].CGColor;
shape.fillColor = nil;
shape.lineWidth = 3;
shape.masksToBounds = NO;
....
[self.layer addSublayer: shape];
self.link = shape;
就我个人而言,我不认为在一行代码中同时分配 shape
和 _link
的行提高了它的可读性,所以我更喜欢将它们分开,但随心所欲。
此外,我通常建议使用 setter,因为我永远不知道我是否可能有一个自定义 setter 或在将来的某个日期更改内存语义(这里的代码不应该关心那个)。我不止一次不得不重构直接使用 ivar 的代码,因为一些实现细节后来发生了变化,但我还没有后悔使用访问器方法。
关于ios - 初始化弱属性的惯用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514702/