ios - 初始化弱属性的惯用方法?

标签 ios objective-c

我有一个 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/

相关文章:

ios - NSInternalInconsistencyException,在我关闭下一个场景后崩溃

iOS在一个线程中运行多个操作

objective-c - 为什么我会收到 'Unlock Focus used too many times' 消息?

php - PKPass 无法识别 Passbook Web 服务 URL

ios - 向 DataSource 添加值时,带有 CollectionView 的 IBDesignable 崩溃

ios - 我如何找到 CouchDB 是否已启动并正在运行?

ios - 设置缓存时间 AFNetworking swift 2

ios - 如果蓝牙关闭 iOS,禁用警告对话框

objective-c - 等待 NSStream 响应时替换对 sleep 的调用

c++ - Objective-C 与 C++ 有何不同?