在ObjC实现文件中声明的实例变量 [英] Instance variables declared in ObjC implementation file

查看:133
本文介绍了在ObjC实现文件中声明的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在观看WWDC ARC的介绍视频,在某些Apple工程师谈论Stack示例之前,我发现在ObjC中从未见过的东西.

I was watching the WWDC ARC introduction video and I saw something I've never seen in ObjC before when some Apple engineer talked about a Stack example.

以下代码用于ARC的堆栈示例:

The following code was used for a stack example with ARC:

@implementation Stack 
{ 
    // instance variable declared in implementation context
    NSMutableArray *_array; 
}

- (id)init 
{
   if (self = [super init])
      _array = [NSMutableArray array];
   return self;
}

- (void)push:(id)x 
{
   [_array addObject:x];
}

- (id)pop 
{
   id x = [_array lastObject];
   [_array removeLastObject];
   return x;
}

@end

请注意在 @implementation 指令之后声明的实例变量.

Please note the instance variable declared right after the @implementation directive.

现在让我惊讶的是,实例变量实际上可以在实现文件中声明,而不必是静态变量.我的问题如下:

Now the thing that surprised me, is that an instance variable could actually be declared in the implementation file, without it being a static variable. My questions would be the following:

  • 这是iOS 5 SDK中引入的一些新结构吗?或者这种可能性已经存在很长时间了?
  • 如果不希望在对象外部访问实例变量,那么在实现中声明实例变量是否是一种好习惯?似乎比使用@private指令更干净.

推荐答案

这确实是一项新的语言功能,如果您必须声明自己的ivars(而不是简单地声明属性并让编译器为您生成ivars),那是一个很好的选择实践.理论上,您的头文件应该只公开类的公共接口;其他所有东西都属于实现.

This is indeed a new language feature, and if you must declare your ivars (rather than simply declaring properties and letting the compiler generate ivars for you) it's a good practice. Your header files in theory should only expose public interface for your classes; everything else belongs in the implementation.

一个警告是,实现文件ivars对子类不可见,如果您手动生成了需要子类化的setter和getter,这有时会有些尴尬.

One caveat is that implementation-file ivars are not visible to subclasses, which can occasionally be a little bit awkward if you have manually generated setters and getters that you need to subclass.

这篇关于在ObjC实现文件中声明的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆