OGeek|极客世界-中国程序员成长平台

标题: ios - 苹果代码示例,为什么他们在这里直接访问 ivars? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:46
标题: ios - 苹果代码示例,为什么他们在这里直接访问 ivars?

查看 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方法。



Best Answer-推荐答案


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

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

关于ios - 苹果代码示例,为什么他们在这里直接访问 ivars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962383/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4