【问题标题】:Apple code example, why are they accessing ivars directly here?苹果代码示例,为什么他们在这里直接访问 ivars?
【发布时间】:2013-09-23 14:49:49
【问题描述】:

查看 MultipeerGroupChat 的 Apple 示例应用程序(特别是 MainViewController.m):

https://developer.apple.com/library/ios/samplecode/MultipeerGroupChat/Listings/AdhocGroupChat_MainViewController_m.html#//apple_ref/doc/uid/DTS40013691-AdhocGroupChat_MainViewController_m-DontLinkElementID_8

该示例包含以下代码分配属性:

@property (retain, nonatomic) NSMutableArray *transcripts;
@property (retain, nonatomic) NSMutableDictionary *imageNameIndex;

然后在 viewDidLoad 中初始化它们:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Init transcripts array to use as table view data source
    _transcripts = [NSMutableArray new];
    _imageNameIndex = [NSMutableDictionary new];

    ---SNIP---

他们直接分配给 ivars _transcripts 和 _imageNameIndex 有什么原因吗?我认为正确的约定要求您始终使用属性来访问变量,除非您在 init 方法中......事实上,在 viewDidLoad 方法中,作者确实使用属性来分配其他变量:

self.displayName = [defaults objectForKey:kNSDefaultDisplayName];

self.serviceType = [defaults objectForKey:kNSDefaultServiceType];

我知道过去,Apple 示例代码有时会偏离良好的编码习惯,所以我想知道这是否只是草率的编码,或者是否有正当理由在非初始化中直接访问这两个 ivars方法。

【问题讨论】:

  • 除了避免使用二传手之外,没有其他明显的原因。与最佳做法略有不同,但并非真正“错误”。

标签: ios objective-c ivar


【解决方案1】:

对于如何访问属性没有明确的方法。鉴于这只是一个演示项目,写这篇文章的工程师可能知道该项目的范围允许一些捷径。

这里的做法没有错,只是不推荐。

【讨论】:

  • Apple 示例代码因违反最佳实践而臭名昭著。他们也几乎没有模型类。每隔一段时间,你就会看到类似“你永远不会这样做……”这样的评论
  • 使用 iVars 初始化属性实际上是一个不错的主意,但应限于-initWith...-Methods,因此不会调用触发 KVO 的设置器,或者如果子类覆盖设置器,它可能发现自己处于部分初始化状态。
  • 感谢您的确认,这就是我的怀疑。
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 2011-02-20
  • 2021-12-01
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
相关资源
最近更新 更多