2

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

4

1 回答 1

1

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

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

于 2013-09-23T15:28:52.037 回答