在Objective-C中定义私有变量的最佳方法

Mak*_*tsu 32 objective-c

我想在MyClass.m文件中定义私有实例变量.在我看来,有两种方法可以做到:

  1. 使用类扩展

    @interface HelloViewController ()
    {
         int value;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在@implementation部分中定义

    @implementation HelloViewController
    {
        int value;
    }
    
    Run Code Online (Sandbox Code Playgroud)

哪个更好?

我认为最近Apple的编码风格是使用类扩展吗?

例如,由Master-Detail Application Template生成的MasterViewController.m

@interface MasterViewController () {
    NSMutableArray *_objects;
}
@end
Run Code Online (Sandbox Code Playgroud)

Dru*_*erB 50

"现代Objective-C"方法是在您的实现块中声明它们,如下所示:

@implementation ClassName {
    int privateInteger;
    MyObject *privateObject;
}

// method implementations etc...

@end
Run Code Online (Sandbox Code Playgroud)

见这早些时候我的岗位更多的细节.


Ano*_*dya 8

@interface HelloViewController ()
{
    @private     //optional, this is old style
    int vale;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你正在创建一个库,理论上没有人会知道你没有在头文件中声明的任何方法.

复制自:如何制作一个真正的私有实例变量?


在@implementation中声明实例变量是Obj-C的一个新功能,这就是为什么你在@interface中看到很多带有它们的代码 - 没有别的选择.

如果您正在使用支持在实现中声明实例变量的编译器来声明它们,则可能存在最佳默认值 - 只有在需要其他人访问时才将它们放在接口中.

在实现中声明的实例变量被隐式隐藏(实际上是私有的)并且不能更改可见性 - @ public,@ protected和@private不会产生编译器错误(至少使用当前的Clang)但会被忽略.

复制自:@interface或@implementation中的私有ivar